From ef8de4ddd6c60a57f0848020d88b474d41eefc7d Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:00:18 +0200 Subject: [PATCH 01/13] feat: add shared oxlint config and rules --- .github/workflows/lint.yml | 6 +- .yarnrc.yml | 3 + apps/brunch-agent/package.json | 4 +- apps/petrinaut-website/package.json | 4 +- libs/@hashintel/brunch-agent/package.json | 4 +- libs/@hashintel/ds-icons/package.json | 4 +- libs/@hashintel/petrinaut-cli/package.json | 4 +- libs/@hashintel/petrinaut-core/package.json | 4 +- libs/@hashintel/petrinaut/package.json | 4 +- libs/@hashintel/refractive/package.json | 4 +- libs/@local/flue-aisdk-transport/package.json | 4 +- libs/@local/oxlint/LICENSE.md | 607 ++++++++++++++++++ libs/@local/oxlint/README.md | 65 ++ .../@local/oxlint/docs/task-dependencies.json | 35 + libs/@local/oxlint/oxlint.config.ts | 10 + libs/@local/oxlint/package.json | 40 ++ libs/@local/oxlint/src/index.test.ts | 54 ++ libs/@local/oxlint/src/index.ts | 317 +++++++++ libs/@local/oxlint/src/lib/casing.test.ts | 53 ++ libs/@local/oxlint/src/lib/casing.ts | 128 ++++ libs/@local/oxlint/src/lib/kind-affixes.ts | 61 ++ libs/@local/oxlint/src/lib/reserved-names.ts | 63 ++ libs/@local/oxlint/src/rules/index.ts | 24 + .../src/rules/naming-conventions.test.ts | 357 ++++++++++ .../oxlint/src/rules/naming-conventions.ts | 474 ++++++++++++++ .../src/rules/no-property-modifiers.test.ts | 192 ++++++ .../oxlint/src/rules/no-property-modifiers.ts | 472 ++++++++++++++ .../src/rules/prefer-options-object.test.ts | 66 ++ .../oxlint/src/rules/prefer-options-object.ts | 116 ++++ .../rules/require-rule-change-comment.test.ts | 124 ++++ .../src/rules/require-rule-change-comment.ts | 180 ++++++ ...-safety-comment-for-type-assertion.test.ts | 87 +++ ...quire-safety-comment-for-type-assertion.ts | 130 ++++ .../rules/require-suppression-comment.test.ts | 65 ++ .../src/rules/require-suppression-comment.ts | 66 ++ libs/@local/oxlint/tsconfig.json | 15 + libs/@local/oxlint/tsdown.config.ts | 9 + libs/@local/oxlint/turbo.json | 18 + libs/@local/oxlint/vitest.config.ts | 9 + libs/@local/petrinaut-arch-docs/package.json | 2 +- libs/@local/pi-faux-providers/package.json | 4 +- package.json | 2 + .../petrinaut-brunch-integration/package.json | 4 +- turbo.json | 7 + yarn.lock | 453 ++++++++++++- 45 files changed, 4305 insertions(+), 49 deletions(-) create mode 100644 libs/@local/oxlint/LICENSE.md create mode 100644 libs/@local/oxlint/README.md create mode 100644 libs/@local/oxlint/docs/task-dependencies.json create mode 100644 libs/@local/oxlint/oxlint.config.ts create mode 100644 libs/@local/oxlint/package.json create mode 100644 libs/@local/oxlint/src/index.test.ts create mode 100644 libs/@local/oxlint/src/index.ts create mode 100644 libs/@local/oxlint/src/lib/casing.test.ts create mode 100644 libs/@local/oxlint/src/lib/casing.ts create mode 100644 libs/@local/oxlint/src/lib/kind-affixes.ts create mode 100644 libs/@local/oxlint/src/lib/reserved-names.ts create mode 100644 libs/@local/oxlint/src/rules/index.ts create mode 100644 libs/@local/oxlint/src/rules/naming-conventions.test.ts create mode 100644 libs/@local/oxlint/src/rules/naming-conventions.ts create mode 100644 libs/@local/oxlint/src/rules/no-property-modifiers.test.ts create mode 100644 libs/@local/oxlint/src/rules/no-property-modifiers.ts create mode 100644 libs/@local/oxlint/src/rules/prefer-options-object.test.ts create mode 100644 libs/@local/oxlint/src/rules/prefer-options-object.ts create mode 100644 libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts create mode 100644 libs/@local/oxlint/src/rules/require-rule-change-comment.ts create mode 100644 libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.test.ts create mode 100644 libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.ts create mode 100644 libs/@local/oxlint/src/rules/require-suppression-comment.test.ts create mode 100644 libs/@local/oxlint/src/rules/require-suppression-comment.ts create mode 100644 libs/@local/oxlint/tsconfig.json create mode 100644 libs/@local/oxlint/tsdown.config.ts create mode 100644 libs/@local/oxlint/turbo.json create mode 100644 libs/@local/oxlint/vitest.config.ts diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index db5725bf6b2..05e6c59892a 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -42,7 +42,7 @@ jobs: # can differ in what they consider affected. set -o pipefail PACKAGES=$( - .github/scripts/affected-packages.sh codegen lint:eslint lint:tsc lint:clippy lint:ruff format:ruff check:ty lint:tach lint:deptry | + .github/scripts/affected-packages.sh codegen lint:eslint lint:oxlint lint:tsc lint:clippy lint:ruff format:ruff check:ty lint:tach lint:deptry | jq --compact-output ' .include |= map(select(.name != "hash-python")) | .name = [.include[].name] @@ -148,6 +148,10 @@ jobs: if: always() && matrix['lint:eslint'] != null run: turbo run lint:eslint --filter "${{ matrix.name }}" + - name: Run Oxlint + if: always() && matrix['lint:oxlint'] != null + run: turbo run lint:oxlint --filter "${{ matrix.name }}" + - name: Run TSC if: always() && matrix['lint:tsc'] != null run: turbo run lint:tsc --filter "${{ matrix.name }}" diff --git a/.yarnrc.yml b/.yarnrc.yml index 0093a244f8b..9fca1c6a007 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -50,6 +50,9 @@ catalog: "@fast-check/vitest": "0.5.0" "@tsconfig/bases": "1.0.28" "@types/node": "22.18.13" + oxlint: "1.86.0" + "@oxlint/plugins": "1.86.0" + oxlint-tsgolint: "7.0.2003" catalogs: typescript6: diff --git a/apps/brunch-agent/package.json b/apps/brunch-agent/package.json index c0a7d4abc63..bb116584105 100644 --- a/apps/brunch-agent/package.json +++ b/apps/brunch-agent/package.json @@ -64,8 +64,8 @@ "@valibot/to-json-schema": "1.7.1", "ai": "6.0.286", "dependency-cruiser": "18.0.0", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "typescript": "catalog:", "vite": "catalog:", "vitest": "catalog:", diff --git a/apps/petrinaut-website/package.json b/apps/petrinaut-website/package.json index 12bbd81b652..78dea05ec43 100644 --- a/apps/petrinaut-website/package.json +++ b/apps/petrinaut-website/package.json @@ -56,8 +56,8 @@ "jsdom": "24.1.3", "monaco-editor": "0.55.1", "oxc-transform-react": "0.152.0", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "sharp": "0.35.5", "typescript": "catalog:", "vite": "catalog:", diff --git a/libs/@hashintel/brunch-agent/package.json b/libs/@hashintel/brunch-agent/package.json index 9c637512e67..dcea9bab4b3 100644 --- a/libs/@hashintel/brunch-agent/package.json +++ b/libs/@hashintel/brunch-agent/package.json @@ -40,8 +40,8 @@ "@local/tsconfig": "workspace:*", "@tsconfig/bases": "catalog:", "@types/node": "catalog:", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "typescript": "catalog:", "vite": "catalog:", "vitest": "catalog:" diff --git a/libs/@hashintel/ds-icons/package.json b/libs/@hashintel/ds-icons/package.json index 012a80a67ca..dfd9e5642a3 100644 --- a/libs/@hashintel/ds-icons/package.json +++ b/libs/@hashintel/ds-icons/package.json @@ -59,8 +59,8 @@ "@vitejs/plugin-react": "6.1.1", "jsdom": "24.1.3", "oxc-transform-react": "0.152.0", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "react": "19.2.6", "react-dom": "19.2.6", "rolldown": "1.2.6", diff --git a/libs/@hashintel/petrinaut-cli/package.json b/libs/@hashintel/petrinaut-cli/package.json index 8a7367d5a92..7ab7f807676 100644 --- a/libs/@hashintel/petrinaut-cli/package.json +++ b/libs/@hashintel/petrinaut-cli/package.json @@ -27,8 +27,8 @@ "@tsconfig/bases": "catalog:", "@types/node": "catalog:", "oxfmt": "0.71.0", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "tsx": "catalog:", "typescript": "catalog:", "vite": "catalog:", diff --git a/libs/@hashintel/petrinaut-core/package.json b/libs/@hashintel/petrinaut-core/package.json index 8af6f2df327..23674d09cc6 100644 --- a/libs/@hashintel/petrinaut-core/package.json +++ b/libs/@hashintel/petrinaut-core/package.json @@ -119,8 +119,8 @@ "@types/react": "19.2.14", "@typescript/typescript6": "catalog:", "@webgpu/types": "0.1.71", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "pyodide": "314.0.6", "rolldown": "1.2.6", "rolldown-plugin-dts": "0.28.3", diff --git a/libs/@hashintel/petrinaut/package.json b/libs/@hashintel/petrinaut/package.json index a30e22ab10a..69e1cced678 100644 --- a/libs/@hashintel/petrinaut/package.json +++ b/libs/@hashintel/petrinaut/package.json @@ -114,8 +114,8 @@ "@vitejs/plugin-react": "6.1.1", "jsdom": "24.1.3", "oxc-transform-react": "0.152.0", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "react": "19.2.6", "react-dom": "19.2.6", "rolldown": "1.2.6", diff --git a/libs/@hashintel/refractive/package.json b/libs/@hashintel/refractive/package.json index 6cda2811cc6..920880e41cc 100644 --- a/libs/@hashintel/refractive/package.json +++ b/libs/@hashintel/refractive/package.json @@ -41,8 +41,8 @@ "@vitejs/plugin-react": "6.1.1", "jsdom": "24.1.3", "oxc-transform-react": "0.152.0", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "react": "19.2.6", "react-dom": "19.2.6", "rolldown": "1.2.6", diff --git a/libs/@local/flue-aisdk-transport/package.json b/libs/@local/flue-aisdk-transport/package.json index b3f53a16ab1..1a42a54ce9a 100644 --- a/libs/@local/flue-aisdk-transport/package.json +++ b/libs/@local/flue-aisdk-transport/package.json @@ -34,8 +34,8 @@ "@local/tsconfig": "workspace:*", "@tsconfig/bases": "catalog:", "@types/node": "catalog:", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "typescript": "catalog:", "valibot": "1.4.2", "vite": "catalog:", diff --git a/libs/@local/oxlint/LICENSE.md b/libs/@local/oxlint/LICENSE.md new file mode 100644 index 00000000000..c7d627721e2 --- /dev/null +++ b/libs/@local/oxlint/LICENSE.md @@ -0,0 +1,607 @@ +GNU Affero General Public License +================================= + +_Version 3, 19 November 2007_ +_Copyright © 2007 Free Software Foundation, Inc. <>_ + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +## Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: **(1)** assert copyright on the software, and **(2)** offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions + +“This License” refers to version 3 of the GNU Affero General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this +License. Each licensee is addressed as “you”. “Licensees” and +“recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a “modified version” of the +earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based +on the Program. + +To “propagate” a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” +to the extent that it includes a convenient and prominently visible +feature that **(1)** displays an appropriate copyright notice, and **(2)** +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code + +The “source code” for a work means the preferred form of the work +for making modifications to it. “Object code” means any non-source +form of a work. + +A “Standard Interface” means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other +than the work as a whole, that **(a)** is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and **(b)** serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +“Major Component”, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +### 2. Basic Permissions + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +### 4. Conveying Verbatim Copies + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + +* **a)** The work must carry prominent notices stating that you modified +it, and giving a relevant date. +* **b)** The work must carry prominent notices stating that it is +released under this License and any conditions added under section 7. +This requirement modifies the requirement in section 4 to +“keep intact all notices”. +* **c)** You must license the entire work, as a whole, under this +License to anyone who comes into possession of a copy. This +License will therefore apply, along with any applicable section 7 +additional terms, to the whole of the work, and all its parts, +regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not +invalidate such permission if you have separately received it. +* **d)** If the work has interactive user interfaces, each must display +Appropriate Legal Notices; however, if the Program has interactive +interfaces that do not display Appropriate Legal Notices, your +work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +“aggregate” if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + +* **a)** Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by the +Corresponding Source fixed on a durable physical medium +customarily used for software interchange. +* **b)** Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by a +written offer, valid for at least three years and valid for as +long as you offer spare parts or customer support for that product +model, to give anyone who possesses the object code either **(1)** a +copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical +medium customarily used for software interchange, for a price no +more than your reasonable cost of physically performing this +conveying of source, or **(2)** access to copy the +Corresponding Source from a network server at no charge. +* **c)** Convey individual copies of the object code with a copy of the +written offer to provide the Corresponding Source. This +alternative is allowed only occasionally and noncommercially, and +only if you received the object code with such an offer, in accord +with subsection 6b. +* **d)** Convey the object code by offering access from a designated +place (gratis or for a charge), and offer equivalent access to the +Corresponding Source in the same way through the same place at no +further charge. You need not require recipients to copy the +Corresponding Source along with the object code. If the place to +copy the object code is a network server, the Corresponding Source +may be on a different server (operated by you or a third party) +that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the +Corresponding Source, you remain obligated to ensure that it is +available for as long as needed to satisfy these requirements. +* **e)** Convey the object code using peer-to-peer transmission, provided +you inform other peers where the object code and Corresponding +Source of the work are being offered to the general public at no +charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A “User Product” is either **(1)** a “consumer product”, which means any +tangible personal property which is normally used for personal, family, +or household purposes, or **(2)** anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, “normally used” refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms + +“Additional permissions” are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + +* **a)** Disclaiming warranty or limiting liability differently from the +terms of sections 15 and 16 of this License; or +* **b)** Requiring preservation of specified reasonable legal notices or +author attributions in that material or in the Appropriate Legal +Notices displayed by works containing it; or +* **c)** Prohibiting misrepresentation of the origin of that material, or +requiring that modified versions of such material be marked in +reasonable ways as different from the original version; or +* **d)** Limiting the use for publicity purposes of names of licensors or +authors of the material; or +* **e)** Declining to grant rights under trademark law for use of some +trade names, trademarks, or service marks; or +* **f)** Requiring indemnification of licensors and authors of that +material by anyone who conveys the material (or modified versions of +it) with contractual assumptions of liability to the recipient, for +any liability that these contractual assumptions directly impose on +those licensors and authors. + +All other non-permissive additional terms are considered “further +restrictions” within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +### 8. Termination + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated **(a)** +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and **(b)** permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents + +A “contributor” is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, “control” includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To “grant” such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either **(1)** cause the Corresponding Source to be so +available, or **(2)** arrange to deprive yourself of the benefit of the +patent license for this particular work, or **(3)** arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. “Knowingly relying” means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is “discriminatory” if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license **(a)** in connection with copies of the covered work +conveyed by you (or copies made from those copies), or **(b)** primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +### 13. Remote Network Interaction; Use with the GNU General Public License + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +### 14. Revised Versions of this License + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License “or any later version” applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +### 16. Limitation of Liability + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16 + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. diff --git a/libs/@local/oxlint/README.md b/libs/@local/oxlint/README.md new file mode 100644 index 00000000000..b798e5cbbff --- /dev/null +++ b/libs/@local/oxlint/README.md @@ -0,0 +1,65 @@ +# Shared lint configuration + +Strict, type-aware Oxlint configuration for TypeScript packages, intended to become the repository default. Package-specific exceptions override the shared rules. Current tuning covers vanilla TypeScript, Effect and Vitest consumers. React and Next selections remain provisional. The policy will change as more packages migrate. + +```ts +import { createConfig, defineConfig } from "@local/oxlint"; + +export default defineConfig({ + extends: [ + createConfig({ + runtime: "node", + frameworks: ["vitest", "effect"], + ignorePatterns: ["generated/**"], + }), + ], + rules: { + "eslint/no-console": "off", // This CLI writes results to stdout. + }, +}); +``` + +Build the package before importing it. `createConfig` accepts a required `runtime` of `node` or `browser`. Its optional `frameworks` array selects `react`, `next`, `vitest` or `effect`. Use Oxlint's `defineConfig` for package-specific rules and overrides. + +The React and Next selections enable their native plugins. Vitest adds test rules and file overrides for runtime and type tests under `src`. Effect extends the strict native Effect preset and allows its namespace imports and functional composition conventions. + +`additionalRestrictedTypes` adds messages for restricted types without replacing the built-in entries for `object`, `unknown` and `Function`. An attempt to replace one of those entries throws. `ignorePatterns` passes the package's exclusion globs to Oxlint. + +## Repository rules + +The `hash` plugin enforces naming conventions, including mapped type parameters. Its naming fixes update references and avoid name collisions. Other rules cover JavaScript visibility and options-object parameters. Type assertions and individual lint suppressions require explanations. + +The default `hash/require-rule-change-comment` rule requires an inline explanation beside a literal severity setting. For tuple settings, put the comment beside the first element: + +```ts +"no-magic-numbers": [ + "deny", // These small constants are conventional indices and bounds. + { ignore: [-2, -1, 0, 1, 2] }, +], +``` + +The check recognizes literal `rules` objects, `rules` variable initializers and `defineRules` calls in Oxlint configuration modules. Computed settings and inherited presets remain outside its analysis. An explanation covers the complete setting, including options, without requiring a comparison with upstream defaults. + +A comment records an author's justification. These rules check for an explanation. A reviewer must judge whether it supports the assertion or exception. + +## Preparation and checks + +The Effect rules require a patched Oxlint binary. From the repository root, run: + +```sh +yarn prepare:oxlint +``` + +This patches Oxlint without replacing TypeScript or adding an install hook. The Turbo build task runs preparation without caching it: build artifacts cannot restore changes inside `node_modules`. + +Run the package checks with: + +```sh +yarn workspace @local/oxlint build +yarn workspace @local/oxlint lint:tsc +yarn workspace @local/oxlint lint:oxlint +yarn workspace @local/oxlint lint:format +yarn workspace @local/oxlint test:unit +``` + +Packages expose a `lint:oxlint` task alongside any existing `lint:eslint` task. The root Turbo task and lint workflow run it for affected packages. diff --git a/libs/@local/oxlint/docs/task-dependencies.json b/libs/@local/oxlint/docs/task-dependencies.json new file mode 100644 index 00000000000..f2eebfa510d --- /dev/null +++ b/libs/@local/oxlint/docs/task-dependencies.json @@ -0,0 +1,35 @@ +{ + "package": "@local/oxlint", + "dependencies": [ + "@local/tsconfig" + ], + "tasks": { + "build": { + "dependsOn": [ + "prepare:oxlint" + ] + }, + "lint:oxlint": { + "dependsOn": [ + "build" + ] + }, + "lint:tsc": { + "dependsOn": [ + "build" + ] + }, + "prepare:oxlint": { + "dependsOn": [], + "cache": false + }, + "test:unit": { + "dependsOn": [ + "build" + ], + "env": [ + "TEST_COVERAGE" + ] + } + } +} diff --git a/libs/@local/oxlint/oxlint.config.ts b/libs/@local/oxlint/oxlint.config.ts new file mode 100644 index 00000000000..225afa6cf31 --- /dev/null +++ b/libs/@local/oxlint/oxlint.config.ts @@ -0,0 +1,10 @@ +import { createConfig, defineConfig } from "@local/oxlint"; + +export default defineConfig({ + extends: [ + createConfig({ + frameworks: ["vitest"], + runtime: "node", + }), + ], +}); diff --git a/libs/@local/oxlint/package.json b/libs/@local/oxlint/package.json new file mode 100644 index 00000000000..2660616ec57 --- /dev/null +++ b/libs/@local/oxlint/package.json @@ -0,0 +1,40 @@ +{ + "name": "@local/oxlint", + "version": "0.0.0-private", + "private": true, + "description": "Composable, reviewed Oxlint configuration profiles", + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./rules": { + "types": "./dist/rules/index.d.ts", + "default": "./dist/rules/index.js" + } + }, + "scripts": { + "build": "tsdown", + "lint:format": "oxfmt --check --config ../../../oxfmt.config.ts .", + "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", + "lint:tsc": "tsc --noEmit", + "prepare:oxlint": "effect-tsgo patch --no-typescript --oxlint", + "test:unit": "vitest run" + }, + "dependencies": { + "@effect/tsgo": "0.47.1", + "@oxlint/plugins": "catalog:", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:" + }, + "devDependencies": { + "@local/tsconfig": "workspace:*", + "@tsconfig/bases": "catalog:", + "@types/node": "catalog:", + "tsdown": "0.23.0", + "typescript": "catalog:", + "vite": "catalog:", + "vitest": "catalog:" + } +} diff --git a/libs/@local/oxlint/src/index.test.ts b/libs/@local/oxlint/src/index.test.ts new file mode 100644 index 00000000000..bb5aacad36d --- /dev/null +++ b/libs/@local/oxlint/src/index.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, test } from "vitest"; + +import { createConfig } from "./index.js"; + +describe("createConfig", () => { + test("strict_defaults", () => { + expect.hasAssertions(); + + const config = createConfig({ runtime: "node" }); + + expect(config.categories).toStrictEqual({ + correctness: "deny", + nursery: "deny", + pedantic: "deny", + perf: "deny", + restriction: "deny", + style: "deny", + suspicious: "deny", + }); + expect(config.options?.typeAware).toBe(true); + expect(config.rules?.["hash/require-rule-change-comment"]).toBe("deny"); + }); + + test("vitest_boolean_matchers", () => { + expect.hasAssertions(); + + const config = createConfig({ runtime: "node", frameworks: ["vitest"] }); + + expect(config.rules?.["vitest/prefer-to-be-falsy"]).toBe("off"); + expect(config.rules?.["vitest/prefer-to-be-truthy"]).toBe("off"); + }); + + test("ignore_patterns", () => { + expect.hasAssertions(); + + const config = createConfig({ + ignorePatterns: ["generated/**"], + runtime: "node", + }); + + expect(config.ignorePatterns).toStrictEqual(["generated/**"]); + }); + + test.each(["unknown", "object"])("reserved_type_%s", (typeName) => { + expect.hasAssertions(); + + expect(() => + createConfig({ + additionalRestrictedTypes: { [typeName]: "Override" }, + runtime: "node", + }), + ).toThrow(`Cannot override the built-in restriction for "${typeName}".`); + }); +}); diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts new file mode 100644 index 00000000000..a85344aec1f --- /dev/null +++ b/libs/@local/oxlint/src/index.ts @@ -0,0 +1,317 @@ +import { URL, fileURLToPath } from "node:url"; + +import { strict as effectStrict } from "@effect/tsgo/oxlint-presets"; +import { defineConfig } from "oxlint"; + +import plugin from "./rules/index.js"; + +import type { AllowWarnDeny, DummyRuleMap, OxlintConfig } from "oxlint"; + +export { defineConfig } from "oxlint"; +export type Framework = "react" | "next" | "vitest" | "effect"; +export type Runtime = "node" | "browser"; + +type RestrictedTypeRule = NonNullable< + NonNullable["typescript/no-restricted-types"] +>; +type RestrictedTypes = NonNullable< + Exclude[1]["types"] +>; + +const defaultRestrictedTypes = { + object: + "Prefer a domain type or a useful generic relationship, or justify this broad contract.", + unknown: "Preserve known type information, or justify this unknown boundary.", + Function: "Prefer a named function over an anonymous function.", +} satisfies RestrictedTypes; + +type AdditionalRestrictedTypes = Readonly & { + readonly [TypeName in keyof typeof defaultRestrictedTypes]?: never; +}; + +export interface Options { + readonly runtime: Runtime; + + /** Adds restrictions without replacing built-in entries. Duplicate keys throw. */ + readonly additionalRestrictedTypes?: AdditionalRestrictedTypes; + readonly frameworks?: readonly Framework[]; + readonly ignorePatterns?: readonly string[]; +} + +type Overrides = NonNullable; +type LintPlugins = NonNullable; + +type Env = NonNullable; + +type Extends = NonNullable; + +const defineRules = (rules: DummyRuleMap): DummyRuleMap => rules; +const defineOverride = (override: Overrides[number]): Overrides[number] => + override; + +// oxlint-disable-next-line max-lines-per-function -- no logic, only configuration +export const createConfig = (options: Options): OxlintConfig => { + const additionalRestrictedTypes = options.additionalRestrictedTypes ?? {}; + for (const typeName of Object.keys(defaultRestrictedTypes)) { + if (Object.hasOwn(additionalRestrictedTypes, typeName)) { + throw new Error( + `Cannot override the built-in restriction for "${typeName}".`, + ); + } + } + + const plugins: LintPlugins = [ + "eslint", + "typescript", + "import", + "unicorn", + "oxc", + "jsdoc", + "promise", + ]; + const extend: Extends = []; + const env: Env = { builtin: true, es2026: true }; + const rules: DummyRuleMap = {}; + const overrides: Overrides = [ + { + files: ["**/*.config.ts"], + rules: { + "import/no-default-export": "off", // config files always use `defineConfig` with a default export + }, + }, + ]; + + switch (options.runtime) { + case "node": { + env["node"] = true; + break; + } + case "browser": { + env["browser"] = true; + break; + } + } + + for (const framework of options.frameworks ?? []) { + switch (framework) { + case "react": { + plugins.push("react", "react-perf", "jsx-a11y"); + break; + } + case "next": { + plugins.push("nextjs", "react-perf", "jsx-a11y"); + break; + } + case "vitest": { + plugins.push("vitest"); + Object.assign( + rules, + defineRules({ + "vitest/consistent-test-it": ["deny", { withinDescribe: "test" }], // Use the same declaration name inside and outside describe blocks. + "vitest/no-importing-vitest-globals": "off", // import Vitest APIs instead of relying on globals + "vitest/no-restricted-vi-methods": [ + "deny", // Module mocks hide dependencies. Method spies remain available. + { + doMock: "Inject dependencies instead of replacing modules.", + mock: "Inject dependencies instead of replacing modules.", + }, + ], + "vitest/require-test-timeout": "off", // the default timeout is a good default for most tests + "vitest/prefer-describe-function-title": "off", // clashes with valid-title + "vitest/prefer-to-be-falsy": "off", // Strict boolean matchers distinguish false from falsy values. + "vitest/prefer-to-be-truthy": "off", // Strict boolean matchers distinguish true from truthy values. + }), + ); + overrides.push( + defineOverride({ + files: ["src/**/*.test-d.ts"], + rules: { + "vitest/prefer-expect-assertions": "off", // type tests run through the compiler, not the runtime assertion counter. + "no-magic-numbers": "off", // magic numbers are often used in test fixtures + "max-lines-per-function": "off", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests + }, + }), + defineOverride({ + files: ["src/**/*.test.ts"], + rules: { + "no-magic-numbers": "off", // magic numbers are often used in test fixtures + "max-lines-per-function": "off", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests + }, + }), + ); + + break; + } + case "effect": { + extend.push(effectStrict); + Object.assign( + rules, + defineRules({ + "new-cap": "off", // clashes with effect's capitalization conventions + "oxc/no-barrel-file": "off", // side-effect free barrel files are common + "import/no-namespace": "off", // barrel files are common in effect + "no-underscore-dangle": ["deny", { allow: ["_tag"] }], // `_tag` is used to discriminate union types + "unicorn/max-nested-calls": "off", // functional programming and composition + "typescript/no-namespace": ["deny", { allowDeclarations: true }], // declarations are often used for type aliases + "no-shadow": "off", // covered by the strict typescript setup + "no-redeclare": "off", // covered by the strict typescript setup + "effecttsgo/missed-pipeable-opportunity": "deny", // nested function calls otherwise aren't readable + }), + ); + break; + } + } + } + + const pluginDeny = Object.fromEntries( + Object.keys(plugin.rules).map((key) => [ + `${plugin.meta?.name ?? "hash"}/${key}`, + "deny", + ]), + ); + + return defineConfig({ + categories: { + correctness: "deny", + nursery: "deny", + pedantic: "deny", + perf: "deny", + restriction: "deny", + style: "deny", + suspicious: "deny", + }, + env, + extends: extend, + ignorePatterns: [...(options.ignorePatterns ?? [])], + jsPlugins: [ + { + name: "hash", + specifier: fileURLToPath(new URL("rules/index.js", import.meta.url)), + }, + ], + options: { + reportUnusedDisableDirectives: "error", + typeAware: true, + }, + overrides, + plugins, + rules: { + "capitalized-comments": "off", // a linter should not police the style of comments + "default-case": "off", // type checking establishes the exhaustive set of cases + "import/exports-last": "off", // hurts readability, as items are commonly exported at declaration + "import/group-exports": "off", // hurts readability + "import/no-named-export": "off", // prefer named exports + "import/no-nodejs-modules": "off", // TypeScript 7 handles this natively through removal of ambient type definitions + "import/no-relative-parent-imports": "off", // relative parent imports are the de-factor standard for importing from parent directories + "import/prefer-default-export": "off", // depends on the module + "jsdoc/require-param": "off", // TypeScript supplies parameter types + "jsdoc/require-returns": "off", // TypeScript supplies return types + "max-lines": [ + "deny", // Keep each module reviewable as one unit, including its documentation. + { + max: 500, + skipBlankLines: false, + skipComments: false, + }, + ], + "max-lines-per-function": [ + "deny", // Bound executable bodies without charging comments against their budget. + { + IIFEs: true, + max: 100, + skipBlankLines: true, + skipComments: true, + }, + ], + "max-statements": "off", // "max-lines-per-function" is a better proxy + "no-duplicate-imports": [ + "error", // Keep type-only dependencies distinct from runtime imports. + { + allowSeparateTypeImports: true, + }, + ], + "no-inline-comments": "off", // inline comments are useful for explaining complex logic + "no-magic-numbers": [ + "deny", // Keep the rule narrow with the exceptions below. + { + enforceConst: true, + ignore: [-2, -1, 0, 1, 2], + ignoreClassFieldInitialValues: true, + ignoreDefaultValues: true, + ignoreEnums: true, + ignoreNumericLiteralTypes: true, + ignoreReadonlyClassProperties: true, + ignoreTypeIndexes: true, + }, + ], + "no-undefined": "off", // comparisons need `undefined` + "one-var": ["deny", "never"], // use one declaration per variable + "oxc/no-optional-chaining": "off", // optional chaining is useful for optional properties + "oxc/no-rest-spread-properties": "off", // central to functional programming + "prefer-destructuring": "off", // requiring destructuring for reassignment makes the code awkward + "sort-imports": [ + "deny", // Sort members while preserving dependency groups and declaration order. + { + allowSeparatedGroups: true, + ignoreDeclarationSort: true, + }, + ], + "sort-keys": "off", // declaration order is more important, and fix may be unsafe, sorting of keys does not increase clarity + "typescript/no-floating-promises": [ + "deny", // Discarded async failures must not disappear behind void or an IIFE. + { + checkThenables: true, + ignoreIIFE: false, + ignoreVoid: false, + }, + ], + "typescript/no-restricted-types": [ + "deny", // Broad types erase contracts that callers need to check their use. + { types: { ...defaultRestrictedTypes, ...additionalRestrictedTypes } }, + ], + "typescript/restrict-plus-operands": [ + "deny", // Addition must not depend on implicit coercion. + { + allowAny: false, + allowBoolean: false, + allowNullish: false, + allowNumberAndString: false, + allowRegExp: false, + }, + ], + "typescript/restrict-template-expressions": [ + "deny", // Make object and nullable interpolation explicit to avoid accidental placeholder text. + { + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: true, + allowRegExp: false, + }, + ], + "typescript/strict-boolean-expressions": [ + "deny", // Truthiness hides distinctions between absence, zero and empty strings. + { + allowNullableObject: false, + allowNumber: false, + allowString: false, + }, + ], + "unicorn/no-null": "off", // `null` is a useful type to indicate explicit absence of a value + "func-names": ["deny", "always", { generators: "never" }], // Name functions for stack traces without naming generator callbacks. + "typescript/no-empty-interface": ["deny", { allowSingleExtends: true }], // Permit named interfaces for readable editor type hints. + "typescript/no-empty-object-type": [ + "deny", // Permit named interfaces for readable editor type hints. + { allowInterfaces: "with-single-extends" }, + ], + "typescript/prefer-readonly-parameter-types": "off", // neat idea, but way too many false positives + "unicorn/prefer-ternary": "off", // clashes with the rule that requires explicit if/else + "id-length": ["deny", { checkGeneric: false, exceptions: ["$", "_"] }], // Type parameters and conventional helper bindings need their short names. + "unicorn/no-array-callback-reference": "off", // goes against functional programming + "typescript/explicit-member-accessibility": "off", // goes against modern ts and js interop + ...rules, + ...pluginDeny, + }, + }); +}; diff --git a/libs/@local/oxlint/src/lib/casing.test.ts b/libs/@local/oxlint/src/lib/casing.test.ts new file mode 100644 index 00000000000..7857aff18d1 --- /dev/null +++ b/libs/@local/oxlint/src/lib/casing.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, test } from "vitest"; + +import { isCase, splitWords, toCase } from "./casing.js"; + +import type { Casing } from "./casing.js"; + +describe("casing", () => { + test("split_words_boundaries", () => { + expect.hasAssertions(); + + expect(splitWords("XMLHttpRequest")).toStrictEqual([ + "XML", + "Http", + "Request", + ]); + expect(splitWords("base64Encode")).toStrictEqual(["base64", "Encode"]); + expect(splitWords("foo_bar-baz qux")).toStrictEqual([ + "foo", + "bar", + "baz", + "qux", + ]); + expect(splitWords("HTML5Parser")).toStrictEqual(["HTML5", "Parser"]); + }); + + test.each<[string, Casing, string]>([ + ["foo_bar", "camelCase", "fooBar"], + ["XMLHttpRequest", "strictCamelCase", "xmlHttpRequest"], + ["fooBar", "PascalCase", "FooBar"], + ["fooBar", "snake_case", "foo_bar"], + ["fooBar", "UPPER_CASE", "FOO_BAR"], + ["__foo_bar$", "camelCase", "__fooBar$"], + ["_", "camelCase", "_"], + ])("to_case_%s_%s_%s", (input, format, expected) => { + expect.hasAssertions(); + expect(toCase(input, format)).toBe(expected); + }); + + test.each<[string, Casing, boolean]>([ + ["userID", "camelCase", true], + ["userID", "strictCamelCase", false], + ["HTTPServer", "PascalCase", true], + ["HTTPServer", "StrictPascalCase", false], + ["V8ENGINE", "UPPER_CASE", true], + ["foo__bar", "snake_case", false], + ["foo_bar", "camelCase", false], + ["_private", "camelCase", true], + ])("is_case_%s_%s_%s", (input, format, expected) => { + expect.hasAssertions(); + + expect(isCase(input, format)).toBe(expected); + }); +}); diff --git a/libs/@local/oxlint/src/lib/casing.ts b/libs/@local/oxlint/src/lib/casing.ts new file mode 100644 index 00000000000..d3c3478ffb6 --- /dev/null +++ b/libs/@local/oxlint/src/lib/casing.ts @@ -0,0 +1,128 @@ +/** + * Classifies and converts identifier names between casings. + * + * Conversions preserve leading and trailing `_` / `$` affixes (`_private`, `value$`). Checks ignore them. + */ + +/** + * Supported naming formats, mirroring the formats of `@typescript-eslint/naming-convention`. + * + * The non-strict camel and Pascal variants allow consecutive capitals (`userID`), the strict + * variants do not (`userId`). Conversions always produce the strict spelling. + */ +export type Casing = + | "camelCase" + | "strictCamelCase" + | "PascalCase" + | "StrictPascalCase" + | "snake_case" + | "UPPER_CASE"; + +interface AffixedName { + readonly prefix: string; + readonly core: string; + readonly suffix: string; +} + +const leadingAffixPattern = /^[$_]+/u; +const trailingAffixPattern = /[$_]+$/u; +const separatorPattern = /[\s_-]+/u; +const lowerToUpperPattern = /(?[\p{Ll}\p{N}])(?\p{Lu})/gu; +const acronymEndPattern = /(?\p{Lu})(?\p{Lu}\p{Ll})/gu; +const startsUpperPattern = /^\p{Lu}/u; +const startsLowerPattern = /^\p{Ll}/u; +const consecutiveUpperPattern = /\p{Lu}{2}/u; +const invalidSnakeSeparatorPattern = /_{2}|[\s-]/u; + +const splitAffixes = (name: string): AffixedName => { + const withoutPrefix = name.replace(leadingAffixPattern, ""); + const core = withoutPrefix.replace(trailingAffixPattern, ""); + + return { + core, + prefix: name.slice(0, name.length - withoutPrefix.length), + suffix: withoutPrefix.slice(core.length), + }; +}; + +/** + * Splits text into its words. + * + * Word boundaries occur at `_`, `-` and whitespace, at lower-to-upper transitions (`fooBar`), and + * at the end of acronyms (`XMLHttp` → `XML`, `Http`). Digits stay attached to the preceding word + * (`base64Encode` → `base64`, `Encode`). + */ +export const splitWords = (text: string): string[] => + text + .replaceAll(lowerToUpperPattern, "$ $") + .replaceAll(acronymEndPattern, "$ $") + .split(separatorPattern) + .filter((word) => word.length > 0); + +const capitalize = (word: string): string => { + const [first = "", ...rest] = word; + + return first.toUpperCase() + rest.join("").toLowerCase(); +}; + +const lowerCamel = (words: readonly string[]): string => { + const [first = "", ...rest] = words; + + return first.toLowerCase() + rest.map((word) => capitalize(word)).join(""); +}; + +const upperCamel = (words: readonly string[]): string => + words.map((word) => capitalize(word)).join(""); + +const joiners: Readonly string>> = + { + PascalCase: upperCamel, + StrictPascalCase: upperCamel, + UPPER_CASE: (words) => words.map((word) => word.toUpperCase()).join("_"), + camelCase: lowerCamel, + snake_case: (words) => words.map((word) => word.toLowerCase()).join("_"), + strictCamelCase: lowerCamel, + }; + +const matchers: Readonly boolean>> = { + PascalCase: (core) => + !startsLowerPattern.test(core) && !separatorPattern.test(core), + StrictPascalCase: (core) => + !startsLowerPattern.test(core) && + !separatorPattern.test(core) && + !consecutiveUpperPattern.test(core), + UPPER_CASE: (core) => + core === core.toUpperCase() && !invalidSnakeSeparatorPattern.test(core), + camelCase: (core) => + !startsUpperPattern.test(core) && !separatorPattern.test(core), + snake_case: (core) => + core === core.toLowerCase() && !invalidSnakeSeparatorPattern.test(core), + strictCamelCase: (core) => + !startsUpperPattern.test(core) && + !separatorPattern.test(core) && + !consecutiveUpperPattern.test(core), +}; + +/** Whether `name` follows `casing`, ignoring leading and trailing `_` / `$` affixes. */ +export const isCase = (name: string, casing: Casing): boolean => { + const { core } = splitAffixes(name); + + return core.length === 0 || matchers[casing](core); +}; + +/** + * Converts `name` to `casing`, preserving leading and trailing `_` / `$` affixes. + * + * The result is not guaranteed to satisfy {@link isCase} (single-letter words such as in + * `foo_a_bar` → `fooABar` violate the strict formats), so check it before using it as a fix. + */ +export const toCase = (name: string, casing: Casing): string => { + const { prefix, core, suffix } = splitAffixes(name); + const words = splitWords(core); + + if (words.length === 0) { + return name; + } + + return `${prefix}${joiners[casing](words)}${suffix}`; +}; diff --git a/libs/@local/oxlint/src/lib/kind-affixes.ts b/libs/@local/oxlint/src/lib/kind-affixes.ts new file mode 100644 index 00000000000..ad6378048b7 --- /dev/null +++ b/libs/@local/oxlint/src/lib/kind-affixes.ts @@ -0,0 +1,61 @@ +/** + * Detects affixes that restate what kind of declaration a name refers to, as in Java and C# + * (`IUser`, `EColor`, `UserI`), or that it describes the structure of a value (`UserShape`). + */ + +export interface KindAffixMatch { + readonly affix: string; + readonly position: "prefix" | "suffix"; + /** The name without the affix. */ + readonly expected: string; +} + +interface KindAffix { + readonly affix: string; + readonly position: "prefix" | "suffix"; + /** Matches a name carrying the affix. Replacing the match with `replacement` drops it. */ + readonly pattern: RegExp; + readonly replacement: string; +} + +// A prefix only counts before a capitalized word. This excludes acronyms (`IOError`, `ETL`) +// and words that start with the letter (`IPv4`, `IFrame`, `ETag`). +const kindAffixes: readonly KindAffix[] = [ + { + affix: "I", + pattern: /^(?[$_]*)I(?!Pv[46]|Frame(?!\p{Ll}))(?=\p{Lu}\p{Ll})/u, + position: "prefix", + replacement: "$", + }, + { + affix: "E", + pattern: /^(?[$_]*)E(?!Tag(?!\p{Ll}))(?=\p{Lu}\p{Ll})/u, + position: "prefix", + replacement: "$", + }, + { + affix: "I", + pattern: /^(?[$_]*\p{Lu}.*[\p{Ll}\p{N}])I(?[$_]*)$/u, + position: "suffix", + replacement: "$$", + }, + { + affix: "Shape", + pattern: /^(?.*[\p{Ll}\p{N}])Shape(?[$_]*)$/u, + position: "suffix", + replacement: "$$", + }, +]; + +/** The first kind affix `name` carries, or `null` if it carries none. */ +export const findKindAffix = (name: string): KindAffixMatch | null => { + for (const { affix, pattern, position, replacement } of kindAffixes) { + const expected = name.replace(pattern, replacement); + + if (expected !== name) { + return { affix, expected, position }; + } + } + + return null; +}; diff --git a/libs/@local/oxlint/src/lib/reserved-names.ts b/libs/@local/oxlint/src/lib/reserved-names.ts new file mode 100644 index 00000000000..3968934ba68 --- /dev/null +++ b/libs/@local/oxlint/src/lib/reserved-names.ts @@ -0,0 +1,63 @@ +// Reserved words and names forbidden in strict-mode bindings or TypeScript type declarations. +export const reservedNames: ReadonlySet = new Set([ + "any", + "arguments", + "await", + "bigint", + "boolean", + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "eval", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "implements", + "import", + "in", + "Infinity", + "instanceof", + "interface", + "let", + "NaN", + "never", + "new", + "null", + "number", + "object", + "package", + "private", + "protected", + "public", + "return", + "static", + "string", + "super", + "switch", + "symbol", + "this", + "throw", + "true", + "try", + "typeof", + "undefined", + "unknown", + "var", + "void", + "while", + "with", + "yield", +]); diff --git a/libs/@local/oxlint/src/rules/index.ts b/libs/@local/oxlint/src/rules/index.ts new file mode 100644 index 00000000000..527577c2032 --- /dev/null +++ b/libs/@local/oxlint/src/rules/index.ts @@ -0,0 +1,24 @@ +import { definePlugin } from "@oxlint/plugins"; + +import { namingConventions } from "./naming-conventions.js"; +import { noPropertyModifiers } from "./no-property-modifiers.js"; +import { preferOptionsObject } from "./prefer-options-object.js"; +import { requireRuleChangeComment } from "./require-rule-change-comment.js"; +import { requireSafetyCommentForTypeAssertion } from "./require-safety-comment-for-type-assertion.js"; +import { requireSuppressionComment } from "./require-suppression-comment.js"; + +// oxlint-disable-next-line import/no-default-export -- required by the plugin API +export default definePlugin({ + meta: { + name: "hash", + }, + rules: { + "naming-conventions": namingConventions, + "no-property-modifiers": noPropertyModifiers, + "prefer-options-object": preferOptionsObject, + "require-rule-change-comment": requireRuleChangeComment, + "require-safety-comment-for-type-assertion": + requireSafetyCommentForTypeAssertion, + "require-suppression-comment": requireSuppressionComment, + }, +}); diff --git a/libs/@local/oxlint/src/rules/naming-conventions.test.ts b/libs/@local/oxlint/src/rules/naming-conventions.test.ts new file mode 100644 index 00000000000..c96ce1b48b3 --- /dev/null +++ b/libs/@local/oxlint/src/rules/naming-conventions.test.ts @@ -0,0 +1,357 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { namingConventions } from "./naming-conventions.js"; + +const tester = new RuleTester({ + languageOptions: { parserOptions: { lang: "tsx" }, sourceType: "module" }, +}); + +const error = { messageId: "casing" }; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("naming-conventions/variable-casing", namingConventions, { + invalid: [ + { + code: "const foo_bar = 1; console.log(foo_bar);", + errors: [error], + output: "const fooBar = 1; console.log(fooBar);", + }, + // Oxlint merges a report's edits into one span. The overlapping second rename waits a pass. + { + code: "const fn = (foo_bar: string, baz_q?: number) => foo_bar + String(baz_q);", + errors: [error, error], + output: + "const fn = (fooBar: string, baz_q?: number) => fooBar + String(baz_q);", + }, + { + code: "class Foo { m(@D() foo_bar: string) { return foo_bar; } }", + errors: [error], + output: "class Foo { m(@D() fooBar: string) { return fooBar; } }", + }, + { + code: "const foo_bar = 1; export { foo_bar };", + errors: [error], + output: "const fooBar = 1; export { fooBar as foo_bar };", + }, + { + code: "const foo_bar = 1; const o = { foo_bar }; const { k_v = 1 } = o;", + errors: [error, error], + output: + "const fooBar = 1; const o = { foo_bar: fooBar }; const { k_v: kV = 1 } = o;", + }, + { + code: "function f() { var a_b; { let aB = 1; } return a_b; }", + errors: [error], + output: "function f() { var aB; { let aB = 1; } return aB; }", + }, + // Types, classes, enums and namespaces are PascalCase. + { + code: "class Foo_Bar { static make() { return new Foo_Bar(); } } new Foo_Bar();", + errors: [ + { + data: { casing: "PascalCase", expected: "FooBar", name: "Foo_Bar" }, + messageId: "casing", + }, + ], + output: + "class FooBar { static make() { return new FooBar(); } } new FooBar();", + }, + { + code: "const make = () => new (class inner_class {})(); make();", + errors: [error], + output: "const make = () => new (class InnerClass {})(); make();", + }, + { + code: "const my_class = class {}; new my_class();", + errors: [error], + output: "const MyClass = class {}; new MyClass();", + }, + { + code: "type user_id = string; const id: user_id = '';", + errors: [error], + output: "type UserId = string; const id: UserId = '';", + }, + { + code: "interface fooBar {} let value: fooBar;", + errors: [error], + output: "interface FooBar {} let value: FooBar;", + }, + { + code: "enum color { Red } color.Red;", + errors: [error], + output: "enum Color { Red } Color.Red;", + }, + { + code: "namespace utils {}", + errors: [error], + output: "namespace Utils {}", + }, + // Renaming an enum member would rename a property of the enum object. + { code: "enum Color { dark_red }", errors: [error], output: null }, + { + code: "const identity = (value: t_value): t_value => value;", + errors: [error], + output: "const identity = (value: TValue): TValue => value;", + }, + { + code: "type Copy = { readonly [index in keyof T]: T[index] };", + errors: [ + { + messageId: "casing", + data: { casing: "PascalCase", expected: "Index", name: "index" }, + }, + ], + output: "type Copy = { readonly [Index in keyof T]: T[Index] };", + }, + { + code: `type Getters = { [key_name in keyof T as \`get\${key_name & string}\`]: T[key_name] };`, + errors: [ + { + messageId: "casing", + data: { casing: "PascalCase", expected: "KeyName", name: "key_name" }, + }, + ], + output: `type Getters = { [KeyName in keyof T as \`get\${KeyName & string}\`]: T[KeyName] };`, + }, + { + code: "type Copy = { [index in Keys]: [Index, index] };", + errors: [error], + output: null, + }, + { + code: "let Index = 0; type Copy = { [Index in keyof T]: T[Index] }; Index += 1;", + errors: [error], + output: + "let index = 0; type Copy = { [Index in keyof T]: T[Index] }; index += 1;", + }, + // A value merged with a type follows the type. + { + code: "const user_schema = 1; type user_schema = typeof user_schema;", + errors: [error], + output: "const UserSchema = 1; type UserSchema = typeof UserSchema;", + }, + { + code: "const q = function inner_f() { return inner_f; }; q();", + errors: [error], + output: "const q = function innerF() { return innerF; }; q();", + }, + // Renaming would cause a collision or shadowing with an existing binding. + { + code: "const foo_bar = 1; const fooBar = 2;", + errors: [error], + output: null, + }, + { + code: "const foo_bar = 1; function f(fooBar: number) { return foo_bar + fooBar; }", + errors: [error], + output: null, + }, + { + code: "const foo_bar = 1; function f() { return fooBar + foo_bar; }", + errors: [error], + output: null, + }, + { + code: "function f() { var a_b; { let aB = 1; var a_b; } }", + errors: [error], + output: null, + }, + // Only the first rename can claim the name when two variables converge on it. + { + code: "const foo_bar = 1; const fooBar_ = 2; const foo__bar = 3;", + errors: [error, error], + output: "const fooBar = 1; const fooBar_ = 2; const foo__bar = 3;", + }, + // Renaming would change the module's interface or the meaning of the code. + { code: "export const foo_bar = 1;", errors: [error], output: null }, + { code: "export class Foo_Bar {}", errors: [error], output: null }, + { code: "export type foo_bar = string;", errors: [error], output: null }, + { code: "declare const foo_bar: string;", errors: [error], output: null }, + { + code: "class P { constructor(private foo_bar: string) {} }", + errors: [error], + output: null, + }, + // `const` bindings and function declarations keep the case of their first letter. + { + code: "const My_Comp = () => null; const el = ;", + errors: [ + { + data: { + casing: "camelCase or PascalCase", + expected: "MyComp", + name: "My_Comp", + }, + messageId: "casing", + }, + ], + output: "const MyComp = () => null; const el = ;", + }, + { + code: "function User_Schema() {} User_Schema();", + errors: [error], + output: "function UserSchema() {} UserSchema();", + }, + { + code: "function make_user(): void; function make_user() {} make_user();", + errors: [error], + output: "function makeUser(): void; function makeUser() {} makeUser();", + }, + { + code: "const { Foo_Bar } = source;", + errors: [error], + output: "const { Foo_Bar: FooBar } = source;", + }, + // `let`, `var`, parameters and function expression names are camelCase only. + { + code: "let Counter = 0; Counter += 1;", + errors: [error], + output: "let counter = 0; counter += 1;", + }, + { + code: "const fn = (Value: number) => Value;", + errors: [error], + output: "const fn = (value: number) => value;", + }, + // A JSX component must not become an intrinsic element. + { + code: "let My_Comp = () => null; const el = ;", + errors: [error], + output: null, + }, + { + code: "const foo_bar = 1; eval('foo_bar');", + errors: [error], + output: null, + }, + { code: "let New = 1;", errors: [error], output: null }, + ], + valid: [ + "const fooBar = 1;", + "const userID = 1;", + "const _private = 1; const value$ = 2; const __dirname = '';", + "import { foo_bar as fooBar } from 'x';", + // The exporting module chooses imported names. + "import Foo_Bar, { foo_bar, Baz_Q as baz_q } from 'x'; import * as Ns_X from 'y'; import type { T_x } from 'z';", + "class FooBar {} const Expr = class Inner {}; abstract class Base {}", + "type UserId = string; interface Props {} enum Color { Red } namespace Utils {}", + "function identity(value: TValue): TValue { return value; }", + "type Values = { [Index in keyof Members]: Members[Index] };", + "type Nested = { [Outer in keyof T]: { [Inner in keyof T[Outer]]: T[Outer][Inner] } };", + `type Getters = { readonly [Key in keyof T as \`get\${Key & string}\`]-?: T[Key] };`, + "type Value = T extends infer Item ? Item : never;", + "const Schema = 1; type Schema = typeof Schema;", + "const MyComponent = () => null; const User = Schema.Struct({}); const { Foo } = source;", + "function Person() {} function makePerson() { return new Person(); }", + "function Over(value: string): void; function Over(value: unknown) {}", + ], +}); + +const affixError = { messageId: "kindAffix" }; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("naming-conventions/kind-affixes", namingConventions, { + invalid: [ + { + code: "interface IUser {} let user: IUser;", + errors: [ + { + data: { + affix: "I", + expected: "User", + name: "IUser", + position: "prefix", + }, + messageId: "kindAffix", + }, + ], + output: "interface User {} let user: User;", + }, + { + code: "type IUser = { id: string }; let user: IUser;", + errors: [affixError], + output: "type User = { id: string }; let user: User;", + }, + { + code: "class IRepository {} new IRepository();", + errors: [affixError], + output: "class Repository {} new Repository();", + }, + { + code: "enum EColor { Red } EColor.Red;", + errors: [affixError], + output: "enum Color { Red } Color.Red;", + }, + { + code: "interface UserI {} let user: UserI;", + errors: [affixError], + output: "interface User {} let user: User;", + }, + { + code: "type UserShape = { id: string }; let user: UserShape;", + errors: [affixError], + output: "type User = { id: string }; let user: User;", + }, + { + code: "const userShape = {}; console.log(userShape);", + errors: [affixError], + output: "const user = {}; console.log(user);", + }, + { + code: "const UserShape = Schema.Struct({}); type UserShape = typeof UserShape.Type;", + errors: [affixError], + output: "const User = Schema.Struct({}); type User = typeof User.Type;", + }, + { + code: "interface _IUser {} let user: _IUser;", + errors: [affixError], + output: "interface _User {} let user: _User;", + }, + // A single rename fixes both the casing and the affix. + { + code: "interface I_user {} let user: I_user;", + errors: [ + { + data: { + affix: "I", + casing: "PascalCase", + expected: "User", + name: "I_user", + position: "prefix", + }, + messageId: "casingAndKindAffix", + }, + ], + output: "interface User {} let user: User;", + }, + { + code: "const User_Shape = 1; console.log(User_Shape);", + errors: [{ messageId: "casingAndKindAffix" }], + output: "const User = 1; console.log(User);", + }, + // A conversion to camelCase lowercases the prefix, leaving no affix behind. + { + code: "let IUser = 1; IUser += 1;", + errors: [error], + output: "let iUser = 1; iUser += 1;", + }, + // The name without the affix already exists. The author must choose a new name. + { + code: "interface IUser {} class User implements IUser {}", + errors: [affixError], + output: null, + }, + { code: "export interface IUser {}", errors: [affixError], output: null }, + ], + valid: [ + "interface IOError {} type ETL = string; interface IPAddress {} type ID = string;", + "type IPv4Address = string; interface IFrameProps {} type ETagHeader = string;", + "interface Effect {} type Entity = {}; interface Item {}", + "type Shape = {}; type UI = {}; class AppUI {} type PhaseII = 2;", + "let rowI = 0; const userShapes = [];", + "function f(error: EIn, item: IItem) {}", + "type Copy = { [IIndex in keyof T]: T[IIndex] };", + // The exporting module chooses imported names. + "import type { IUser, UserShape } from 'x';", + ], +}); diff --git a/libs/@local/oxlint/src/rules/naming-conventions.ts b/libs/@local/oxlint/src/rules/naming-conventions.ts new file mode 100644 index 00000000000..d4f5b240313 --- /dev/null +++ b/libs/@local/oxlint/src/rules/naming-conventions.ts @@ -0,0 +1,474 @@ +/** + * Enforces declaration-specific casing and rejects redundant kind affixes. + * + * Types, classes, enums and namespaces use PascalCase. Other bindings use camelCase, with either allowed for const bindings and function declarations. Imported bindings are exempt. + * + * Fixes rename eligible local bindings and their references, preserving property keys and explicit export names. The rule reports directly named exports and detected scope conflicts without a fix. + * + * @example Incorrect + * ```ts + * const user_name = "Ada"; + * ``` + * + * @example Correct + * ```ts + * const userName = "Ada"; + * ``` + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +import { isCase, toCase } from "../lib/casing.js"; +import { findKindAffix } from "../lib/kind-affixes.js"; +import { reservedNames } from "../lib/reserved-names.js"; + +import type { Casing } from "../lib/casing.js"; +import type { KindAffixMatch } from "../lib/kind-affixes.js"; +import type { + Context, + Definition, + ESTree, + Fix, + Scope, + SourceCode, + Variable, +} from "@oxlint/plugins"; + +// A JSX tag name starting with an ASCII lowercase letter denotes an intrinsic element. +const intrinsicJsxNamePattern = /^[a-z]/u; + +/** + * Names claimed by fixes reported earlier in this lint pass. + * + * Oxlint applies all non-overlapping fixes together. Without these claims, fixes could rename both `foo_bar` and `foo__bar` to `fooBar`. Each `Variable` belongs to one file, which also bounds the lifetime of its claim. + */ +const claimedNames = new WeakMap(); + +const effectiveName = (variable: Variable): string => + claimedNames.get(variable) ?? variable.name; + +interface Rename { + /** The variables to rename together, such as a class's outer and inner binding. */ + readonly variables: ReadonlySet; + readonly name: string; +} + +const declaredTogether = ( + sourceCode: SourceCode, + variable: Variable, +): ReadonlySet => { + const starts = new Set( + variable.identifiers.map((identifier) => identifier.range[0]), + ); + const variables = variable.defs + .flatMap((definition) => sourceCode.getDeclaredVariables(definition.node)) + .filter((candidate) => + candidate.identifiers.some((identifier) => + starts.has(identifier.range[0]), + ), + ); + + return new Set([variable, ...variables]); +}; + +const isExportedDeclaration = (definition: Definition): boolean => { + if (definition.type === "Parameter" || definition.type === "CatchClause") { + return false; + } + + if (definition.type === "Variable") { + return definition.parent?.parent?.type === "ExportNamedDeclaration"; + } + + return definition.node.parent?.type === "ExportNamedDeclaration"; +}; + +const isAmbient = (sourceCode: SourceCode, definition: Definition): boolean => + sourceCode + .getAncestors(definition.name) + .some((node) => "declare" in node && node.declare === true); + +// Renaming a parameter property or an enum member would rename a member of an object. +const definesMember = (definition: Definition): boolean => { + let { parent } = definition.name; + + while (parent.type === "AssignmentPattern") { + ({ parent } = parent); + } + + return ( + definition.node.type === "TSEnumMember" || + parent.type === "TSParameterProperty" + ); +}; + +const hasWithScope = (scope: Scope): boolean => + scope.type === "with" || + scope.childScopes.some((child) => hasWithScope(child)); + +const isRenameable = (sourceCode: SourceCode, variable: Variable): boolean => + // Bindings in a script's global scope are visible to other scripts. + variable.scope.type !== "global" && + variable.defs.length > 0 && + variable.defs.every( + (definition) => + !isExportedDeclaration(definition) && + !isAmbient(sourceCode, definition) && + !definesMember(definition), + ) && + !hasWithScope(variable.scope) && + !variable.scope.through.some( + (reference) => reference.identifier.name === "eval", + ); + +const declares = (scope: Scope, rename: Rename): boolean => + scope.variables.some( + (candidate) => + !rename.variables.has(candidate) && + effectiveName(candidate) === rename.name, + ); + +/** Whether a scope from `from` up to, but excluding, the variable's scope declares the name. */ +const isShadowed = ( + from: Scope, + variable: Variable, + rename: Rename, +): boolean => { + for ( + let scope: Scope | null = from; + scope !== null && scope !== variable.scope; + scope = scope.upper + ) { + if (declares(scope, rename)) { + return true; + } + } + + return false; +}; + +/** Whether declaring the name in `scope` would capture references that resolve elsewhere. */ +const captures = (scope: Scope, rename: Rename): boolean => + scope.through.some((reference) => { + if (reference.resolved === null) { + return reference.identifier.name === rename.name; + } + + return effectiveName(reference.resolved) === rename.name; + }); + +const hasConflict = (sourceCode: SourceCode, rename: Rename): boolean => + [...rename.variables].some( + (variable) => + declares(variable.scope, rename) || + captures(variable.scope, rename) || + variable.references.some((reference) => + isShadowed(reference.from, variable, rename), + ) || + // A `var` declared in a block must not collide with that block's bindings either. + variable.identifiers.some((identifier) => + isShadowed(sourceCode.getScope(identifier), variable, rename), + ), + ); + +/** Every node spelling the name. Declarations and their `init` references may coincide. */ +const nameNodes = (rename: Rename): ESTree.Node[] => { + const nodes = new Map(); + + for (const variable of rename.variables) { + for (const identifier of variable.identifiers) { + nodes.set(identifier.range[0], identifier); + } + + for (const reference of variable.references) { + nodes.set(reference.identifier.range[0], reference.identifier); + } + } + + return [...nodes.values()]; +}; + +const isJsxTagName = (node: ESTree.Node): boolean => + node.type === "JSXIdentifier" && + (node.parent.type === "JSXOpeningElement" || + node.parent.type === "JSXClosingElement"); + +const isShorthandProperty = (node: ESTree.Node): boolean => { + let { parent } = node; + + if (parent?.type === "AssignmentPattern" && parent.left === node) { + ({ parent } = parent); + } + + return parent?.type === "Property" && parent.shorthand; +}; + +/** + * Text replacing the name at `node`. Expanding shorthand forms preserves the spelling of property keys, imported names and exported names. + */ +const replacementText = ( + node: ESTree.Node, + name: string, + newName: string, +): string => { + const { parent } = node; + + if ( + parent?.type === "ImportSpecifier" && + parent.imported.range[0] === parent.local.range[0] + ) { + return `${name} as ${newName}`; + } + + if ( + parent?.type === "ExportSpecifier" && + parent.exported.range[0] === parent.local.range[0] + ) { + return `${newName} as ${name}`; + } + + if (isShorthandProperty(node)) { + return `${name}: ${newName}`; + } + + return newName; +}; + +/** + * Edits renaming `variable` and every reference to it to `newName`, or `null` if the rename + * could change behaviour or the module's interface. + * + * On success this function claims the new name for the rest of the lint pass. The caller must report the returned edits. + */ +const renameVariable = ( + sourceCode: SourceCode, + variable: Variable, + newName: string, +): Fix[] | null => { + const rename: Rename = { + name: newName, + variables: declaredTogether(sourceCode, variable), + }; + + if ( + reservedNames.has(newName) || + ![...rename.variables].every((candidate) => + isRenameable(sourceCode, candidate), + ) || + hasConflict(sourceCode, rename) + ) { + return null; + } + + const nodes = nameNodes(rename); + + if ( + intrinsicJsxNamePattern.test(newName) && + nodes.some((node) => isJsxTagName(node)) + ) { + return null; + } + + const edits: Fix[] = []; + + for (const node of nodes) { + // A binding identifier's range also covers its type annotation. Its first token is the name. + const token = sourceCode.getFirstToken(node); + + if (token === null) { + return null; + } + + edits.push({ + range: token.range, + text: replacementText(node, variable.name, newName), + }); + } + + for (const candidate of rename.variables) { + claimedNames.set(candidate, newName); + } + + return edits; +}; + +// Mapped types attach their parameter definition to the mapped-type node. +const isTypeParameter = (variable: Variable): boolean => + variable.defs.some( + (definition) => + definition.node.type === "TSTypeParameter" || + definition.node.type === "TSMappedType", + ); + +const pascalCaseDeclarations: ReadonlySet = new Set([ + "ClassDeclaration", + "ClassExpression", + "TSEnumDeclaration", + "TSEnumMember", + "TSInterfaceDeclaration", + "TSModuleDeclaration", + "TSTypeAliasDeclaration", +]); + +// `const Foo = class {}` binds a class through a variable declaration. +const isClassBinding = (definition: Definition): boolean => + definition.node.type === "VariableDeclarator" && + definition.node.id.type === "Identifier" && + definition.node.init?.type === "ClassExpression"; + +/** + * `const` bindings and function declarations may use PascalCase to signal a class-like or type-like role. Examples include React components, constructor functions and Effect schemas. + */ +const isFlexibleDefinition = (definition: Definition): boolean => + definition.node.type === "FunctionDeclaration" || + definition.node.type === "TSDeclareFunction" || + (definition.parent?.type === "VariableDeclaration" && + definition.parent.kind === "const"); + +const startsUpperPattern = /^[$_]*\p{Lu}/u; + +type NamingPolicy = Casing | "camelCase or PascalCase"; + +/** + * The casing `variable` must follow, or `null` if the rule does not govern its name. + * + * Types, classes, enums and namespaces are PascalCase, `const` bindings and function + * declarations either camelCase or PascalCase, everything else camelCase. A value merged with a + * type (`const Schema = ...` with `type Schema = ...`) follows the type. The exporting module chooses imported names. The author may rename them on import. + */ +const policyOf = (variable: Variable): NamingPolicy | null => { + if ( + variable.defs.length === 0 || + variable.defs.some((definition) => definition.type === "ImportBinding") + ) { + return null; + } + + if ( + isTypeParameter(variable) || + variable.defs.some( + (definition) => + pascalCaseDeclarations.has(definition.node.type) || + isClassBinding(definition), + ) + ) { + return "PascalCase"; + } + + if (variable.defs.every((definition) => isFlexibleDefinition(definition))) { + return "camelCase or PascalCase"; + } + + return "camelCase"; +}; + +const conformsTo = (name: string, policy: NamingPolicy): boolean => { + if (policy === "camelCase or PascalCase") { + return isCase(name, "camelCase") || isCase(name, "PascalCase"); + } + + return isCase(name, policy); +}; + +/** The target casing. A flexible name keeps the case of its first letter. */ +const targetCasing = (name: string, policy: NamingPolicy): Casing => { + if (policy !== "camelCase or PascalCase") { + return policy; + } + + if (startsUpperPattern.test(name)) { + return "PascalCase"; + } + + return "camelCase"; +}; + +const messageIdOf = ( + casing: Casing | null, + affix: KindAffixMatch | null, +): "casing" | "casingAndKindAffix" | "kindAffix" => { + if (affix === null) { + return "casing"; + } + + if (casing === null) { + return "kindAffix"; + } + + return "casingAndKindAffix"; +}; + +const checkVariable = (context: Context, variable: Variable): void => { + const [identifier] = variable.identifiers; + const policy = policyOf(variable); + + if (identifier === undefined || policy === null) { + return; + } + + let casing: Casing | null = null; + let cased = variable.name; + let affix: KindAffixMatch | null = null; + + if (!conformsTo(variable.name, policy)) { + casing = targetCasing(variable.name, policy); + cased = toCase(variable.name, casing); + } + + // Single-letter prefixes are the convention for type parameters (`TValue`, `EIn`, `RIn`). + // Checking the converted name removes both the `_` separator and the `I` prefix from `I_user`. + if (!isTypeParameter(variable)) { + affix = findKindAffix(cased); + } + + if (casing === null && affix === null) { + return; + } + + const expected = affix?.expected ?? cased; + let edits: Fix[] | null = null; + + // Conversions can fail to conform, e.g. `foo_a_bar` becomes `fooABar`, which may violate the naming policy. + if (expected !== variable.name && conformsTo(expected, policy)) { + edits = renameVariable(context.sourceCode, variable, expected); + } + + context.report({ + data: { ...affix, casing: policy, expected, name: variable.name }, + fix: () => edits, + messageId: messageIdOf(casing, affix), + node: identifier, + }); +}; + +export const namingConventions = defineRule({ + createOnce: (context) => ({ + "Program:exit": (): void => { + const checked = new Set(); + + for (const scope of context.sourceCode.scopeManager.scopes) { + for (const variable of scope.variables) { + const [identifier] = variable.identifiers; + + if (identifier !== undefined && !checked.has(identifier.range[0])) { + checked.add(identifier.range[0]); + checkVariable(context, variable); + } + } + } + }, + }), + meta: { + fixable: "code", + messages: { + casing: 'Rename "{{name}}" to "{{expected}}" ({{casing}}).', + casingAndKindAffix: + 'Rename "{{name}}" to "{{expected}}" ({{casing}}). The {{affix}} {{position}} restates what kind of declaration it is, which is the job of TypeScript.', + kindAffix: + 'Rename "{{name}}" to "{{expected}}". The {{affix}} {{position}} restates what kind of declaration it is, which is the job of TypeScript.', + }, + type: "suggestion", + }, +}); diff --git a/libs/@local/oxlint/src/rules/no-property-modifiers.test.ts b/libs/@local/oxlint/src/rules/no-property-modifiers.test.ts new file mode 100644 index 00000000000..fc6b6eb364b --- /dev/null +++ b/libs/@local/oxlint/src/rules/no-property-modifiers.test.ts @@ -0,0 +1,192 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { noPropertyModifiers } from "./no-property-modifiers.js"; + +const tester = new RuleTester({ + languageOptions: { parserOptions: { lang: "ts" }, sourceType: "module" }, +}); + +const privateError = { messageId: "private" }; +const publicError = { messageId: "public" }; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("no-property-modifiers", noPropertyModifiers, { + invalid: [ + { + code: "class A { private foo = 1; get() { return this.foo; } }", + errors: [privateError], + output: "class A { #foo = 1; get() { return this.#foo; } }", + }, + { + code: "class A { private readonly foo: number; constructor() { this.foo = 1; } }", + errors: [privateError], + output: + "class A { readonly #foo: number; constructor() { this.#foo = 1; } }", + }, + { + code: "class A { private foo = 1; bar = () => this.foo; baz = this.foo + 1; m() { return () => this?.foo; } }", + errors: [privateError], + output: + "class A { #foo = 1; bar = () => this.#foo; baz = this.#foo + 1; m() { return () => this?.#foo; } }", + }, + { + code: "class A { private static foo = 1; static { this.foo; } static m() { return A.foo + this.foo; } }", + errors: [privateError], + output: + "class A { static #foo = 1; static { this.#foo; } static m() { return A.#foo + this.#foo; } }", + }, + { + code: "class A { private accessor foo = 1; m() { return this.foo; } }", + errors: [privateError], + output: "class A { accessor #foo = 1; m() { return this.#foo; } }", + }, + // `.foo` outside the class cannot refer to the private property. + { + code: "class A { private foo = 1; } const o = { foo: 1 }; o.foo;", + errors: [privateError], + output: "class A { #foo = 1; } const o = { foo: 1 }; o.foo;", + }, + // Not every access can be rewritten with certainty. + { + code: "class A { private foo = 1; eq(other: A) { return other.foo === this.foo; } }", + errors: [privateError], + output: null, + }, + { + code: "class A { private foo = 1; m() { return function () { return this.foo; }; } }", + errors: [privateError], + output: null, + }, + { + code: "class A { private foo = 1; static m() { return this.foo; } }", + errors: [privateError], + output: null, + }, + { + code: "class A { private foo = 1; m() { const { foo } = this; return foo; } }", + errors: [privateError], + output: null, + }, + { + code: "class A { private foo = 1; m() { return this['foo']; } }", + errors: [privateError], + output: null, + }, + { + code: "class A { private foo = 1; m() { delete this.foo; } }", + errors: [privateError], + output: null, + }, + { + code: "class A { private foo = 1; #foo = 2; }", + errors: [privateError], + output: null, + }, + { + code: "class A { private foo?: number; }", + errors: [privateError], + output: null, + }, + { + code: "class A { @dec private foo = 1; }", + errors: [privateError], + output: null, + }, + { + code: "declare class A { private foo: number; }", + errors: [privateError], + output: null, + }, + { + code: "class A { private 'foo-bar' = 1; }", + errors: [privateError], + output: null, + }, + // The fix removes `public`, the default visibility. + { + code: "class A { public foo = 1; public static readonly bar = 2; public /* c */ accessor baz = 3; }", + errors: [publicError, publicError, publicError], + output: + "class A { foo = 1; static readonly bar = 2; /* c */ accessor baz = 3; }", + }, + { + code: "class A { @dec({ public: true }) public foo = 1; }", + errors: [publicError], + output: "class A { @dec({ public: true }) foo = 1; }", + }, + { + code: "class A { public foo_bar() {} public static baz() {} }", + errors: [publicError, publicError], + output: "class A { foo_bar() {} static baz() {} }", + }, + { + code: "class A { public get value() { return 1; } public set value(next: number) {} }", + errors: [publicError, publicError], + output: + "class A { get value() { return 1; } set value(next: number) {} }", + }, + { + code: "abstract class A { public abstract foo(): void; public bar(value: string): void; public bar(value: number): void; public bar(value: string | number) {} }", + errors: [publicError, publicError, publicError, publicError], + output: + "abstract class A { abstract foo(): void; bar(value: string): void; bar(value: number): void; bar(value: string | number) {} }", + }, + { + code: "class A extends B { @dec({ public: true }) public /* keep */ override foo() {} public async *bar() {} }", + errors: [publicError, publicError], + output: + "class A extends B { @dec({ public: true }) /* keep */ override foo() {} async *bar() {} }", + }, + { + code: "class A { public constructor() {} }", + errors: [publicError], + output: "class A { constructor() {} }", + }, + { + code: "class A { private foo_bar() {} private static baz() {} private get value() { return 1; } private set value(next: number) {} }", + errors: [privateError, privateError, privateError, privateError], + output: null, + }, + { + code: "class A { foo = value\n public [key]() {} }", + errors: [publicError], + output: null, + }, + { + code: "class A { foo = value\n public *bar() {} }", + errors: [publicError], + output: null, + }, + { + code: "class A { constructor(public readonly foo: number) {} }", + errors: [publicError], + output: "class A { constructor(readonly foo: number) {} }", + }, + // Without the modifier, the computed key would continue the previous member. + { + code: "class A { foo = 1\n public [key] = 2; }", + errors: [publicError], + output: null, + }, + // Without `readonly` or `override`, the parameter would no longer declare a property. + { + code: "class A { constructor(private readonly foo: number, public bar = 1) {} }", + errors: [privateError, publicError], + output: null, + }, + { + code: "class A { protected foo = 1; }", + errors: [{ messageId: "protected" }], + output: null, + }, + ], + valid: [ + "class A { foo = 1; #bar = 2; static baz = 3; readonly qux = 4; }", + "class A { foo_bar() {} #bar() {} static baz() {} }", + "class A { protected foo() {} protected get bar() { return 1; } protected set bar(value: number) {} }", + "class A { private constructor() {} }", + "class A { protected constructor() {} }", + "const object = { public() {}, private() {}, protected() {} };", + "class A { constructor(readonly foo: number) {} }", + ], +}); diff --git a/libs/@local/oxlint/src/rules/no-property-modifiers.ts b/libs/@local/oxlint/src/rules/no-property-modifiers.ts new file mode 100644 index 00000000000..0d7b7325c68 --- /dev/null +++ b/libs/@local/oxlint/src/rules/no-property-modifiers.ts @@ -0,0 +1,472 @@ +/** + * Prefers JavaScript private names and default public visibility. + * + * Reports accessibility modifiers on fields, auto-accessors and constructor parameter properties. Methods report only public and private modifiers. Private and protected constructors remain valid. + * + * Fixes remove redundant public modifiers and can rewrite private fields and recognized accesses to #names. Private methods have no fix. Private-name conversion changes enumeration and serialization. Protected properties and unsupported conversions need manual edits. + * + * @example Incorrect + * ```ts + * class Counter { public count = 0; } + * ``` + * + * @example Correct + * ```ts + * class Counter { count = 0; } + * ``` + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +import type { Context, ESTree, Fix, SourceCode, Token } from "@oxlint/plugins"; + +type ClassProperty = ESTree.PropertyDefinition | ESTree.AccessorProperty; + +type ClassMemberProperty = ClassProperty & { + readonly parent: ESTree.ClassBody; +}; + +interface ThisOwner { + readonly body: ESTree.ClassBody; + readonly isStatic: boolean; +} + +/** Nodes retained until traversal of the whole file finishes. */ +interface FileState { + readonly classBodies: ESTree.ClassBody[]; + readonly memberExpressions: ESTree.StaticMemberExpression[]; + readonly patternKeys: ESTree.IdentifierName[]; + /** Names accessed in ways a private name cannot be, such as `this["foo"]` or `typeof this.foo`. */ + readonly unrenameableNames: Set; +} + +const isClassMember = ( + property: ClassProperty, +): property is ClassMemberProperty => property.parent.type === "ClassBody"; + +const isStaticMember = ( + node: ESTree.MemberExpression, +): node is ESTree.StaticMemberExpression => + !node.computed && node.property.type === "Identifier"; + +const isClassProperty = ( + element: ESTree.ClassElement, +): element is ClassProperty => + element.type === "PropertyDefinition" || + element.type === "TSAbstractPropertyDefinition" || + element.type === "AccessorProperty" || + element.type === "TSAbstractAccessorProperty"; + +const elementName = (element: ESTree.ClassElement): string | null => { + if ( + element.type === "StaticBlock" || + element.type === "TSIndexSignature" || + element.computed + ) { + return null; + } + + if ( + element.key.type === "Identifier" || + element.key.type === "PrivateIdentifier" + ) { + return element.key.name; + } + + return null; +}; + +const addStringKey = (state: FileState, node: ESTree.Node): void => { + if (node.type === "Literal" && typeof node.value === "string") { + state.unrenameableNames.add(node.value); + } +}; + +const methodOwner = (method: ESTree.Function): ThisOwner | null => { + const { parent } = method; + + if ( + (parent.type === "MethodDefinition" || + parent.type === "TSAbstractMethodDefinition") && + parent.value === method && + parent.parent.type === "ClassBody" + ) { + return { body: parent.parent, isStatic: parent.static }; + } + + return null; +}; + +/** The class and context (static or instance) that `this` refers to at `node`. */ +const thisOwner = (node: ESTree.ThisExpression): ThisOwner | null => { + let child: ESTree.Node = node; + + for ( + let current: ESTree.Node | null = node.parent; + current !== null; + current = current.parent + ) { + if ( + current.type === "FunctionDeclaration" || + current.type === "FunctionExpression" + ) { + return methodOwner(current); + } + + if (current.type === "StaticBlock" && current.parent.type === "ClassBody") { + return { body: current.parent, isStatic: true }; + } + + // Only initializers use the class's `this`. Computed keys use the enclosing context. + if ( + (current.type === "PropertyDefinition" || + current.type === "AccessorProperty") && + current.value === child && + current.parent.type === "ClassBody" + ) { + return { body: current.parent, isStatic: current.static }; + } + + child = current; + } + + return null; +}; + +const refersToClass = ( + sourceCode: SourceCode, + identifier: ESTree.IdentifierReference, + body: ESTree.ClassBody, +): boolean => { + const reference = sourceCode + .getScope(identifier) + .references.find((candidate) => candidate.identifier === identifier); + + return ( + reference?.resolved?.defs.some( + (definition) => definition.node === body.parent, + ) === true + ); +}; + +/** Whether `member` resolves to `property` within its declaring class. */ +const accessesProperty = ( + sourceCode: SourceCode, + member: ESTree.StaticMemberExpression, + property: ClassMemberProperty, +): boolean => { + // JavaScript forbids deleting private names. + if ( + member.parent.type === "UnaryExpression" && + member.parent.operator === "delete" + ) { + return false; + } + + if (member.object.type === "ThisExpression") { + const owner = thisOwner(member.object); + + return ( + owner?.body === property.parent && owner.isStatic === property.static + ); + } + + return ( + property.static && + member.object.type === "Identifier" && + refersToClass(sourceCode, member.object, property.parent) + ); +}; + +type AccessibleMember = + | ClassProperty + | ESTree.MethodDefinition + | ESTree.TSParameterProperty; + +const modifierToken = ( + sourceCode: SourceCode, + node: AccessibleMember, + modifier: ESTree.TSAccessibility, +): Token | null => { + const lastDecorator = node.decorators.at(-1); + const start = lastDecorator?.range[1] ?? node.range[0]; + + return sourceCode.getFirstToken(node, { + filter: (token) => token.range[0] >= start && token.value === modifier, + }); +}; + +/** Removes `modifier` and the whitespace after it from `node`. */ +const modifierRemoval = ( + sourceCode: SourceCode, + node: AccessibleMember, + modifier: ESTree.TSAccessibility, +): Fix | null => { + const token = modifierToken(sourceCode, node, modifier); + + if (token === null) { + return null; + } + + const next = sourceCode.getTokenAfter(token, { includeComments: true }); + const nextValue = sourceCode.getTokenAfter(token)?.value; + + // A leading `[` or `*` could continue the previous field's initializer after removal. + if (next === null || nextValue === "[" || nextValue === "*") { + return null; + } + + return { range: [token.range[0], next.range[0]], text: "" }; +}; + +const isWithin = (node: ESTree.Node, container: ESTree.Node): boolean => + node.range[0] >= container.range[0] && node.range[1] <= container.range[1]; + +const isAmbient = (node: ESTree.Node): boolean => { + for ( + let current: ESTree.Node | null = node; + current !== null; + current = current.parent + ) { + if ("declare" in current && current.declare) { + return true; + } + } + + return false; +}; + +/** Whether the property's declaration and recorded uses permit a private `name`. */ +const canUsePrivateName = ( + state: FileState, + property: ClassMemberProperty, + name: string, +): boolean => + // Private names cannot be optional, decorated by legacy decorators, or ambient. + (property.type === "PropertyDefinition" || + property.type === "AccessorProperty") && + property.optional !== true && + property.decorators.length === 0 && + !isAmbient(property) && + !state.unrenameableNames.has(name) && + !property.parent.body.some( + (element) => element !== property && elementName(element) === name, + ) && + !state.patternKeys.some( + (key) => key.name === name && isWithin(key, property.parent), + ); + +/** + * Edits turning the `private` property into a private name (`#name`), or `null` if the rule cannot establish a rewrite for every access. + */ +const privateNameFix = ( + sourceCode: SourceCode, + state: FileState, + property: ClassProperty, +): Fix[] | null => { + const name = elementName(property); + + if ( + !isClassMember(property) || + name === null || + !canUsePrivateName(state, property, name) + ) { + return null; + } + + // TypeScript only allows access to a private property from within its class. + const accesses = state.memberExpressions.filter( + (member) => + member.property.name === name && isWithin(member, property.parent), + ); + const removal = modifierRemoval(sourceCode, property, "private"); + + if ( + removal === null || + !accesses.every((member) => accessesProperty(sourceCode, member, property)) + ) { + return null; + } + + return [ + removal, + { range: property.key.range, text: `#${name}` }, + ...accesses.map( + (member): Fix => ({ range: member.property.range, text: `#${name}` }), + ), + ]; +}; + +const checkProperty = ( + context: Context, + state: FileState, + property: ClassProperty, +): void => { + const { accessibility } = property; + + if (accessibility === undefined || accessibility === null) { + return; + } + + let edits: Fix[] | Fix | null = null; + + if (accessibility === "private") { + edits = privateNameFix(context.sourceCode, state, property); + } else if (accessibility === "public") { + // Properties are public by default. + edits = modifierRemoval(context.sourceCode, property, accessibility); + } + + context.report({ + data: { name: context.sourceCode.getText(property.key) }, + fix: () => edits, + messageId: accessibility, + node: + modifierToken(context.sourceCode, property, accessibility) ?? property, + }); +}; + +/** + * Removes only `public`, and only while `readonly` or `override` keeps the parameter a property. The author must handle conversion to a field and an assignment. + */ +const checkParameterProperty = ( + context: Context, + property: ESTree.TSParameterProperty, +): void => { + const { accessibility, parameter } = property; + + if (accessibility === null) { + return; + } + + let binding: ESTree.Node = parameter; + let edit: Fix | null = null; + + if (parameter.type === "AssignmentPattern") { + binding = parameter.left; + } + + if (accessibility === "public" && (property.readonly || property.override)) { + edit = modifierRemoval(context.sourceCode, property, accessibility); + } + + context.report({ + data: { + name: context.sourceCode.getText( + context.sourceCode.getFirstToken(binding), + ), + }, + fix: () => edit, + messageId: accessibility, + node: + modifierToken(context.sourceCode, property, accessibility) ?? property, + }); +}; + +const checkMethod = ( + context: Context, + method: ESTree.MethodDefinition, +): void => { + const { accessibility, kind } = method; + + if ( + accessibility !== "public" && + (accessibility !== "private" || kind === "constructor") + ) { + return; + } + + let edit: Fix | null = null; + if (accessibility === "public") { + edit = modifierRemoval(context.sourceCode, method, accessibility); + } + + context.report({ + data: { name: context.sourceCode.getText(method.key) }, + fix: () => edit, + messageId: accessibility, + node: modifierToken(context.sourceCode, method, accessibility) ?? method, + }); +}; + +export const noPropertyModifiers = defineRule({ + createOnce: (context) => { + const state: FileState = { + classBodies: [], + memberExpressions: [], + patternKeys: [], + unrenameableNames: new Set(), + }; + + return { + BinaryExpression: (node): void => { + if (node.operator === "in") { + addStringKey(state, node.left); + } + }, + ClassBody: (node): void => { + state.classBodies.push(node); + }, + MemberExpression: (node): void => { + if (node.computed) { + addStringKey(state, node.property); + } else if (isStaticMember(node)) { + state.memberExpressions.push(node); + } + }, + MethodDefinition: (node): void => { + checkMethod(context, node); + }, + "Program:exit": (): void => { + for (const body of state.classBodies) { + for (const property of body.body.filter(isClassProperty)) { + checkProperty(context, state, property); + } + } + }, + Property: (node): void => { + if ( + node.parent.type === "ObjectPattern" && + !node.computed && + node.key.type === "Identifier" + ) { + state.patternKeys.push(node.key); + } + }, + TSAbstractMethodDefinition: (node): void => { + checkMethod(context, node); + }, + TSIndexedAccessType: (node): void => { + if (node.indexType.type === "TSLiteralType") { + addStringKey(state, node.indexType.literal); + } + }, + TSParameterProperty: (node): void => { + checkParameterProperty(context, node); + }, + TSQualifiedName: (node): void => { + if (node.left.type === "ThisExpression") { + state.unrenameableNames.add(node.right.name); + } + }, + before: (): void => { + state.classBodies.length = 0; + state.memberExpressions.length = 0; + state.patternKeys.length = 0; + state.unrenameableNames.clear(); + }, + }; + }, + meta: { + fixable: "code", + messages: { + private: + 'Use a private name ("#{{name}}") instead of the `private` modifier on "{{name}}".', + protected: 'Remove the `protected` modifier from property "{{name}}".', + public: 'Remove the `public` modifier from "{{name}}".', + }, + type: "suggestion", + }, +}); diff --git a/libs/@local/oxlint/src/rules/prefer-options-object.test.ts b/libs/@local/oxlint/src/rules/prefer-options-object.test.ts new file mode 100644 index 00000000000..bd6e2ab224f --- /dev/null +++ b/libs/@local/oxlint/src/rules/prefer-options-object.test.ts @@ -0,0 +1,66 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { preferOptionsObject } from "./prefer-options-object.js"; + +const tester = new RuleTester({ + languageOptions: { parserOptions: { lang: "ts" } }, +}); +const error = { messageId: "optionsObject" }; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("prefer-options-object", preferOptionsObject, { + invalid: [ + { code: "function query(retry?: boolean) {}", errors: [error] }, + { code: "const query = (limit?: number) => {};", errors: [error] }, + { code: "const query = function (name?: string) {};", errors: [error] }, + { code: "function query(mode?: 'fast') {}", errors: [error] }, + { code: "function query(limit?: bigint) {}", errors: [error] }, + { code: "function query(key?: symbol) {}", errors: [error] }, + { code: "function query(retry = true) {}", errors: [error] }, + { code: "function query(limit = -1) {}", errors: [error] }, + { code: "function query(limit = +1) {}", errors: [error] }, + { code: "function query(limit = -1n) {}", errors: [error] }, + { code: "function query(limit = 1n) {}", errors: [error] }, + { code: "function query(name = `default`) {}", errors: [error] }, + { + code: "function query(limit: number = defaultLimit) {}", + errors: [error], + }, + { code: "class Query { run(retry?: boolean) {} }", errors: [error] }, + { + code: "class Query { constructor(public retry = true) {} }", + errors: [error], + }, + { code: "declare function query(retry?: boolean): void;", errors: [error] }, + { code: "function query(retry?: boolean): void;", errors: [error] }, + { code: "type Query = (retry?: boolean) => void;", errors: [error] }, + { + code: "type Query = new (retry?: boolean) => QueryResult;", + errors: [error], + }, + { code: "interface Query { (retry?: boolean): void }", errors: [error] }, + { + code: "interface Query { new (retry?: boolean): QueryResult }", + errors: [error], + }, + { code: "interface Query { run(retry?: boolean): void }", errors: [error] }, + { + code: "function query(retry?: boolean, limit = 1) {}", + errors: [error, error], + }, + ], + valid: [ + "function query(retry: boolean) {}", + "function query(options?: { retry?: boolean }) {}", + "function query(options: QueryOptions = {}) {}", + "function query({ retry = true }: QueryOptions = {}) {}", + "function query(values: number[] = []) {}", + "function query(pattern = /query/) {}", + "function query(value = null) {}", + "function query(...values: number[]) {}", + // These require semantic type information, which this syntax rule does not infer. + "type Retry = boolean; function query(retry?: Retry) {}", + "function query(retry = defaultRetry) {}", + "import { accept } from 'library'; accept(retry => {});", + ], +}); diff --git a/libs/@local/oxlint/src/rules/prefer-options-object.ts b/libs/@local/oxlint/src/rules/prefer-options-object.ts new file mode 100644 index 00000000000..bafe6aace2d --- /dev/null +++ b/libs/@local/oxlint/src/rules/prefer-options-object.ts @@ -0,0 +1,116 @@ +/** + * Requires optional or defaulted scalar parameters to move into an options object. + * + * Checks written scalar annotations and recognizable scalar defaults, without resolving aliases or contextual callback types. Provides no autofix because changing a signature also requires updating its callers. + * + * @example Incorrect + * ```ts + * type Query = (retry?: boolean) => void; + * ``` + * + * @example Correct + * ```ts + * type Query = (options?: { retry?: boolean }) => void; + * ``` + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +import type { ESTree } from "@oxlint/plugins"; + +type ParameterOwner = + | ESTree.Function + | ESTree.ArrowFunctionExpression + | ESTree.TSCallSignatureDeclaration + | ESTree.TSConstructSignatureDeclaration + | ESTree.TSConstructorType + | ESTree.TSFunctionType + | ESTree.TSMethodSignature; + +const scalarAnnotations: ReadonlySet = new Set([ + "TSBigIntKeyword", + "TSBooleanKeyword", + "TSLiteralType", + "TSNumberKeyword", + "TSStringKeyword", + "TSSymbolKeyword", + "TSTemplateLiteralType", +]); + +// The public binding type declares optional as false, but parsed optional parameters carry true. +const isOptional = (parameter: { readonly optional?: boolean }): boolean => + parameter.optional === true; + +const hasScalarAnnotation = (parameter: ESTree.BindingIdentifier): boolean => + parameter.typeAnnotation !== undefined && + parameter.typeAnnotation !== null && + scalarAnnotations.has(parameter.typeAnnotation.typeAnnotation.type); + +const isScalarDefault = (expression: ESTree.Expression): boolean => { + if (expression.type === "Literal") { + return expression.value !== null && typeof expression.value !== "object"; + } + + if (expression.type === "TemplateLiteral") { + return true; + } + + return ( + expression.type === "UnaryExpression" && + (expression.operator === "-" || expression.operator === "+") && + expression.argument.type === "Literal" && + (typeof expression.argument.value === "number" || + typeof expression.argument.value === "bigint") + ); +}; + +export const preferOptionsObject = defineRule({ + createOnce: (context) => { + const checkParameters = (node: ParameterOwner): void => { + for (const original of node.params) { + let parameter = original; + if (parameter.type === "TSParameterProperty") { + parameter = parameter.parameter; + } + + const optionalScalar = + parameter.type === "Identifier" && + isOptional(parameter) && + hasScalarAnnotation(parameter); + + const defaultScalar = + parameter.type === "AssignmentPattern" && + parameter.left.type === "Identifier" && + (hasScalarAnnotation(parameter.left) || + isScalarDefault(parameter.right)); + + if (optionalScalar || defaultScalar) { + context.report({ messageId: "optionsObject", node: original }); + } + } + }; + + return { + ArrowFunctionExpression: checkParameters, + FunctionDeclaration: checkParameters, + FunctionExpression: checkParameters, + TSCallSignatureDeclaration: checkParameters, + TSConstructSignatureDeclaration: checkParameters, + TSConstructorType: checkParameters, + TSDeclareFunction: checkParameters, + TSEmptyBodyFunctionExpression: checkParameters, + TSFunctionType: checkParameters, + TSMethodSignature: checkParameters, + }; + }, + meta: { + messages: { + optionsObject: + "Move optional or defaulted scalar parameters into an options object. Justify externally imposed signatures with a local suppression.", + }, + schema: [], + type: "suggestion", + }, +}); diff --git a/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts b/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts new file mode 100644 index 00000000000..e84815bce39 --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts @@ -0,0 +1,124 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { requireRuleChangeComment } from "./require-rule-change-comment.js"; + +const tester = new RuleTester(); +const explanation = { messageId: "explanation" }; +const configuration = (rules: string): string => + `import { defineConfig } from "oxlint"; +defineConfig({ rules: { +${rules} +} });`; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("require-rule-change-comment", requireRuleChangeComment, { + invalid: [ + { + code: 'import { defineConfig } from "oxlint"; const rules = { one: "off" } as const;', + errors: [explanation], + filename: "config-factory.ts", + }, + { + code: 'import { defineConfig } from "oxlint"; defineConfig({ rules: { one: "off" as const } satisfies DummyRuleMap });', + errors: [explanation], + filename: "config-factory.ts", + }, + { + code: 'import { defineConfig } from "oxlint"; defineConfig({ rules: { one: ["off" as const] as const } });', + errors: [explanation], + filename: "config-factory.ts", + }, + { + code: 'import { defineConfig } from "oxlint"; defineConfig({ rules: ({ one: ("off") }) });', + errors: [explanation], + }, + ...["allow", "off", "warn", "deny", "error"].map((severity) => ({ + code: configuration(`"one": "${severity}",`), + errors: [explanation], + })), + ...[0, 1, 2].map((severity) => ({ + code: configuration(`"one": ${severity},`), + errors: [explanation], + })), + { + code: configuration('"one": "off", // '), + errors: [explanation], + }, + { + code: configuration('"one": "off", /* */'), + errors: [explanation], + }, + { + code: configuration('// CLI output is intentional.\n"one": "off",'), + errors: [explanation], + }, + { + code: configuration('"one": "off",\n// CLI output is intentional.'), + errors: [explanation], + }, + { + code: configuration( + '"one": [\n "deny",\n { max: 2 },\n], // Too far from the modifier.', + ), + errors: [explanation], + }, + { + code: configuration( + '"one": "off", "two": "off", // This explains only two.', + ), + errors: [explanation], + }, + { + code: 'import type { DummyRuleMap } from "oxlint"; defineRules({ one: "off" });', + errors: [explanation], + filename: "config-factory.ts", + }, + { + code: 'import { createConfig } from "@local/oxlint"; const rules = { one: "off" };', + errors: [explanation], + }, + { + code: 'export default { overrides: [{ files: ["test.ts"], rules: { one: "off" } }] };', + errors: [explanation], + filename: "oxlint.config.ts", + }, + { + code: configuration( + '"one": "off", /*\nReason starts on the next line.\n*/', + ), + errors: [explanation], + }, + { + code: 'export default { rules: { one: "off" } }; // Outside the rule map.', + errors: [explanation], + filename: ".oxlintrc.mjs", + }, + ], + valid: [ + { + code: 'import { defineConfig } from "oxlint"; const rules = { one: "off" as const, // CLI output is intentional.\n} as const;', + filename: "config-factory.ts", + }, + { + code: 'import { defineConfig } from "oxlint"; defineRules(({ one: ["off", // CLI output is intentional.\n] }) satisfies DummyRuleMap);', + filename: "config-factory.ts", + }, + configuration('"one": "off", // CLI output is intentional.'), + configuration('"one": "warn", /* Migration remains in progress. */'), + configuration('"one": ["deny", { max: 2 }], // Limit public API arity.'), + configuration( + '"one": [\n "deny", // Limit public API arity.\n { max: 2 },\n],', + ), + configuration( + '"one": "off", /* First reason. */ "two": "off", // Second reason.', + ), + configuration('"one": inheritedSetting,\n...inheritedRules,'), + configuration('"one": [],'), + 'const validation = { rules: { one: "off" } };', + 'defineRules({ one: "off" });', + 'import { defineConfig } from "vitest/config"; defineConfig({ rules: { one: "off" } });', + 'import { defineConfig } from "oxlint"; const categories = { correctness: "deny" };', + 'import { defineConfig } from "oxlint"; const plugin = { rules: { one: implementation } };', + 'import { defineConfig } from "oxlint"; const config = { rules: { ...otherRules } };', + ], +}); diff --git a/libs/@local/oxlint/src/rules/require-rule-change-comment.ts b/libs/@local/oxlint/src/rules/require-rule-change-comment.ts new file mode 100644 index 00000000000..f5b87165fbe --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-rule-change-comment.ts @@ -0,0 +1,180 @@ +/** + * Requires explanations beside literal severity settings in Oxlint configuration. + * + * Checks `rules` objects and `defineRules` arguments in files that import Oxlint or use its configuration filename. Tuple settings put the explanation beside the first element. Computed settings and inherited presets are not resolved. + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +import type { ESTree, SourceCode } from "@oxlint/plugins"; + +const severities: ReadonlySet = new Set([ + "allow", + "off", + "warn", + "deny", + "error", +]); + +const propertyName = ( + property: Pick, +): string | null => { + if (!property.computed && property.key.type === "Identifier") { + return property.key.name; + } + + if ( + property.key.type === "Literal" && + typeof property.key.value === "string" + ) { + return property.key.value; + } + + return null; +}; + +type TransparentExpression = + | ESTree.ParenthesizedExpression + | ESTree.TSAsExpression + | ESTree.TSSatisfiesExpression + | ESTree.TSTypeAssertion + | ESTree.TSNonNullExpression; + +const isTransparentExpression = ( + node: ESTree.Node, +): node is TransparentExpression => + node.type === "ParenthesizedExpression" || + node.type === "TSAsExpression" || + node.type === "TSSatisfiesExpression" || + node.type === "TSTypeAssertion" || + node.type === "TSNonNullExpression"; + +const unwrapExpression = (node: ESTree.Node): ESTree.Node => { + let expression = node; + + while (isTransparentExpression(expression)) { + expression = expression.expression; + } + + return expression; +}; + +const isRuleMap = (node: ESTree.ObjectExpression): boolean => { + let expression: ESTree.Node = node; + while (isTransparentExpression(expression.parent)) { + expression = expression.parent; + } + + const { parent } = expression; + if (parent.type === "Property") { + return parent.value === expression && propertyName(parent) === "rules"; + } + + if (parent.type === "CallExpression") { + return ( + parent.callee.type === "Identifier" && + parent.callee.name === "defineRules" && + parent.arguments[0] === expression + ); + } + + return ( + parent.type === "VariableDeclarator" && + parent.id.type === "Identifier" && + parent.id.name === "rules" + ); +}; + +const severityOf = (value: ESTree.Node): ESTree.Node | null => { + let candidate = unwrapExpression(value); + if (candidate.type === "ArrayExpression") { + const [first] = candidate.elements; + if (first === null || first === undefined) { + return null; + } + + candidate = unwrapExpression(first); + } + + if (candidate.type !== "Literal") { + return null; + } + + if (typeof candidate.value === "string" && severities.has(candidate.value)) { + return candidate; + } + + if (candidate.value === 0 || candidate.value === 1 || candidate.value === 2) { + return candidate; + } + + return null; +}; + +const hasExplanation = ( + sourceCode: SourceCode, + severity: ESTree.Node, + end: number, +): boolean => + sourceCode.getAllComments().some((comment) => { + if ( + comment.loc.start.line !== severity.loc.end.line || + comment.range[0] < severity.range[1] || + comment.range[0] >= end + ) { + return false; + } + + const [firstLine] = comment.value.split("\n"); + return firstLine !== undefined && firstLine.trim().length > 0; + }); + +export const requireRuleChangeComment = defineRule({ + createOnce: (context) => { + let configuration = false; + + return { + Program: (program): void => { + configuration = + /(?:^|[/\\])(?:oxlint\.config|\.oxlintrc)\.[cm]?[jt]s$/u.test( + context.filename, + ) || + program.body.some( + (statement) => + statement.type === "ImportDeclaration" && + (statement.source.value === "oxlint" || + statement.source.value === "@local/oxlint"), + ); + }, + ObjectExpression: (node): void => { + if (!configuration || !isRuleMap(node)) { + return; + } + + for (const [index, property] of node.properties.entries()) { + if (property.type === "Property") { + const severity = severityOf(property.value); + const end = node.properties[index + 1]?.range[0] ?? node.range[1]; + + if ( + severity !== null && + !hasExplanation(context.sourceCode, severity, end) + ) { + context.report({ messageId: "explanation", node: severity }); + } + } + } + }, + }; + }, + meta: { + messages: { + explanation: + "Explain this rule setting in a trailing comment on the severity's line. For an array setting, put the comment beside its first element.", + }, + schema: [], + type: "problem", + }, +}); diff --git a/libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.test.ts b/libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.test.ts new file mode 100644 index 00000000000..25a8737d925 --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.test.ts @@ -0,0 +1,87 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { requireSafetyCommentForTypeAssertion } from "./require-safety-comment-for-type-assertion.js"; + +const tester = new RuleTester({ + languageOptions: { parserOptions: { lang: "ts" } }, +}); +const error = { messageId: "safetyComment" }; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run( + "require-safety-comment-for-type-assertion", + requireSafetyCommentForTypeAssertion, + { + invalid: [ + { code: "const value = input as Message;", errors: [error] }, + { code: "const value = input;", errors: [error] }, + { + code: "const value = input as Message; // SAFETY: Too late.", + errors: [error], + }, + { + code: "// The schema is checked.\nconst value = input as Message;", + errors: [error], + }, + { code: "// SAFETY:\nconst value = input as Message;", errors: [error] }, + { + code: "/* SAFETY:\n *\n */\nconst value = input as Message;", + errors: [error], + }, + { + code: "const value = /* SAFETY: */ input as Message;", + errors: [error], + }, + { + code: "// UNSAFETY: Not a safety marker.\nconst value = input as Message;", + errors: [error], + }, + { + code: "// safety: Wrong marker.\nconst value = input as Message;", + errors: [error], + }, + { + code: "// SAFETY: Applies to the previous declaration.\nconst first = 1;\nconst value = input as Message;", + errors: [error], + }, + { + code: "const first = 1; // SAFETY: Applies to the previous declaration.\nconst value = input as Message;", + errors: [error], + }, + { + code: "// SAFETY: Not a justification for arbitrary statements in the function.\nfunction parse() { return input as Message; }", + errors: [error], + }, + { + code: "// SAFETY: Not a justification for a later field.\nclass Reader { value = input as Message; }", + errors: [error], + }, + { + code: "const value = input as unknown as Message;", + errors: [error, error], + }, + { code: "export const value = input as Message;", errors: [error] }, + { + code: "const value = /* SAFETY: The first conversion is checked. */ (input as Message); const second = other as Message;", + errors: [error], + }, + ], + valid: [ + "const value = { id: 1 } as const;", + "const value = { id: 1 };", + "const value = { id: 1 } satisfies Message;", + "const value = input!;", + "// SAFETY: The schema validates this value.\nconst value = input as Message;", + "/* SAFETY:\n * The schema validates this value.\n */\nconst value = input as Message;", + "const value = /* SAFETY: The schema validates this value. */ input as Message;", + "// SAFETY: The schema validates both values.\nconst values = [first as Message, second as Message];", + "// SAFETY: The schema validates this value.\nexport const value = input as Message;", + "// SAFETY: The schema validates this value.\nexport default input as Message;", + "function parse() {\n// SAFETY: The schema validates this value.\nreturn input as Message;\n}", + "class Reader {\n// SAFETY: The schema validates this value.\nvalue = input as Message;\n}", + "// SAFETY: The schema validates every returned value.\nconst parse = () => input as Message;", + "// SAFETY: The conversion follows the checked external layout.\nconst value = input as unknown as Message;", + "// SAFETY: The schema validates this value.\nconst value = input;", + ], + }, +); diff --git a/libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.ts b/libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.ts new file mode 100644 index 00000000000..cff764fd532 --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-safety-comment-for-type-assertion.ts @@ -0,0 +1,130 @@ +/** + * Requires a nonempty SAFETY: justification before every non-const type assertion. + * + * A preceding comment can justify an individual assertion or its containing statement. The rule checks for an explanation, not whether that explanation is true. Provides no autofix because the author must supply the reasoning. + * + * @example Incorrect + * ```ts + * const payload = value as Payload; + * ``` + * + * @example Correct + * ```ts + * // SAFETY: validatePayload(value) succeeded before this statement. + * const payload = value as Payload; + * ``` + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +import type { ESTree, SourceCode } from "@oxlint/plugins"; + +type TypeAssertion = ESTree.TSAsExpression | ESTree.TSTypeAssertion; + +const isConstAssertion = (assertion: TypeAssertion): boolean => + assertion.typeAnnotation.type === "TSTypeReference" && + assertion.typeAnnotation.typeName.type === "Identifier" && + assertion.typeAnnotation.typeName.name === "const"; + +const isCommentOwner = (node: ESTree.Node): boolean => + node.type.endsWith("Statement") || + node.type === "VariableDeclaration" || + node.type === "PropertyDefinition" || + node.type === "AccessorProperty"; + +const commentOwner = (assertion: TypeAssertion): ESTree.Node => { + let owner: ESTree.Node = assertion; + while (!isCommentOwner(owner) && owner.parent.type !== "Program") { + owner = owner.parent; + } + + if ( + owner.parent.type === "ExportNamedDeclaration" || + owner.parent.type === "ExportDefaultDeclaration" + ) { + return owner.parent; + } + + return owner; +}; + +const isJustification = (comment: ESTree.Comment): boolean => + /^\s*SAFETY:\s*\S/mu.test(comment.value.replaceAll(/^\s*\* ?/gmu, "")); + +const hasJustificationBefore = ( + sourceCode: SourceCode, + owner: ESTree.Node, + node: ESTree.Node, +): boolean => { + let current: ESTree.Node | ESTree.Token = node; + for (;;) { + const justified = sourceCode.getCommentsBefore(current).some((comment) => { + if (!isJustification(comment)) { + return false; + } + + // A trailing comment on the preceding statement does not justify this statement. + return ( + comment.range[0] >= owner.range[0] || + sourceCode.lines[comment.loc.start.line - 1] + ?.slice(0, comment.loc.start.column) + .trim() === "" + ); + }); + + if (justified) { + return true; + } + + const previous: ESTree.Token | null = sourceCode.getTokenBefore(current); + if (previous?.value !== "(" || previous.range[0] < owner.range[0]) { + return false; + } + current = previous; + } +}; + +const hasSafetyComment = ( + sourceCode: SourceCode, + assertion: TypeAssertion, +): boolean => { + const owner = commentOwner(assertion); + let current: ESTree.Node = assertion; + for (;;) { + if (hasJustificationBefore(sourceCode, owner, current)) { + return true; + } + if (current === owner || current.parent === null) { + return false; + } + current = current.parent; + } +}; + +export const requireSafetyCommentForTypeAssertion = defineRule({ + createOnce: (context) => { + const checkAssertion = (assertion: TypeAssertion): void => { + if ( + !isConstAssertion(assertion) && + !hasSafetyComment(context.sourceCode, assertion) + ) { + context.report({ messageId: "safetyComment", node: assertion }); + } + }; + + return { + TSAsExpression: checkAssertion, + TSTypeAssertion: checkAssertion, + }; + }, + meta: { + messages: { + safetyComment: + "Explain why this assertion is valid in a preceding SAFETY: comment. Const assertions do not need a justification.", + }, + schema: [], + type: "problem", + }, +}); diff --git a/libs/@local/oxlint/src/rules/require-suppression-comment.test.ts b/libs/@local/oxlint/src/rules/require-suppression-comment.test.ts new file mode 100644 index 00000000000..e8b0988249e --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-suppression-comment.test.ts @@ -0,0 +1,65 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { requireSuppressionComment } from "./require-suppression-comment.js"; + +const tester = new RuleTester(); + +const allRules = { messageId: "allRules" }; +const justification = { messageId: "justification" }; +const multipleRules = { messageId: "multipleRules" }; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("require-suppression-comment", requireSuppressionComment, { + invalid: [ + { + code: "// oxlint-disable-next-line no-console\nconsole.log();", + errors: [justification], + }, + { + code: "console.log(); // oxlint-disable-line no-console -- ", + errors: [justification], + }, + { code: "/* oxlint-disable -- legacy file */", errors: [allRules] }, + { + code: "// oxlint-disable-next-line\nconsole.log();", + errors: [allRules, justification], + }, + { + code: "// oxlint-disable-next-line no-console, no-var -- legacy\nvar a = console;", + errors: [ + { data: { rules: "no-console, no-var" }, messageId: "multipleRules" }, + ], + }, + { + code: "/* eslint-disable no-console, no-var */", + errors: [multipleRules, justification], + }, + { + code: "// oxlint-disable-next-line no-console , no-var -- legacy\nvar a = console;", + errors: [ + { data: { rules: "no-console, no-var" }, messageId: "multipleRules" }, + ], + }, + // Each report points to the directive's own comment. Oxlint's columns are 0-indexed. + { + code: [ + "/* oxlint-disable no-console -- generated file */", + "const a = 1; // oxlint-disable-line no-unused-vars", + "// oxlint-disable-next-line", + "const b = 2;", + ].join("\n"), + errors: [ + { column: 13, line: 2, messageId: "justification" }, + { column: 0, line: 3, messageId: "allRules" }, + { column: 0, line: 3, messageId: "justification" }, + ], + }, + ], + valid: [ + "// oxlint-disable-next-line no-console -- the CLI reports progress on stdout\nconsole.log();", + "/* oxlint-disable no-console -- generated file */\n/* oxlint-enable */", + "console.log(); // eslint-disable-line no-console -- debugging aid", + "// oxlint-disable-next-line unicorn/no-null -- the API distinguishes null from undefined\nconst a = null;", + "// a regular comment, mentioning oxlint-disable in passing", + ], +}); diff --git a/libs/@local/oxlint/src/rules/require-suppression-comment.ts b/libs/@local/oxlint/src/rules/require-suppression-comment.ts new file mode 100644 index 00000000000..7da31ed8343 --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-suppression-comment.ts @@ -0,0 +1,66 @@ +/** + * Requires lint suppressions to name exactly one rule and give a nonempty reason after `--`. + * + * Checks oxlint-disable and eslint-disable directives, including line-scoped forms. Enable directives only end suppressions and are not checked. Provides no autofix because the author must choose the rule and explain the exception. + * + * @example Incorrect + * ```ts + * // oxlint-disable-next-line no-console + * console.log("Ready."); + * ``` + * + * @example Correct + * ```ts + * // oxlint-disable-next-line no-console -- This CLI writes its result to stdout. + * console.log("Ready."); + * ``` + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +export const requireSuppressionComment = defineRule({ + createOnce: (context) => ({ + "Program:exit": (): void => { + const { directives } = context.sourceCode.getDisableDirectives(); + + for (const directive of directives) { + if (directive.type !== "enable") { + const rules = directive.value + .split(",") + .map((rule) => rule.trim()) + .filter((rule) => rule.length > 0); + + if (rules.length === 0) { + context.report({ messageId: "allRules", node: directive.node }); + } else if (rules.length > 1) { + context.report({ + data: { rules: rules.join(", ") }, + messageId: "multipleRules", + node: directive.node, + }); + } + + if (directive.justification.trim().length === 0) { + context.report({ + messageId: "justification", + node: directive.node, + }); + } + } + } + }, + }), + meta: { + messages: { + allRules: + "Name the rule to disable; a directive without a rule disables every rule.", + justification: + 'Explain why the rule is disabled after "--", e.g. "oxlint-disable-next-line rule -- reason".', + multipleRules: + "Disable one rule per directive, each with its own justification, instead of {{rules}}.", + }, + type: "problem", + }, +}); diff --git a/libs/@local/oxlint/tsconfig.json b/libs/@local/oxlint/tsconfig.json new file mode 100644 index 00000000000..d54c7cbc41c --- /dev/null +++ b/libs/@local/oxlint/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": ["@tsconfig/bases/strictest", "@local/tsconfig/policy.json"], + "compilerOptions": { + "types": ["node"], + "module": "NodeNext", + "moduleResolution": "NodeNext" + }, + "include": [ + "src", + "oxlint.config.ts", + "tsdown.config.ts", + "vitest.config.ts" + ], + "exclude": ["dist"] +} diff --git a/libs/@local/oxlint/tsdown.config.ts b/libs/@local/oxlint/tsdown.config.ts new file mode 100644 index 00000000000..b218a5e54c4 --- /dev/null +++ b/libs/@local/oxlint/tsdown.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "tsdown"; + +export default defineConfig({ + dts: true, + entry: ["src/index.ts", "src/rules/index.ts"], + fixedExtension: false, + format: "esm", + platform: "node", +}); diff --git a/libs/@local/oxlint/turbo.json b/libs/@local/oxlint/turbo.json new file mode 100644 index 00000000000..0ff73890dfa --- /dev/null +++ b/libs/@local/oxlint/turbo.json @@ -0,0 +1,18 @@ +{ + "extends": ["//"], + "tasks": { + "build": { + "dependsOn": ["prepare:oxlint"], + "outputs": ["dist/**"] + }, + "lint:oxlint": { + "dependsOn": ["build"] + }, + "lint:tsc": { + "dependsOn": ["build"] + }, + "test:unit": { + "dependsOn": ["build"] + } + } +} diff --git a/libs/@local/oxlint/vitest.config.ts b/libs/@local/oxlint/vitest.config.ts new file mode 100644 index 00000000000..96dd0982ada --- /dev/null +++ b/libs/@local/oxlint/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + // Oxlint's RuleTester registers its cases through the test framework's globals. + globals: true, + include: ["src/**/*.test.ts"], + }, +}); diff --git a/libs/@local/petrinaut-arch-docs/package.json b/libs/@local/petrinaut-arch-docs/package.json index 2468badce41..1b0f5c2b7f3 100644 --- a/libs/@local/petrinaut-arch-docs/package.json +++ b/libs/@local/petrinaut-arch-docs/package.json @@ -33,7 +33,7 @@ "@tsconfig/bases": "catalog:", "@types/js-yaml": "^4", "@types/node": "catalog:", - "oxlint": "1.86.0", + "oxlint": "catalog:", "tsx": "catalog:", "typescript": "catalog:", "vite": "catalog:", diff --git a/libs/@local/pi-faux-providers/package.json b/libs/@local/pi-faux-providers/package.json index 4b73971d53a..75ec2e0316c 100644 --- a/libs/@local/pi-faux-providers/package.json +++ b/libs/@local/pi-faux-providers/package.json @@ -27,8 +27,8 @@ "@local/tsconfig": "workspace:*", "@tsconfig/bases": "catalog:", "@types/node": "catalog:", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "typescript": "catalog:" } } diff --git a/package.json b/package.json index 44bbef9af89..9e72d1d3cf0 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "lint:format": "oxfmt --check", "lint:license-in-workspaces": "yarn workspace @local/repo-chores exe scripts/check-license-in-workspaces.ts", "lint:markdownlint": "mise exec --env dev markdownlint-cli2 -- markdownlint-cli2", + "lint:oxlint": "CARGO_TERM_PROGRESS_WHEN=never turbo --continue=always lint:oxlint --", "lint:ruff": "turbo run lint:ruff --continue=always --filter '!hash-python'", "lint:skill": "yarn agents:skill-management validate", "lint:tach": "turbo run lint:tach --continue=always --filter '!hash-python'", @@ -61,6 +62,7 @@ "lint:tsc": "mise run lint:tsc", "lint:ty": "turbo run check:ty --continue=always --filter '!hash-python'", "lint:yarn-deduplicate": "yarn dedupe --strategy highest --check", + "prepare:oxlint": "CARGO_TERM_PROGRESS_WHEN=never turbo run prepare:oxlint --filter @local/oxlint", "prune-node-modules": "find . -type d -name \"node_modules\" -exec rm -rf {} +", "start": "CARGO_TERM_PROGRESS_WHEN=never turbo run start start:healthcheck --filter hash-graph --filter @apps/hash-api --filter @apps/hash-ai-worker-ts --filter @apps/hash-integration-worker --filter @apps/hash-frontend --env-mode=loose", "start:backend": "CARGO_TERM_PROGRESS_WHEN=never turbo run start start:healthcheck --filter @apps/hash-api --env-mode=loose", diff --git a/tests/petrinaut-brunch-integration/package.json b/tests/petrinaut-brunch-integration/package.json index 23e3be14ea6..f708e9a872e 100644 --- a/tests/petrinaut-brunch-integration/package.json +++ b/tests/petrinaut-brunch-integration/package.json @@ -32,8 +32,8 @@ "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "jsdom": "24.1.3", - "oxlint": "1.86.0", - "oxlint-tsgolint": "7.0.2003", + "oxlint": "catalog:", + "oxlint-tsgolint": "catalog:", "typescript": "catalog:", "vite": "catalog:", "vitest": "catalog:" diff --git a/turbo.json b/turbo.json index feedc5c1b17..8089257d0d9 100644 --- a/turbo.json +++ b/turbo.json @@ -112,6 +112,10 @@ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/infra/compose/**"] }, // Linting and formatting + // Patching writes node_modules, which an artifact cache cannot restore. + "prepare:oxlint": { + "cache": false + }, "lint": {}, // The clippy invocation differs between pull requests (`--all-features`) and other runs // such as the merge queue (`cargo hack --feature-powerset`), selected via @@ -126,6 +130,9 @@ "env": ["CHECK_TEMPORARILY_DISABLED_RULES"], "dependsOn": ["codegen", "^build", "@local/eslint#build"] }, + "lint:oxlint": { + "dependsOn": ["codegen", "^build"] + }, "lint:tsc": { "dependsOn": ["codegen", "^build"] }, diff --git a/yarn.lock b/yarn.lock index c89061ba39d..2e64d97a69e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -422,8 +422,8 @@ __metadata: ai: "npm:6.0.286" dependency-cruiser: "npm:18.0.0" hono: "npm:4.13.13" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" pg: "npm:8.23.0" react: "npm:19.2.6" react-dom: "npm:19.2.6" @@ -912,8 +912,8 @@ __metadata: jsdom: "npm:24.1.3" monaco-editor: "npm:0.55.1" oxc-transform-react: "npm:0.152.0" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" react: "npm:19.2.6" react-dom: "npm:19.2.6" react-icons: "npm:5.5.0" @@ -5219,6 +5219,87 @@ __metadata: languageName: node linkType: hard +"@effect/tsgo-darwin-arm64@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo-darwin-arm64@npm:0.47.1" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@effect/tsgo-darwin-x64@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo-darwin-x64@npm:0.47.1" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@effect/tsgo-linux-arm64@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo-linux-arm64@npm:0.47.1" + conditions: os=linux & cpu=arm64 + languageName: node + linkType: hard + +"@effect/tsgo-linux-arm@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo-linux-arm@npm:0.47.1" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"@effect/tsgo-linux-x64@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo-linux-x64@npm:0.47.1" + conditions: os=linux & cpu=x64 + languageName: node + linkType: hard + +"@effect/tsgo-win32-arm64@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo-win32-arm64@npm:0.47.1" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@effect/tsgo-win32-x64@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo-win32-x64@npm:0.47.1" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + +"@effect/tsgo@npm:0.47.1": + version: 0.47.1 + resolution: "@effect/tsgo@npm:0.47.1" + dependencies: + "@effect/tsgo-darwin-arm64": "npm:0.47.1" + "@effect/tsgo-darwin-x64": "npm:0.47.1" + "@effect/tsgo-linux-arm": "npm:0.47.1" + "@effect/tsgo-linux-arm64": "npm:0.47.1" + "@effect/tsgo-linux-x64": "npm:0.47.1" + "@effect/tsgo-win32-arm64": "npm:0.47.1" + "@effect/tsgo-win32-x64": "npm:0.47.1" + dependenciesMeta: + "@effect/tsgo-darwin-arm64": + optional: true + "@effect/tsgo-darwin-x64": + optional: true + "@effect/tsgo-linux-arm": + optional: true + "@effect/tsgo-linux-arm64": + optional: true + "@effect/tsgo-linux-x64": + optional: true + "@effect/tsgo-win32-arm64": + optional: true + "@effect/tsgo-win32-x64": + optional: true + bin: + effect-tsgo: dist/effect-tsgo.cjs + checksum: 10c0/37bdf7d08e8320994e1a78c34e9d188e7c8588e0065d0bc26596755aa11fbd36b8ee5e42904dd891f8eb1cd04e1490e36f9e4426c72190bb7638e85d82fcd77e + languageName: node + linkType: hard + "@effect/vitest@npm:4.0.3": version: 4.0.3 resolution: "@effect/vitest@npm:4.0.3" @@ -7477,8 +7558,8 @@ __metadata: "@tsconfig/bases": "catalog:" "@types/node": "catalog:" md-pen: "npm:1.2.0" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" typescript: "catalog:" valibot: "npm:1.4.2" vite: "catalog:" @@ -7621,8 +7702,8 @@ __metadata: "@vitejs/plugin-react": "npm:6.1.1" jsdom: "npm:24.1.3" oxc-transform-react: "npm:0.152.0" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" react: "npm:19.2.6" react-dom: "npm:19.2.6" rolldown: "npm:1.2.6" @@ -7658,8 +7739,8 @@ __metadata: "@types/node": "catalog:" "@typescript/typescript6": "catalog:" oxfmt: "npm:0.71.0" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" tsx: "catalog:" typescript: "catalog:" vite: "catalog:" @@ -7686,8 +7767,8 @@ __metadata: elkjs: "npm:0.11.0" immer: "npm:10.1.3" js-yaml: "npm:4.3.2" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" pyodide: "npm:314.0.6" rolldown: "npm:1.2.6" rolldown-plugin-dts: "npm:0.28.3" @@ -7742,8 +7823,8 @@ __metadata: lodash-es: "npm:4.18.1" monaco-editor: "npm:0.55.1" oxc-transform-react: "npm:0.152.0" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" react: "npm:19.2.6" react-dom: "npm:19.2.6" react-markdown: "npm:10.1.0" @@ -7809,8 +7890,8 @@ __metadata: "@vitejs/plugin-react": "npm:6.1.1" jsdom: "npm:24.1.3" oxc-transform-react: "npm:0.152.0" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" react: "npm:19.2.6" react-dom: "npm:19.2.6" rolldown: "npm:1.2.6" @@ -9773,8 +9854,8 @@ __metadata: "@tsconfig/bases": "catalog:" "@types/node": "catalog:" ai: "npm:6.0.286" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" typescript: "catalog:" valibot: "npm:1.4.2" vite: "catalog:" @@ -10047,6 +10128,24 @@ __metadata: languageName: unknown linkType: soft +"@local/oxlint@workspace:libs/@local/oxlint": + version: 0.0.0-use.local + resolution: "@local/oxlint@workspace:libs/@local/oxlint" + dependencies: + "@effect/tsgo": "npm:0.47.1" + "@local/tsconfig": "workspace:*" + "@oxlint/plugins": "catalog:" + "@tsconfig/bases": "catalog:" + "@types/node": "catalog:" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" + tsdown: "npm:0.23.0" + typescript: "catalog:" + vite: "catalog:" + vitest: "catalog:" + languageName: unknown + linkType: soft + "@local/petrinaut-arch-docs@workspace:*, @local/petrinaut-arch-docs@workspace:libs/@local/petrinaut-arch-docs": version: 0.0.0-use.local resolution: "@local/petrinaut-arch-docs@workspace:libs/@local/petrinaut-arch-docs" @@ -10061,7 +10160,7 @@ __metadata: "@types/node": "catalog:" dependency-cruiser: "npm:18.0.0" js-yaml: "npm:4.3.2" - oxlint: "npm:1.86.0" + oxlint: "catalog:" tsx: "catalog:" typescript: "catalog:" vite: "catalog:" @@ -10101,8 +10200,8 @@ __metadata: "@local/tsconfig": "workspace:*" "@tsconfig/bases": "catalog:" "@types/node": "catalog:" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" typescript: "catalog:" languageName: unknown linkType: soft @@ -12461,6 +12560,13 @@ __metadata: languageName: node linkType: hard +"@oxlint/plugins@npm:1.86.0": + version: 1.86.0 + resolution: "@oxlint/plugins@npm:1.86.0" + checksum: 10c0/4eddfc296610b1cdc6117e47b4732c64b1d15a11bce0401c8a64a58575e67fe97ca6ead8b6bf5ea2bcac2971a33e267d7b8ae8acff77df33e398f75a27505a5d + languageName: node + linkType: hard + "@pagefind/darwin-arm64@npm:1.5.2": version: 1.5.2 resolution: "@pagefind/darwin-arm64@npm:1.5.2" @@ -13282,6 +13388,15 @@ __metadata: languageName: node linkType: hard +"@quansync/fs@npm:^1.0.0": + version: 1.1.0 + resolution: "@quansync/fs@npm:1.1.0" + dependencies: + quansync: "npm:^1.0.0" + checksum: 10c0/fa7bca4eae8ec036bfe3181304bf827f10f798ac485d698e7d72fde98c5786f8685aecf2c0f8d5f7fdff8608487c9d62794ba5f4def02518d6835ecda6d8e4cc + languageName: node + linkType: hard + "@radix-ui/colors@npm:3.0.0": version: 3.0.0 resolution: "@radix-ui/colors@npm:3.0.0" @@ -17692,8 +17807,8 @@ __metadata: "@types/react-dom": "npm:19.2.3" ai: "npm:6.0.286" jsdom: "npm:24.1.3" - oxlint: "npm:1.86.0" - oxlint-tsgolint: "npm:7.0.2003" + oxlint: "catalog:" + oxlint-tsgolint: "catalog:" react: "npm:19.2.6" react-dom: "npm:19.2.6" typescript: "catalog:" @@ -20683,6 +20798,90 @@ __metadata: languageName: node linkType: hard +"@yuku-core/binding-android-arm64@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-android-arm64@npm:0.19.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-core/binding-darwin-arm64@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-darwin-arm64@npm:0.19.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-core/binding-darwin-x64@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-darwin-x64@npm:0.19.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@yuku-core/binding-freebsd-x64@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-freebsd-x64@npm:0.19.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@yuku-core/binding-linux-arm-gnu@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-linux-arm-gnu@npm:0.19.0" + conditions: os=linux & cpu=arm & libc=glibc + languageName: node + linkType: hard + +"@yuku-core/binding-linux-arm-musl@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-linux-arm-musl@npm:0.19.0" + conditions: os=linux & cpu=arm & libc=musl + languageName: node + linkType: hard + +"@yuku-core/binding-linux-arm64-gnu@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-linux-arm64-gnu@npm:0.19.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@yuku-core/binding-linux-arm64-musl@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-linux-arm64-musl@npm:0.19.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@yuku-core/binding-linux-x64-gnu@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-linux-x64-gnu@npm:0.19.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@yuku-core/binding-linux-x64-musl@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-linux-x64-musl@npm:0.19.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@yuku-core/binding-win32-arm64@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-win32-arm64@npm:0.19.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-core/binding-win32-x64@npm:0.19.0": + version: 0.19.0 + resolution: "@yuku-core/binding-win32-x64@npm:0.19.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@yuku-parser/binding-android-arm64@npm:0.9.3": version: 0.9.3 resolution: "@yuku-parser/binding-android-arm64@npm:0.9.3" @@ -20767,6 +20966,13 @@ __metadata: languageName: node linkType: hard +"@yuku-toolchain/types@npm:^0.19.0": + version: 0.19.0 + resolution: "@yuku-toolchain/types@npm:0.19.0" + checksum: 10c0/3ad5a4c8ec7009432acbc002c5ff484624bdd534c071485894e0f7a88305057416eedff688255022187591c53bb382f252604dd32f42a5e4de575775868e05a6 + languageName: node + linkType: hard + "@yuku-toolchain/types@npm:^0.9.3": version: 0.9.3 resolution: "@yuku-toolchain/types@npm:0.9.3" @@ -24988,7 +25194,7 @@ __metadata: languageName: node linkType: hard -"defu@npm:^6.1.6": +"defu@npm:^6.1.6, defu@npm:^6.1.7": version: 6.1.7 resolution: "defu@npm:6.1.7" checksum: 10c0/e6635388103c8be3c574ac31302f6930e5e6eeedba32cb1b30cf993c7d9fb571aec2485446dfa23bfa63e55e66156fe109027a9695db82a50f931e91e8d4bedb @@ -29635,6 +29841,13 @@ __metadata: languageName: node linkType: hard +"hookable@npm:^6.1.1": + version: 6.1.2 + resolution: "hookable@npm:6.1.2" + checksum: 10c0/ea5cdb1b1a1919b48cfbbfb55c8009f6843473ff50f67d6e959fd291cb2fd0a4934e85124bfd6531b1d2edf1e0675bc5954f85a12318a59b15c7a3e5667f0d4e + languageName: node + linkType: hard + "hookified@npm:^1.12.1": version: 1.12.2 resolution: "hookified@npm:1.12.2" @@ -30343,6 +30556,13 @@ __metadata: languageName: node linkType: hard +"import-without-cache@npm:^0.4.0": + version: 0.4.1 + resolution: "import-without-cache@npm:0.4.1" + checksum: 10c0/85c7f1581605813a892ce44d0b93e94c44f60f76fe558865b0a94f7b6ac3c6b6486388ca8d125e7b108ae1dedaebfc1f8adf67f3783ade0406c8c93ae9cfe656 + languageName: node + linkType: hard + "imurmurhash@npm:^0.1.4": version: 0.1.4 resolution: "imurmurhash@npm:0.1.4" @@ -37550,6 +37770,13 @@ __metadata: languageName: node linkType: hard +"quansync@npm:^1.0.0": + version: 1.0.0 + resolution: "quansync@npm:1.0.0" + checksum: 10c0/076542634399a0cc46078baab6b31acee7a88c5a435234345f645aedaa42bc6a63836e655fb39b1b21a83c98ec86a4b73ec5e2b2d6f3fdc22711eeeff9463253 + languageName: node + linkType: hard + "querystringify@npm:^2.1.1": version: 2.2.0 resolution: "querystringify@npm:2.2.0" @@ -39196,6 +39423,38 @@ __metadata: languageName: node linkType: hard +"rolldown-plugin-dts@npm:^0.28.5": + version: 0.28.8 + resolution: "rolldown-plugin-dts@npm:0.28.8" + dependencies: + dts-resolver: "npm:^3.0.0" + get-tsconfig: "npm:5.0.0-beta.6" + obug: "npm:^3.0.0" + yuku-ast: "npm:^0.19.0" + yuku-codegen: "npm:^0.19.0" + yuku-parser: "npm:^0.19.0" + peerDependencies: + "@typescript/native-preview": "*" + "@volar/typescript": ~2.4.0 + "@vue/language-core": ~3.2.0 || ~3.3.0 + rolldown: ^1.2.0 + typescript: ^5.0.0 || ^6.0.0 || ~7.0.0 + vue-tsc: ~3.2.0 || ~3.3.0 + peerDependenciesMeta: + "@typescript/native-preview": + optional: true + "@volar/typescript": + optional: true + "@vue/language-core": + optional: true + typescript: + optional: true + vue-tsc: + optional: true + checksum: 10c0/fb6a91543b3a328b646a9c4c21e80fa4608d7b7e3982cd7db9c327445a386082ead3455fac0f60eff740169ec2414ce916f745f5b92045e2e8d4b3a400ee4232 + languageName: node + linkType: hard + "rolldown@npm:1.2.6": version: 1.2.6 resolution: "rolldown@npm:1.2.6" @@ -39254,7 +39513,7 @@ __metadata: languageName: node linkType: hard -"rolldown@npm:^1.2.13, rolldown@npm:~1.2.12, rolldown@npm:~1.2.14": +"rolldown@npm:^1.2.13, rolldown@npm:~1.2.12, rolldown@npm:~1.2.14, rolldown@npm:~1.2.7": version: 1.2.15 resolution: "rolldown@npm:1.2.15" dependencies: @@ -41938,6 +42197,59 @@ __metadata: languageName: node linkType: hard +"tsdown@npm:0.23.0": + version: 0.23.0 + resolution: "tsdown@npm:0.23.0" + dependencies: + cac: "npm:^7.0.0" + defu: "npm:^6.1.7" + empathic: "npm:^2.0.1" + hookable: "npm:^6.1.1" + import-without-cache: "npm:^0.4.0" + obug: "npm:^2.1.4" + picomatch: "npm:^4.0.7" + rolldown: "npm:~1.2.7" + rolldown-plugin-dts: "npm:^0.28.5" + tinyexec: "npm:^1.3.1" + tinyglobby: "npm:^0.2.17" + tree-kill: "npm:^1.2.2" + unconfig-core: "npm:^7.5.0" + verkit: "npm:^0.4.0" + peerDependencies: + "@arethetypeswrong/core": ^0.18.1 + "@tsdown/css": 0.23.0 + "@tsdown/exe": 0.23.0 + "@vitejs/devtools": "*" + publint: ^0.3.8 + tsx: "*" + typescript: ^5.0.0 || ^6.0.0 || ^7.0.0 + unplugin-unused: ">=0.5.0" + unrun: "*" + peerDependenciesMeta: + "@arethetypeswrong/core": + optional: true + "@tsdown/css": + optional: true + "@tsdown/exe": + optional: true + "@vitejs/devtools": + optional: true + publint: + optional: true + tsx: + optional: true + typescript: + optional: true + unplugin-unused: + optional: true + unrun: + optional: true + bin: + tsdown: ./dist/run.mjs + checksum: 10c0/0b9f77653ec9955a5b830576d6a4d6ba1feb82d4adb7624a1b529e34fdf772c165cdbf817ef44ad907d507fa1170ad960ba99bd88f448f3d57e0da07cf6c9643 + languageName: node + linkType: hard + "tslib@npm:2.3.0": version: 2.3.0 resolution: "tslib@npm:2.3.0" @@ -42579,6 +42891,16 @@ __metadata: languageName: node linkType: hard +"unconfig-core@npm:^7.5.0": + version: 7.5.0 + resolution: "unconfig-core@npm:7.5.0" + dependencies: + "@quansync/fs": "npm:^1.0.0" + quansync: "npm:^1.0.0" + checksum: 10c0/9c9f745254aa8e267140430a432353d17ee87f625b0ea0668e189d88736828d117b66bd2dd41f1d48bd40d44d5b7c7d160e8b7996a60c8f484e2975ef73c7cb7 + languageName: node + linkType: hard + "uncrypto@npm:^0.1.3": version: 0.1.3 resolution: "uncrypto@npm:0.1.3" @@ -43347,6 +43669,13 @@ __metadata: languageName: node linkType: hard +"verkit@npm:^0.4.0": + version: 0.4.1 + resolution: "verkit@npm:0.4.1" + checksum: 10c0/b184269beec1d8ee90915d504f3d3671663a9c840cae01e664ea2614fcd5ff7e42472ce0b2795b66a967abaef6dfe2ecf89c5d2a6f1826c8cab9e65a41b7fd0f + languageName: node + linkType: hard + "verkit@npm:^0.5.0": version: 0.5.0 resolution: "verkit@npm:0.5.0" @@ -44836,6 +45165,15 @@ __metadata: languageName: node linkType: hard +"yuku-ast@npm:^0.19.0": + version: 0.19.0 + resolution: "yuku-ast@npm:0.19.0" + dependencies: + "@yuku-toolchain/types": "npm:^0.19.0" + checksum: 10c0/420a816c34749a5afeb5093c4c3b0b418f2652ad6d0d90dc131bde26f807cee2ff8a3e0b03253dce0f503f0c6f4185ce310e0f4335df985fcee8dd3862603275 + languageName: node + linkType: hard + "yuku-ast@npm:^0.9.3": version: 0.9.3 resolution: "yuku-ast@npm:0.9.3" @@ -44845,6 +45183,15 @@ __metadata: languageName: node linkType: hard +"yuku-codegen@npm:^0.19.0": + version: 0.19.0 + resolution: "yuku-codegen@npm:0.19.0" + dependencies: + "@yuku-toolchain/types": "npm:^0.19.0" + checksum: 10c0/d434c634102f180b4477ec428fdaf4faf0858225e5b972ac2866a2b8ff468789fae17b4c66502d4c339d8fd441f611ec4d044b735e4dfd79a2866ff8e892885d + languageName: node + linkType: hard + "yuku-codegen@npm:^0.9.3": version: 0.9.3 resolution: "yuku-codegen@npm:0.9.3" @@ -44891,6 +45238,62 @@ __metadata: languageName: node linkType: hard +"yuku-core@npm:0.19.0": + version: 0.19.0 + resolution: "yuku-core@npm:0.19.0" + dependencies: + "@yuku-core/binding-android-arm64": "npm:0.19.0" + "@yuku-core/binding-darwin-arm64": "npm:0.19.0" + "@yuku-core/binding-darwin-x64": "npm:0.19.0" + "@yuku-core/binding-freebsd-x64": "npm:0.19.0" + "@yuku-core/binding-linux-arm-gnu": "npm:0.19.0" + "@yuku-core/binding-linux-arm-musl": "npm:0.19.0" + "@yuku-core/binding-linux-arm64-gnu": "npm:0.19.0" + "@yuku-core/binding-linux-arm64-musl": "npm:0.19.0" + "@yuku-core/binding-linux-x64-gnu": "npm:0.19.0" + "@yuku-core/binding-linux-x64-musl": "npm:0.19.0" + "@yuku-core/binding-win32-arm64": "npm:0.19.0" + "@yuku-core/binding-win32-x64": "npm:0.19.0" + "@yuku-toolchain/types": "npm:^0.19.0" + dependenciesMeta: + "@yuku-core/binding-android-arm64": + optional: true + "@yuku-core/binding-darwin-arm64": + optional: true + "@yuku-core/binding-darwin-x64": + optional: true + "@yuku-core/binding-freebsd-x64": + optional: true + "@yuku-core/binding-linux-arm-gnu": + optional: true + "@yuku-core/binding-linux-arm-musl": + optional: true + "@yuku-core/binding-linux-arm64-gnu": + optional: true + "@yuku-core/binding-linux-arm64-musl": + optional: true + "@yuku-core/binding-linux-x64-gnu": + optional: true + "@yuku-core/binding-linux-x64-musl": + optional: true + "@yuku-core/binding-win32-arm64": + optional: true + "@yuku-core/binding-win32-x64": + optional: true + checksum: 10c0/be8411710d7244c0f27234546f064276cef5c9fdf2048edf457ecb68c04163932d2cdef05c1c37d369739d6936a411de54737bdc7cb7f1eb83fd5b5bdcd15559 + languageName: node + linkType: hard + +"yuku-parser@npm:^0.19.0": + version: 0.19.0 + resolution: "yuku-parser@npm:0.19.0" + dependencies: + "@yuku-toolchain/types": "npm:^0.19.0" + yuku-core: "npm:0.19.0" + checksum: 10c0/acccba03aac6786dbbde6fa1be210d7fa7d04b32bd2a256f89ecfa1e61882f1bb896f70acaf5305641c6ce11209f1609e1cbbe52485a007b5c520644fd272f8e + languageName: node + linkType: hard + "yuku-parser@npm:^0.9.3": version: 0.9.3 resolution: "yuku-parser@npm:0.9.3" From 2b05b641f1d5126c83f2ae0e699d18e20d193645 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:05:31 +0200 Subject: [PATCH 02/13] feat: prefer Rust rule severity names --- .../oxlint/src/lib/rule-configuration.ts | 134 +++++++++++++++++ libs/@local/oxlint/src/rules/index.ts | 2 + .../src/rules/prefer-rust-severities.test.ts | 89 ++++++++++++ .../src/rules/prefer-rust-severities.ts | 74 ++++++++++ .../src/rules/require-rule-change-comment.ts | 135 ++---------------- 5 files changed, 309 insertions(+), 125 deletions(-) create mode 100644 libs/@local/oxlint/src/lib/rule-configuration.ts create mode 100644 libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts create mode 100644 libs/@local/oxlint/src/rules/prefer-rust-severities.ts diff --git a/libs/@local/oxlint/src/lib/rule-configuration.ts b/libs/@local/oxlint/src/lib/rule-configuration.ts new file mode 100644 index 00000000000..2834900bc96 --- /dev/null +++ b/libs/@local/oxlint/src/lib/rule-configuration.ts @@ -0,0 +1,134 @@ +import type { ESTree } from "@oxlint/plugins"; + +const propertyName = ( + property: Pick, +): string | null => { + if (!property.computed && property.key.type === "Identifier") { + return property.key.name; + } + + if ( + property.key.type === "Literal" && + typeof property.key.value === "string" + ) { + return property.key.value; + } + + return null; +}; + +type TransparentExpression = + | ESTree.ParenthesizedExpression + | ESTree.TSAsExpression + | ESTree.TSSatisfiesExpression + | ESTree.TSTypeAssertion + | ESTree.TSNonNullExpression; + +const isTransparentExpression = ( + node: ESTree.Node, +): node is TransparentExpression => + node.type === "ParenthesizedExpression" || + node.type === "TSAsExpression" || + node.type === "TSSatisfiesExpression" || + node.type === "TSTypeAssertion" || + node.type === "TSNonNullExpression"; + +const unwrapExpression = (node: ESTree.Node): ESTree.Node => { + let expression = node; + + while (isTransparentExpression(expression)) { + expression = expression.expression; + } + + return expression; +}; + +const isRuleMap = (node: ESTree.ObjectExpression): boolean => { + let expression: ESTree.Node = node; + while (isTransparentExpression(expression.parent)) { + expression = expression.parent; + } + + const { parent } = expression; + if (parent.type === "Property") { + return parent.value === expression && propertyName(parent) === "rules"; + } + + if (parent.type === "CallExpression") { + return ( + parent.callee.type === "Identifier" && + parent.callee.name === "defineRules" && + parent.arguments[0] === expression + ); + } + + return ( + parent.type === "VariableDeclarator" && + parent.id.type === "Identifier" && + parent.id.name === "rules" + ); +}; + +type SeverityLiteral = Extract; + +const severityOf = (value: ESTree.Node): SeverityLiteral | null => { + let candidate = unwrapExpression(value); + if (candidate.type === "ArrayExpression") { + const [first] = candidate.elements; + if (first === null || first === undefined) { + return null; + } + + candidate = unwrapExpression(first); + } + + if (candidate.type !== "Literal") { + return null; + } + + if ( + typeof candidate.value === "string" || + typeof candidate.value === "number" + ) { + return candidate; + } + + return null; +}; + +export const isOxlintConfiguration = ( + program: ESTree.Program, + filename: string, +): boolean => + /(?:^|[/\\])(?:oxlint\.config|\.oxlintrc)\.[cm]?[jt]s$/u.test(filename) || + program.body.some( + (statement) => + statement.type === "ImportDeclaration" && + (statement.source.value === "oxlint" || + statement.source.value === "@local/oxlint"), + ); + +interface RuleSetting { + readonly severity: SeverityLiteral; + readonly end: number; +} + +export const ruleSettings = function* ( + node: ESTree.ObjectExpression, +): Generator { + if (!isRuleMap(node)) { + return; + } + + for (const [index, property] of node.properties.entries()) { + if (property.type === "Property") { + const severity = severityOf(property.value); + if (severity !== null) { + yield { + severity, + end: node.properties[index + 1]?.range[0] ?? node.range[1], + }; + } + } + } +}; diff --git a/libs/@local/oxlint/src/rules/index.ts b/libs/@local/oxlint/src/rules/index.ts index 527577c2032..fb165c8abfa 100644 --- a/libs/@local/oxlint/src/rules/index.ts +++ b/libs/@local/oxlint/src/rules/index.ts @@ -3,6 +3,7 @@ import { definePlugin } from "@oxlint/plugins"; import { namingConventions } from "./naming-conventions.js"; import { noPropertyModifiers } from "./no-property-modifiers.js"; import { preferOptionsObject } from "./prefer-options-object.js"; +import { preferRustSeverities } from "./prefer-rust-severities.js"; import { requireRuleChangeComment } from "./require-rule-change-comment.js"; import { requireSafetyCommentForTypeAssertion } from "./require-safety-comment-for-type-assertion.js"; import { requireSuppressionComment } from "./require-suppression-comment.js"; @@ -16,6 +17,7 @@ export default definePlugin({ "naming-conventions": namingConventions, "no-property-modifiers": noPropertyModifiers, "prefer-options-object": preferOptionsObject, + "prefer-rust-severities": preferRustSeverities, "require-rule-change-comment": requireRuleChangeComment, "require-safety-comment-for-type-assertion": requireSafetyCommentForTypeAssertion, diff --git a/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts b/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts new file mode 100644 index 00000000000..f8900711630 --- /dev/null +++ b/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts @@ -0,0 +1,89 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { preferRustSeverities } from "./prefer-rust-severities.js"; + +const tester = new RuleTester(); +const severityError = { messageId: "severity" }; +const configuration = (rules: string): string => + `import { defineConfig } from "oxlint"; +defineConfig({ rules: { +${rules} +} });`; +const aliases = [ + ["off", "allow"], + ["error", "deny"], + [0, "allow"], + [1, "warn"], + [2, "deny"], +] as const; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("prefer-rust-severities", preferRustSeverities, { + invalid: [ + ...aliases.map(([severity, replacement]) => ({ + code: configuration(`one: ${JSON.stringify(severity)}, // Local policy.`), + errors: [severityError], + output: configuration(`one: "${replacement}", // Local policy.`), + })), + ...aliases.map(([severity, replacement]) => ({ + code: configuration( + `one: [${JSON.stringify(severity)}, // Local policy.\n{ mode: "off", level: "error" }],`, + ), + errors: [severityError], + output: configuration( + `one: ["${replacement}", // Local policy.\n{ mode: "off", level: "error" }],`, + ), + })), + { + code: configuration('one: [("off" as const)] as const,'), + errors: [severityError], + filename: "config-factory.ts", + output: configuration('one: [("allow" as const)] as const,'), + }, + { + code: 'import type { DummyRuleMap } from "oxlint"; defineRules(({ one: "error" }) satisfies DummyRuleMap);', + errors: [severityError], + filename: "config-factory.ts", + output: + 'import type { DummyRuleMap } from "oxlint"; defineRules(({ one: "deny" }) satisfies DummyRuleMap);', + }, + { + code: 'import { createConfig } from "@local/oxlint"; const rules = { one: 0 } as const;', + errors: [severityError], + filename: "config-factory.ts", + output: + 'import { createConfig } from "@local/oxlint"; const rules = { one: "allow" } as const;', + }, + { + code: 'export default { overrides: [{ files: ["test.ts"], rules: { one: 2 } }] };', + errors: [severityError], + filename: "oxlint.config.ts", + output: + 'export default { overrides: [{ files: ["test.ts"], rules: { one: "deny" } }] };', + }, + { + code: 'export default { rules: { one: "off" } };', + errors: [severityError], + filename: ".oxlintrc.mjs", + output: 'export default { rules: { one: "allow" } };', + }, + ...['"warning"', "3"].map((severity) => ({ + code: configuration(`one: ${severity},`), + errors: [severityError], + output: null, + })), + ], + valid: [ + ...["allow", "warn", "deny"].map((severity) => + configuration(`one: "${severity}",`), + ), + configuration('one: ["deny", { mode: "off", level: "error" }],'), + configuration("one: inheritedSetting,\n...inheritedRules,"), + configuration("one: [],"), + 'import { defineConfig } from "oxlint"; defineConfig({ options: { reportUnusedDisableDirectives: "error" }, globals: { shared: "off" } });', + 'const validation = { rules: { one: "off" } };', + 'defineRules({ one: "off" });', + 'import { defineConfig } from "vitest/config"; defineConfig({ rules: { one: "off" } });', + 'import { defineConfig } from "oxlint"; const plugin = { rules: { one: implementation } };', + ], +}); diff --git a/libs/@local/oxlint/src/rules/prefer-rust-severities.ts b/libs/@local/oxlint/src/rules/prefer-rust-severities.ts new file mode 100644 index 00000000000..f1148b6159a --- /dev/null +++ b/libs/@local/oxlint/src/rules/prefer-rust-severities.ts @@ -0,0 +1,74 @@ +/** + * Keeps literal rule severities in the `allow`, `warn`, and `deny` vocabulary. + * + * Fixes ESLint aliases without changing their severity or surrounding options. Computed settings and inherited presets are not resolved. + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +import { + isOxlintConfiguration, + ruleSettings, +} from "../lib/rule-configuration.js"; + +type Severity = "allow" | "warn" | "deny"; + +const replacements: ReadonlyMap = new Map< + string | number, + Severity +>([ + ["off", "allow"], + ["error", "deny"], + [0, "allow"], + [1, "warn"], + [2, "deny"], +]); + +export const preferRustSeverities = defineRule({ + createOnce: (context) => { + let configuration = false; + + return { + Program: (program): void => { + configuration = isOxlintConfiguration(program, context.filename); + }, + ObjectExpression: (node): void => { + if (!configuration) { + return; + } + + for (const { severity } of ruleSettings(node)) { + const { value } = severity; + if (value !== "allow" && value !== "warn" && value !== "deny") { + let replacement: Severity | undefined; + if (typeof value === "string" || typeof value === "number") { + replacement = replacements.get(value); + } + + context.report({ + messageId: "severity", + node: severity, + fix: (fixer) => { + if (replacement === undefined) { + return null; + } + + return fixer.replaceText(severity, JSON.stringify(replacement)); + }, + }); + } + } + }, + }; + }, + meta: { + fixable: "code", + messages: { + severity: 'Use only "allow", "warn", or "deny" for rule severities.', + }, + schema: [], + type: "suggestion", + }, +}); diff --git a/libs/@local/oxlint/src/rules/require-rule-change-comment.ts b/libs/@local/oxlint/src/rules/require-rule-change-comment.ts index f5b87165fbe..a2c051c8ce6 100644 --- a/libs/@local/oxlint/src/rules/require-rule-change-comment.ts +++ b/libs/@local/oxlint/src/rules/require-rule-change-comment.ts @@ -8,110 +8,12 @@ import { defineRule } from "@oxlint/plugins"; -import type { ESTree, SourceCode } from "@oxlint/plugins"; - -const severities: ReadonlySet = new Set([ - "allow", - "off", - "warn", - "deny", - "error", -]); - -const propertyName = ( - property: Pick, -): string | null => { - if (!property.computed && property.key.type === "Identifier") { - return property.key.name; - } - - if ( - property.key.type === "Literal" && - typeof property.key.value === "string" - ) { - return property.key.value; - } - - return null; -}; - -type TransparentExpression = - | ESTree.ParenthesizedExpression - | ESTree.TSAsExpression - | ESTree.TSSatisfiesExpression - | ESTree.TSTypeAssertion - | ESTree.TSNonNullExpression; - -const isTransparentExpression = ( - node: ESTree.Node, -): node is TransparentExpression => - node.type === "ParenthesizedExpression" || - node.type === "TSAsExpression" || - node.type === "TSSatisfiesExpression" || - node.type === "TSTypeAssertion" || - node.type === "TSNonNullExpression"; - -const unwrapExpression = (node: ESTree.Node): ESTree.Node => { - let expression = node; - - while (isTransparentExpression(expression)) { - expression = expression.expression; - } - - return expression; -}; - -const isRuleMap = (node: ESTree.ObjectExpression): boolean => { - let expression: ESTree.Node = node; - while (isTransparentExpression(expression.parent)) { - expression = expression.parent; - } +import { + isOxlintConfiguration, + ruleSettings, +} from "../lib/rule-configuration.js"; - const { parent } = expression; - if (parent.type === "Property") { - return parent.value === expression && propertyName(parent) === "rules"; - } - - if (parent.type === "CallExpression") { - return ( - parent.callee.type === "Identifier" && - parent.callee.name === "defineRules" && - parent.arguments[0] === expression - ); - } - - return ( - parent.type === "VariableDeclarator" && - parent.id.type === "Identifier" && - parent.id.name === "rules" - ); -}; - -const severityOf = (value: ESTree.Node): ESTree.Node | null => { - let candidate = unwrapExpression(value); - if (candidate.type === "ArrayExpression") { - const [first] = candidate.elements; - if (first === null || first === undefined) { - return null; - } - - candidate = unwrapExpression(first); - } - - if (candidate.type !== "Literal") { - return null; - } - - if (typeof candidate.value === "string" && severities.has(candidate.value)) { - return candidate; - } - - if (candidate.value === 0 || candidate.value === 1 || candidate.value === 2) { - return candidate; - } - - return null; -}; +import type { ESTree, SourceCode } from "@oxlint/plugins"; const hasExplanation = ( sourceCode: SourceCode, @@ -137,33 +39,16 @@ export const requireRuleChangeComment = defineRule({ return { Program: (program): void => { - configuration = - /(?:^|[/\\])(?:oxlint\.config|\.oxlintrc)\.[cm]?[jt]s$/u.test( - context.filename, - ) || - program.body.some( - (statement) => - statement.type === "ImportDeclaration" && - (statement.source.value === "oxlint" || - statement.source.value === "@local/oxlint"), - ); + configuration = isOxlintConfiguration(program, context.filename); }, ObjectExpression: (node): void => { - if (!configuration || !isRuleMap(node)) { + if (!configuration) { return; } - for (const [index, property] of node.properties.entries()) { - if (property.type === "Property") { - const severity = severityOf(property.value); - const end = node.properties[index + 1]?.range[0] ?? node.range[1]; - - if ( - severity !== null && - !hasExplanation(context.sourceCode, severity, end) - ) { - context.report({ messageId: "explanation", node: severity }); - } + for (const { severity, end } of ruleSettings(node)) { + if (!hasExplanation(context.sourceCode, severity, end)) { + context.report({ messageId: "explanation", node: severity }); } } }, From f6957212f6eb771022aec462accd064bf74bc33a Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:48:09 +0200 Subject: [PATCH 03/13] chore: use Rust severity vocabulary in Oxlint configs --- libs/@local/oxlint/README.md | 12 ++- libs/@local/oxlint/src/index.test.ts | 6 +- libs/@local/oxlint/src/index.ts | 80 +++++++++---------- .../src/rules/prefer-rust-severities.test.ts | 31 +++++++ .../src/rules/prefer-rust-severities.ts | 46 +++++++++-- .../rules/require-rule-change-comment.test.ts | 5 ++ .../src/rules/require-rule-change-comment.ts | 33 +++++++- 7 files changed, 163 insertions(+), 50 deletions(-) diff --git a/libs/@local/oxlint/README.md b/libs/@local/oxlint/README.md index b798e5cbbff..a582daa19a8 100644 --- a/libs/@local/oxlint/README.md +++ b/libs/@local/oxlint/README.md @@ -14,7 +14,7 @@ export default defineConfig({ }), ], rules: { - "eslint/no-console": "off", // This CLI writes results to stdout. + "eslint/no-console": "allow", // This CLI writes results to stdout. }, }); ``` @@ -29,6 +29,16 @@ The React and Next selections enable their native plugins. Vitest adds test rule The `hash` plugin enforces naming conventions, including mapped type parameters. Its naming fixes update references and avoid name collisions. Other rules cover JavaScript visibility and options-object parameters. Type assertions and individual lint suppressions require explanations. +Use `allow`, `warn` or `deny` for rule severities. The default `hash/prefer-rust-severities` rule checks literal settings and fixes equivalent ESLint aliases: + +| Alias | Replacement | +| ------------ | ----------- | +| `off`, `0` | `allow` | +| `1` | `warn` | +| `error`, `2` | `deny` | + +The fix leaves rule options and comments unchanged. Other settings, such as `reportUnusedDisableDirectives: "error"`, keep their own vocabulary. + The default `hash/require-rule-change-comment` rule requires an inline explanation beside a literal severity setting. For tuple settings, put the comment beside the first element: ```ts diff --git a/libs/@local/oxlint/src/index.test.ts b/libs/@local/oxlint/src/index.test.ts index bb5aacad36d..383c556d7d2 100644 --- a/libs/@local/oxlint/src/index.test.ts +++ b/libs/@local/oxlint/src/index.test.ts @@ -18,6 +18,8 @@ describe("createConfig", () => { suspicious: "deny", }); expect(config.options?.typeAware).toBe(true); + expect(config.options?.reportUnusedDisableDirectives).toBe("error"); + expect(config.rules?.["hash/prefer-rust-severities"]).toBe("deny"); expect(config.rules?.["hash/require-rule-change-comment"]).toBe("deny"); }); @@ -26,8 +28,8 @@ describe("createConfig", () => { const config = createConfig({ runtime: "node", frameworks: ["vitest"] }); - expect(config.rules?.["vitest/prefer-to-be-falsy"]).toBe("off"); - expect(config.rules?.["vitest/prefer-to-be-truthy"]).toBe("off"); + expect(config.rules?.["vitest/prefer-to-be-falsy"]).toBe("allow"); + expect(config.rules?.["vitest/prefer-to-be-truthy"]).toBe("allow"); }); test("ignore_patterns", () => { diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index a85344aec1f..2e6b8e19a3e 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -76,7 +76,7 @@ export const createConfig = (options: Options): OxlintConfig => { { files: ["**/*.config.ts"], rules: { - "import/no-default-export": "off", // config files always use `defineConfig` with a default export + "import/no-default-export": "allow", // config files always use `defineConfig` with a default export }, }, ]; @@ -108,7 +108,7 @@ export const createConfig = (options: Options): OxlintConfig => { rules, defineRules({ "vitest/consistent-test-it": ["deny", { withinDescribe: "test" }], // Use the same declaration name inside and outside describe blocks. - "vitest/no-importing-vitest-globals": "off", // import Vitest APIs instead of relying on globals + "vitest/no-importing-vitest-globals": "allow", // import Vitest APIs instead of relying on globals "vitest/no-restricted-vi-methods": [ "deny", // Module mocks hide dependencies. Method spies remain available. { @@ -116,26 +116,26 @@ export const createConfig = (options: Options): OxlintConfig => { mock: "Inject dependencies instead of replacing modules.", }, ], - "vitest/require-test-timeout": "off", // the default timeout is a good default for most tests - "vitest/prefer-describe-function-title": "off", // clashes with valid-title - "vitest/prefer-to-be-falsy": "off", // Strict boolean matchers distinguish false from falsy values. - "vitest/prefer-to-be-truthy": "off", // Strict boolean matchers distinguish true from truthy values. + "vitest/require-test-timeout": "allow", // the default timeout is a good default for most tests + "vitest/prefer-describe-function-title": "allow", // clashes with valid-title + "vitest/prefer-to-be-falsy": "allow", // Strict boolean matchers distinguish false from falsy values. + "vitest/prefer-to-be-truthy": "allow", // Strict boolean matchers distinguish true from truthy values. }), ); overrides.push( defineOverride({ files: ["src/**/*.test-d.ts"], rules: { - "vitest/prefer-expect-assertions": "off", // type tests run through the compiler, not the runtime assertion counter. - "no-magic-numbers": "off", // magic numbers are often used in test fixtures - "max-lines-per-function": "off", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests + "vitest/prefer-expect-assertions": "allow", // type tests run through the compiler, not the runtime assertion counter. + "no-magic-numbers": "allow", // magic numbers are often used in test fixtures + "max-lines-per-function": "allow", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests }, }), defineOverride({ files: ["src/**/*.test.ts"], rules: { - "no-magic-numbers": "off", // magic numbers are often used in test fixtures - "max-lines-per-function": "off", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests + "no-magic-numbers": "allow", // magic numbers are often used in test fixtures + "max-lines-per-function": "allow", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests }, }), ); @@ -147,14 +147,14 @@ export const createConfig = (options: Options): OxlintConfig => { Object.assign( rules, defineRules({ - "new-cap": "off", // clashes with effect's capitalization conventions - "oxc/no-barrel-file": "off", // side-effect free barrel files are common - "import/no-namespace": "off", // barrel files are common in effect + "new-cap": "allow", // clashes with effect's capitalization conventions + "oxc/no-barrel-file": "allow", // side-effect free barrel files are common + "import/no-namespace": "allow", // barrel files are common in effect "no-underscore-dangle": ["deny", { allow: ["_tag"] }], // `_tag` is used to discriminate union types - "unicorn/max-nested-calls": "off", // functional programming and composition + "unicorn/max-nested-calls": "allow", // functional programming and composition "typescript/no-namespace": ["deny", { allowDeclarations: true }], // declarations are often used for type aliases - "no-shadow": "off", // covered by the strict typescript setup - "no-redeclare": "off", // covered by the strict typescript setup + "no-shadow": "allow", // covered by the strict typescript setup + "no-redeclare": "allow", // covered by the strict typescript setup "effecttsgo/missed-pipeable-opportunity": "deny", // nested function calls otherwise aren't readable }), ); @@ -196,16 +196,16 @@ export const createConfig = (options: Options): OxlintConfig => { overrides, plugins, rules: { - "capitalized-comments": "off", // a linter should not police the style of comments - "default-case": "off", // type checking establishes the exhaustive set of cases - "import/exports-last": "off", // hurts readability, as items are commonly exported at declaration - "import/group-exports": "off", // hurts readability - "import/no-named-export": "off", // prefer named exports - "import/no-nodejs-modules": "off", // TypeScript 7 handles this natively through removal of ambient type definitions - "import/no-relative-parent-imports": "off", // relative parent imports are the de-factor standard for importing from parent directories - "import/prefer-default-export": "off", // depends on the module - "jsdoc/require-param": "off", // TypeScript supplies parameter types - "jsdoc/require-returns": "off", // TypeScript supplies return types + "capitalized-comments": "allow", // a linter should not police the style of comments + "default-case": "allow", // type checking establishes the exhaustive set of cases + "import/exports-last": "allow", // hurts readability, as items are commonly exported at declaration + "import/group-exports": "allow", // hurts readability + "import/no-named-export": "allow", // prefer named exports + "import/no-nodejs-modules": "allow", // TypeScript 7 handles this natively through removal of ambient type definitions + "import/no-relative-parent-imports": "allow", // relative parent imports are the de-factor standard for importing from parent directories + "import/prefer-default-export": "allow", // depends on the module + "jsdoc/require-param": "allow", // TypeScript supplies parameter types + "jsdoc/require-returns": "allow", // TypeScript supplies return types "max-lines": [ "deny", // Keep each module reviewable as one unit, including its documentation. { @@ -223,14 +223,14 @@ export const createConfig = (options: Options): OxlintConfig => { skipComments: true, }, ], - "max-statements": "off", // "max-lines-per-function" is a better proxy + "max-statements": "allow", // "max-lines-per-function" is a better proxy "no-duplicate-imports": [ - "error", // Keep type-only dependencies distinct from runtime imports. + "deny", // Keep type-only dependencies distinct from runtime imports. { allowSeparateTypeImports: true, }, ], - "no-inline-comments": "off", // inline comments are useful for explaining complex logic + "no-inline-comments": "allow", // inline comments are useful for explaining complex logic "no-magic-numbers": [ "deny", // Keep the rule narrow with the exceptions below. { @@ -244,11 +244,11 @@ export const createConfig = (options: Options): OxlintConfig => { ignoreTypeIndexes: true, }, ], - "no-undefined": "off", // comparisons need `undefined` + "no-undefined": "allow", // comparisons need `undefined` "one-var": ["deny", "never"], // use one declaration per variable - "oxc/no-optional-chaining": "off", // optional chaining is useful for optional properties - "oxc/no-rest-spread-properties": "off", // central to functional programming - "prefer-destructuring": "off", // requiring destructuring for reassignment makes the code awkward + "oxc/no-optional-chaining": "allow", // optional chaining is useful for optional properties + "oxc/no-rest-spread-properties": "allow", // central to functional programming + "prefer-destructuring": "allow", // requiring destructuring for reassignment makes the code awkward "sort-imports": [ "deny", // Sort members while preserving dependency groups and declaration order. { @@ -256,7 +256,7 @@ export const createConfig = (options: Options): OxlintConfig => { ignoreDeclarationSort: true, }, ], - "sort-keys": "off", // declaration order is more important, and fix may be unsafe, sorting of keys does not increase clarity + "sort-keys": "allow", // declaration order is more important, and fix may be unsafe, sorting of keys does not increase clarity "typescript/no-floating-promises": [ "deny", // Discarded async failures must not disappear behind void or an IIFE. { @@ -298,18 +298,18 @@ export const createConfig = (options: Options): OxlintConfig => { allowString: false, }, ], - "unicorn/no-null": "off", // `null` is a useful type to indicate explicit absence of a value + "unicorn/no-null": "allow", // `null` is a useful type to indicate explicit absence of a value "func-names": ["deny", "always", { generators: "never" }], // Name functions for stack traces without naming generator callbacks. "typescript/no-empty-interface": ["deny", { allowSingleExtends: true }], // Permit named interfaces for readable editor type hints. "typescript/no-empty-object-type": [ "deny", // Permit named interfaces for readable editor type hints. { allowInterfaces: "with-single-extends" }, ], - "typescript/prefer-readonly-parameter-types": "off", // neat idea, but way too many false positives - "unicorn/prefer-ternary": "off", // clashes with the rule that requires explicit if/else + "typescript/prefer-readonly-parameter-types": "allow", // neat idea, but way too many false positives + "unicorn/prefer-ternary": "allow", // clashes with the rule that requires explicit if/else "id-length": ["deny", { checkGeneric: false, exceptions: ["$", "_"] }], // Type parameters and conventional helper bindings need their short names. - "unicorn/no-array-callback-reference": "off", // goes against functional programming - "typescript/explicit-member-accessibility": "off", // goes against modern ts and js interop + "unicorn/no-array-callback-reference": "allow", // goes against functional programming + "typescript/explicit-member-accessibility": "allow", // goes against modern ts and js interop ...rules, ...pluginDeny, }, diff --git a/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts b/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts index f8900711630..e76e284695b 100644 --- a/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts +++ b/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts @@ -2,6 +2,31 @@ import { RuleTester } from "oxlint/plugins-dev"; import { preferRustSeverities } from "./prefer-rust-severities.js"; +const incorrectExample = `import { defineConfig } from "oxlint"; + +export default defineConfig({ + rules: { + "no-console": "off", // This CLI writes results to stdout. + "eqeqeq": 1, // Loose comparisons remain during migration. + "max-params": [ + "error", // Additional parameters belong in an options object. + { max: 3 }, + ], + }, +});`; +const correctExample = `import { defineConfig } from "oxlint"; + +export default defineConfig({ + rules: { + "no-console": "allow", // This CLI writes results to stdout. + "eqeqeq": "warn", // Loose comparisons remain during migration. + "max-params": [ + "deny", // Additional parameters belong in an options object. + { max: 3 }, + ], + }, +});`; + const tester = new RuleTester(); const severityError = { messageId: "severity" }; const configuration = (rules: string): string => @@ -20,6 +45,11 @@ const aliases = [ // oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. tester.run("prefer-rust-severities", preferRustSeverities, { invalid: [ + { + code: incorrectExample, + errors: [severityError, severityError, severityError], + output: correctExample, + }, ...aliases.map(([severity, replacement]) => ({ code: configuration(`one: ${JSON.stringify(severity)}, // Local policy.`), errors: [severityError], @@ -74,6 +104,7 @@ tester.run("prefer-rust-severities", preferRustSeverities, { })), ], valid: [ + correctExample, ...["allow", "warn", "deny"].map((severity) => configuration(`one: "${severity}",`), ), diff --git a/libs/@local/oxlint/src/rules/prefer-rust-severities.ts b/libs/@local/oxlint/src/rules/prefer-rust-severities.ts index f1148b6159a..cb86cb6e133 100644 --- a/libs/@local/oxlint/src/rules/prefer-rust-severities.ts +++ b/libs/@local/oxlint/src/rules/prefer-rust-severities.ts @@ -1,7 +1,39 @@ /** * Keeps literal rule severities in the `allow`, `warn`, and `deny` vocabulary. * - * Fixes ESLint aliases without changing their severity or surrounding options. Computed settings and inherited presets are not resolved. + * Fixes ESLint aliases without changing their severity or surrounding options, but does not resolve computed settings or inherited presets. + * + * @example Incorrect + * ```ts + * import { defineConfig } from "oxlint"; + * + * export default defineConfig({ + * rules: { + * "no-console": "off", // This CLI writes results to stdout. + * "eqeqeq": 1, // Loose comparisons remain during migration. + * "max-params": [ + * "error", // Additional parameters belong in an options object. + * { max: 3 }, + * ], + * }, + * }); + * ``` + * + * @example Correct + * ```ts + * import { defineConfig } from "oxlint"; + * + * export default defineConfig({ + * rules: { + * "no-console": "allow", // This CLI writes results to stdout. + * "eqeqeq": "warn", // Loose comparisons remain during migration. + * "max-params": [ + * "deny", // Additional parameters belong in an options object. + * { max: 3 }, + * ], + * }, + * }); + * ``` * * @module */ @@ -41,11 +73,13 @@ export const preferRustSeverities = defineRule({ for (const { severity } of ruleSettings(node)) { const { value } = severity; - if (value !== "allow" && value !== "warn" && value !== "deny") { - let replacement: Severity | undefined; - if (typeof value === "string" || typeof value === "number") { - replacement = replacements.get(value); - } + if ( + (typeof value === "string" || typeof value === "number") && + value !== "allow" && + value !== "warn" && + value !== "deny" + ) { + const replacement = replacements.get(value); context.report({ messageId: "severity", diff --git a/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts b/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts index e84815bce39..00b71bf193e 100644 --- a/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts +++ b/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts @@ -13,6 +13,10 @@ ${rules} // oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. tester.run("require-rule-change-comment", requireRuleChangeComment, { invalid: [ + { + code: 'import { defineConfig } from "oxlint";\n\nexport default defineConfig({\n rules: {\n // This CLI writes results to stdout.\n "no-console": "allow",\n "max-params": [\n "deny",\n { max: 3 },\n ], // Additional parameters belong in an options object.\n },\n});', + errors: [explanation, explanation], + }, { code: 'import { defineConfig } from "oxlint"; const rules = { one: "off" } as const;', errors: [explanation], @@ -95,6 +99,7 @@ tester.run("require-rule-change-comment", requireRuleChangeComment, { }, ], valid: [ + 'import { defineConfig } from "oxlint";\n\nexport default defineConfig({\n rules: {\n "no-console": "allow", // This CLI writes results to stdout.\n "max-params": [\n "deny", // Additional parameters belong in an options object.\n { max: 3 },\n ],\n },\n});', { code: 'import { defineConfig } from "oxlint"; const rules = { one: "off" as const, // CLI output is intentional.\n} as const;', filename: "config-factory.ts", diff --git a/libs/@local/oxlint/src/rules/require-rule-change-comment.ts b/libs/@local/oxlint/src/rules/require-rule-change-comment.ts index a2c051c8ce6..25afb9af694 100644 --- a/libs/@local/oxlint/src/rules/require-rule-change-comment.ts +++ b/libs/@local/oxlint/src/rules/require-rule-change-comment.ts @@ -1,7 +1,38 @@ /** * Requires explanations beside literal severity settings in Oxlint configuration. * - * Checks `rules` objects and `defineRules` arguments in files that import Oxlint or use its configuration filename. Tuple settings put the explanation beside the first element. Computed settings and inherited presets are not resolved. + * Checks `rules` objects and `defineRules` arguments in files that import Oxlint or use its configuration filename, requiring tuple explanations beside the first element without resolving computed settings or inherited presets. + * + * @example Incorrect + * ```ts + * import { defineConfig } from "oxlint"; + * + * export default defineConfig({ + * rules: { + * // This CLI writes results to stdout. + * "no-console": "allow", + * "max-params": [ + * "deny", + * { max: 3 }, + * ], // Additional parameters belong in an options object. + * }, + * }); + * ``` + * + * @example Correct + * ```ts + * import { defineConfig } from "oxlint"; + * + * export default defineConfig({ + * rules: { + * "no-console": "allow", // This CLI writes results to stdout. + * "max-params": [ + * "deny", // Additional parameters belong in an options object. + * { max: 3 }, + * ], + * }, + * }); + * ``` * * @module */ From 136aa96b1b9c158cdee6fe2fc2f0295eb9a585ff Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:44:31 +0200 Subject: [PATCH 04/13] chore: refine oxlint framework configuration --- libs/@local/oxlint/README.md | 2 +- libs/@local/oxlint/src/index.test.ts | 49 ++++++++++++++++++++++++++++ libs/@local/oxlint/src/index.ts | 46 ++++++++++++++++++++++++-- 3 files changed, 94 insertions(+), 3 deletions(-) diff --git a/libs/@local/oxlint/README.md b/libs/@local/oxlint/README.md index a582daa19a8..7443f5f39dc 100644 --- a/libs/@local/oxlint/README.md +++ b/libs/@local/oxlint/README.md @@ -21,7 +21,7 @@ export default defineConfig({ Build the package before importing it. `createConfig` accepts a required `runtime` of `node` or `browser`. Its optional `frameworks` array selects `react`, `next`, `vitest` or `effect`. Use Oxlint's `defineConfig` for package-specific rules and overrides. -The React and Next selections enable their native plugins. Vitest adds test rules and file overrides for runtime and type tests under `src`. Effect extends the strict native Effect preset and allows its namespace imports and functional composition conventions. +The React and Next selections enable their native plugins. Next also ignores its generated `.next/**` output and `next-env.d.ts`. Vitest adds test rules and file overrides for runtime and type tests under `src`. Effect extends the strict native Effect preset and allows its namespace imports and functional composition conventions. `additionalRestrictedTypes` adds messages for restricted types without replacing the built-in entries for `object`, `unknown` and `Function`. An attempt to replace one of those entries throws. `ignorePatterns` passes the package's exclusion globs to Oxlint. diff --git a/libs/@local/oxlint/src/index.test.ts b/libs/@local/oxlint/src/index.test.ts index 383c556d7d2..bf933579a2f 100644 --- a/libs/@local/oxlint/src/index.test.ts +++ b/libs/@local/oxlint/src/index.test.ts @@ -32,6 +32,39 @@ describe("createConfig", () => { expect(config.rules?.["vitest/prefer-to-be-truthy"]).toBe("allow"); }); + test("vitest_effect_tests", () => { + expect.hasAssertions(); + + const effect = createConfig({ + runtime: "node", + frameworks: ["vitest", "effect"], + }); + const plain = createConfig({ runtime: "node", frameworks: ["vitest"] }); + + expect(effect.rules?.["vitest/no-standalone-expect"]).toStrictEqual([ + "deny", + { + additionalTestBlockFunctions: [ + "it", + "it.effect", + "it.effect.skip", + "it.effect.only", + "it.effect.each", + "it.live", + "it.live.skip", + "it.live.only", + "it.live.each", + ], + }, + ]); + expect(effect.rules?.["vitest/require-hook"]).toStrictEqual([ + "deny", + { allowedFunctionCalls: ["layer"] }, + ]); + expect(plain.rules?.["vitest/no-standalone-expect"]).toBeUndefined(); + expect(plain.rules?.["vitest/require-hook"]).toBeUndefined(); + }); + test("ignore_patterns", () => { expect.hasAssertions(); @@ -43,6 +76,22 @@ describe("createConfig", () => { expect(config.ignorePatterns).toStrictEqual(["generated/**"]); }); + test("next_ignore_patterns", () => { + expect.hasAssertions(); + + const config = createConfig({ + frameworks: ["next"], + ignorePatterns: ["generated/**"], + runtime: "node", + }); + + expect(config.ignorePatterns).toStrictEqual([ + "generated/**", + ".next/**", + "next-env.d.ts", + ]); + }); + test.each(["unknown", "object"])("reserved_type_%s", (typeName) => { expect.hasAssertions(); diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index 2e6b8e19a3e..36dbc4743fe 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -72,9 +72,15 @@ export const createConfig = (options: Options): OxlintConfig => { const extend: Extends = []; const env: Env = { builtin: true, es2026: true }; const rules: DummyRuleMap = {}; + const ignorePatterns = [...(options.ignorePatterns ?? [])]; const overrides: Overrides = [ { - files: ["**/*.config.ts"], + files: [ + "**/*.config.js", + "**/*.config.ts", + "**/*.config.mjs", + "**/*.config.mts", + ], rules: { "import/no-default-export": "allow", // config files always use `defineConfig` with a default export }, @@ -96,10 +102,21 @@ export const createConfig = (options: Options): OxlintConfig => { switch (framework) { case "react": { plugins.push("react", "react-perf", "jsx-a11y"); + break; } case "next": { plugins.push("nextjs", "react-perf", "jsx-a11y"); + ignorePatterns.push(".next/**", "next-env.d.ts"); + overrides.push( + defineOverride({ + files: ["app/**/*.tsx", "pages/**/*.tsx"], + rules: { + "import/no-default-export": "allow", // Next.JS uses default exports for pages + }, + }), + ); + break; } case "vitest": { @@ -122,6 +139,30 @@ export const createConfig = (options: Options): OxlintConfig => { "vitest/prefer-to-be-truthy": "allow", // Strict boolean matchers distinguish true from truthy values. }), ); + + if (options.frameworks?.includes("effect") ?? false) { + const effectTesters = ["it.effect", "it.live"].flatMap((tester) => [ + tester, + `${tester}.skip`, + `${tester}.only`, + `${tester}.each`, + ]); + + Object.assign( + rules, + defineRules({ + "vitest/no-standalone-expect": [ + "deny", // @effect/vitest declares tests through `it.effect` and `it.live`, and `layer` hands its tests an `it` of their own. + { additionalTestBlockFunctions: ["it", ...effectTesters] }, + ], + "vitest/require-hook": [ + "deny", // @effect/vitest's `layer` provides services to the tests it groups. + { allowedFunctionCalls: ["layer"] }, + ], + }), + ); + } + overrides.push( defineOverride({ files: ["src/**/*.test-d.ts"], @@ -156,6 +197,7 @@ export const createConfig = (options: Options): OxlintConfig => { "no-shadow": "allow", // covered by the strict typescript setup "no-redeclare": "allow", // covered by the strict typescript setup "effecttsgo/missed-pipeable-opportunity": "deny", // nested function calls otherwise aren't readable + "unicorn/no-array-method-this-argument": "allow", // false positives as it only name matches }), ); break; @@ -182,7 +224,7 @@ export const createConfig = (options: Options): OxlintConfig => { }, env, extends: extend, - ignorePatterns: [...(options.ignorePatterns ?? [])], + ignorePatterns, jsPlugins: [ { name: "hash", From e2e7894f7648655e893fe42dee3e7bbb571a10d9 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:00:42 +0200 Subject: [PATCH 05/13] feat: resolve inherited oxlint config fields --- libs/@local/oxlint/README.md | 17 +- .../@local/oxlint/docs/task-dependencies.json | 8 + libs/@local/oxlint/oxlint.config.ts | 10 +- libs/@local/oxlint/package.json | 3 +- libs/@local/oxlint/src/index.test-d.ts | 16 ++ libs/@local/oxlint/src/index.test.ts | 56 ++++-- libs/@local/oxlint/src/index.ts | 41 +++- .../oxlint/src/lib/inherit-config.test.ts | 119 +++++++++++ libs/@local/oxlint/src/lib/inherit-config.ts | 35 ++++ .../oxlint/src/rules/no-property-modifiers.ts | 7 +- .../src/rules/prefer-rust-severities.test.ts | 4 +- .../rules/require-rule-change-comment.test.ts | 2 +- .../oxlint/tests/config.integration.test.ts | 184 ++++++++++++++++++ libs/@local/oxlint/tsconfig.json | 3 +- libs/@local/oxlint/turbo.json | 3 + libs/@local/oxlint/vitest.config.ts | 21 +- 16 files changed, 474 insertions(+), 55 deletions(-) create mode 100644 libs/@local/oxlint/src/index.test-d.ts create mode 100644 libs/@local/oxlint/src/lib/inherit-config.test.ts create mode 100644 libs/@local/oxlint/src/lib/inherit-config.ts create mode 100644 libs/@local/oxlint/tests/config.integration.test.ts diff --git a/libs/@local/oxlint/README.md b/libs/@local/oxlint/README.md index 7443f5f39dc..c4aa093df1d 100644 --- a/libs/@local/oxlint/README.md +++ b/libs/@local/oxlint/README.md @@ -3,23 +3,21 @@ Strict, type-aware Oxlint configuration for TypeScript packages, intended to become the repository default. Package-specific exceptions override the shared rules. Current tuning covers vanilla TypeScript, Effect and Vitest consumers. React and Next selections remain provisional. The policy will change as more packages migrate. ```ts -import { createConfig, defineConfig } from "@local/oxlint"; +import { defineConfig } from "@local/oxlint"; export default defineConfig({ - extends: [ - createConfig({ - runtime: "node", - frameworks: ["vitest", "effect"], - ignorePatterns: ["generated/**"], - }), - ], + runtime: "node", + frameworks: ["vitest", "effect"], + ignorePatterns: ["generated/**"], rules: { "eslint/no-console": "allow", // This CLI writes results to stdout. }, }); ``` -Build the package before importing it. `createConfig` accepts a required `runtime` of `node` or `browser`. Its optional `frameworks` array selects `react`, `next`, `vitest` or `effect`. Use Oxlint's `defineConfig` for package-specific rules and overrides. +Build the package before importing it. `defineConfig` accepts every native Oxlint configuration field alongside a required `runtime` of `node` or `browser`. Its optional `frameworks` array selects `react`, `next`, `vitest` or `effect`. + +The shared defaults precede the supplied `extends` entries, and the package's own fields take precedence. Oxlint handles rules, categories, plugins, options and ordered overrides. The helper resolves the fields Oxlint does not inherit: `env` and `globals` merge by name, `settings` merges by plugin name, and `ignorePatterns` concatenates in inheritance order. A later plugin settings value replaces that plugin's earlier value as a whole. Nested objects and arrays are not deep-merged. Cyclic `extends` references throw. Relative paths retain Oxlint's configuration-directory semantics. The React and Next selections enable their native plugins. Next also ignores its generated `.next/**` output and `next-env.d.ts`. Vitest adds test rules and file overrides for runtime and type tests under `src`. Effect extends the strict native Effect preset and allows its namespace imports and functional composition conventions. @@ -70,6 +68,7 @@ yarn workspace @local/oxlint lint:tsc yarn workspace @local/oxlint lint:oxlint yarn workspace @local/oxlint lint:format yarn workspace @local/oxlint test:unit +yarn workspace @local/oxlint test:integration ``` Packages expose a `lint:oxlint` task alongside any existing `lint:eslint` task. The root Turbo task and lint workflow run it for affected packages. diff --git a/libs/@local/oxlint/docs/task-dependencies.json b/libs/@local/oxlint/docs/task-dependencies.json index f2eebfa510d..dd5772ef2a3 100644 --- a/libs/@local/oxlint/docs/task-dependencies.json +++ b/libs/@local/oxlint/docs/task-dependencies.json @@ -23,6 +23,14 @@ "dependsOn": [], "cache": false }, + "test:integration": { + "dependsOn": [ + "build" + ], + "env": [ + "TEST_COVERAGE" + ] + }, "test:unit": { "dependsOn": [ "build" diff --git a/libs/@local/oxlint/oxlint.config.ts b/libs/@local/oxlint/oxlint.config.ts index 225afa6cf31..6692ec45759 100644 --- a/libs/@local/oxlint/oxlint.config.ts +++ b/libs/@local/oxlint/oxlint.config.ts @@ -1,10 +1,6 @@ -import { createConfig, defineConfig } from "@local/oxlint"; +import { defineConfig } from "@local/oxlint"; export default defineConfig({ - extends: [ - createConfig({ - frameworks: ["vitest"], - runtime: "node", - }), - ], + frameworks: ["vitest"], + runtime: "node", }); diff --git a/libs/@local/oxlint/package.json b/libs/@local/oxlint/package.json index 2660616ec57..2c0aeb1a179 100644 --- a/libs/@local/oxlint/package.json +++ b/libs/@local/oxlint/package.json @@ -20,7 +20,8 @@ "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", "lint:tsc": "tsc --noEmit", "prepare:oxlint": "effect-tsgo patch --no-typescript --oxlint", - "test:unit": "vitest run" + "test:integration": "vitest run --project integration", + "test:unit": "vitest run --project unit" }, "dependencies": { "@effect/tsgo": "0.47.1", diff --git a/libs/@local/oxlint/src/index.test-d.ts b/libs/@local/oxlint/src/index.test-d.ts new file mode 100644 index 00000000000..177bc72c2f0 --- /dev/null +++ b/libs/@local/oxlint/src/index.test-d.ts @@ -0,0 +1,16 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import type { Options } from "@local/oxlint"; +import type { OxlintConfig } from "oxlint"; + +describe("options", () => { + test("native_fields", () => { + expectTypeOf< + Omit + >().toEqualTypeOf(); + }); + + test("required_runtime", () => { + expectTypeOf().toEqualTypeOf<"node" | "browser">(); + }); +}); diff --git a/libs/@local/oxlint/src/index.test.ts b/libs/@local/oxlint/src/index.test.ts index bf933579a2f..17a5141f622 100644 --- a/libs/@local/oxlint/src/index.test.ts +++ b/libs/@local/oxlint/src/index.test.ts @@ -1,14 +1,14 @@ import { describe, expect, test } from "vitest"; -import { createConfig } from "./index.js"; +import { defineConfig } from "./index.js"; -describe("createConfig", () => { +describe("defineConfig", () => { test("strict_defaults", () => { expect.hasAssertions(); - const config = createConfig({ runtime: "node" }); + const config = defineConfig({ runtime: "node" }); - expect(config.categories).toStrictEqual({ + expect(config.extends?.[0]?.categories).toStrictEqual({ correctness: "deny", nursery: "deny", pedantic: "deny", @@ -17,31 +17,43 @@ describe("createConfig", () => { style: "deny", suspicious: "deny", }); - expect(config.options?.typeAware).toBe(true); - expect(config.options?.reportUnusedDisableDirectives).toBe("error"); - expect(config.rules?.["hash/prefer-rust-severities"]).toBe("deny"); - expect(config.rules?.["hash/require-rule-change-comment"]).toBe("deny"); + expect(config.extends?.[0]?.options?.typeAware).toBe(true); + expect(config.extends?.[0]?.options?.reportUnusedDisableDirectives).toBe( + "error", + ); + expect(config.extends?.[0]?.rules?.["hash/prefer-rust-severities"]).toBe( + "deny", + ); + expect( + config.extends?.[0]?.rules?.["hash/require-rule-change-comment"], + ).toBe("deny"); }); test("vitest_boolean_matchers", () => { expect.hasAssertions(); - const config = createConfig({ runtime: "node", frameworks: ["vitest"] }); + const config = defineConfig({ runtime: "node", frameworks: ["vitest"] }); - expect(config.rules?.["vitest/prefer-to-be-falsy"]).toBe("allow"); - expect(config.rules?.["vitest/prefer-to-be-truthy"]).toBe("allow"); + expect(config.extends?.[0]?.rules?.["vitest/prefer-to-be-falsy"]).toBe( + "allow", + ); + expect(config.extends?.[0]?.rules?.["vitest/prefer-to-be-truthy"]).toBe( + "allow", + ); }); test("vitest_effect_tests", () => { expect.hasAssertions(); - const effect = createConfig({ + const effect = defineConfig({ runtime: "node", frameworks: ["vitest", "effect"], }); - const plain = createConfig({ runtime: "node", frameworks: ["vitest"] }); + const plain = defineConfig({ runtime: "node", frameworks: ["vitest"] }); - expect(effect.rules?.["vitest/no-standalone-expect"]).toStrictEqual([ + expect( + effect.extends?.[0]?.rules?.["vitest/no-standalone-expect"], + ).toStrictEqual([ "deny", { additionalTestBlockFunctions: [ @@ -57,18 +69,20 @@ describe("createConfig", () => { ], }, ]); - expect(effect.rules?.["vitest/require-hook"]).toStrictEqual([ + expect(effect.extends?.[0]?.rules?.["vitest/require-hook"]).toStrictEqual([ "deny", { allowedFunctionCalls: ["layer"] }, ]); - expect(plain.rules?.["vitest/no-standalone-expect"]).toBeUndefined(); - expect(plain.rules?.["vitest/require-hook"]).toBeUndefined(); + expect( + plain.extends?.[0]?.rules?.["vitest/no-standalone-expect"], + ).toBeUndefined(); + expect(plain.extends?.[0]?.rules?.["vitest/require-hook"]).toBeUndefined(); }); test("ignore_patterns", () => { expect.hasAssertions(); - const config = createConfig({ + const config = defineConfig({ ignorePatterns: ["generated/**"], runtime: "node", }); @@ -79,16 +93,16 @@ describe("createConfig", () => { test("next_ignore_patterns", () => { expect.hasAssertions(); - const config = createConfig({ + const config = defineConfig({ frameworks: ["next"], ignorePatterns: ["generated/**"], runtime: "node", }); expect(config.ignorePatterns).toStrictEqual([ - "generated/**", ".next/**", "next-env.d.ts", + "generated/**", ]); }); @@ -96,7 +110,7 @@ describe("createConfig", () => { expect.hasAssertions(); expect(() => - createConfig({ + defineConfig({ additionalRestrictedTypes: { [typeName]: "Override" }, runtime: "node", }), diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index 36dbc4743fe..aa244e8c6a6 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -1,13 +1,12 @@ import { URL, fileURLToPath } from "node:url"; import { strict as effectStrict } from "@effect/tsgo/oxlint-presets"; -import { defineConfig } from "oxlint"; +import { inheritConfig } from "./lib/inherit-config.js"; import plugin from "./rules/index.js"; import type { AllowWarnDeny, DummyRuleMap, OxlintConfig } from "oxlint"; -export { defineConfig } from "oxlint"; export type Framework = "react" | "next" | "vitest" | "effect"; export type Runtime = "node" | "browser"; @@ -29,13 +28,13 @@ type AdditionalRestrictedTypes = Readonly & { readonly [TypeName in keyof typeof defaultRestrictedTypes]?: never; }; -export interface Options { +/** Native Oxlint configuration with shared runtime and framework profiles. */ +export interface Options extends OxlintConfig { readonly runtime: Runtime; /** Adds restrictions without replacing built-in entries. Duplicate keys throw. */ readonly additionalRestrictedTypes?: AdditionalRestrictedTypes; readonly frameworks?: readonly Framework[]; - readonly ignorePatterns?: readonly string[]; } type Overrides = NonNullable; @@ -50,7 +49,12 @@ const defineOverride = (override: Overrides[number]): Overrides[number] => override; // oxlint-disable-next-line max-lines-per-function -- no logic, only configuration -export const createConfig = (options: Options): OxlintConfig => { +const createDefaults = ( + options: Pick< + Options, + "runtime" | "frameworks" | "additionalRestrictedTypes" + >, +): OxlintConfig => { const additionalRestrictedTypes = options.additionalRestrictedTypes ?? {}; for (const typeName of Object.keys(defaultRestrictedTypes)) { if (Object.hasOwn(additionalRestrictedTypes, typeName)) { @@ -72,7 +76,7 @@ export const createConfig = (options: Options): OxlintConfig => { const extend: Extends = []; const env: Env = { builtin: true, es2026: true }; const rules: DummyRuleMap = {}; - const ignorePatterns = [...(options.ignorePatterns ?? [])]; + const ignorePatterns: string[] = []; const overrides: Overrides = [ { files: [ @@ -212,7 +216,7 @@ export const createConfig = (options: Options): OxlintConfig => { ]), ); - return defineConfig({ + return { categories: { correctness: "deny", nursery: "deny", @@ -355,5 +359,26 @@ export const createConfig = (options: Options): OxlintConfig => { ...rules, ...pluginDeny, }, - }); + }; }; + +/** + * Combines shared profiles, extensions and package-specific configuration. + * + * Environments and globals merge by name. Settings replace each plugin’s value. Ignore patterns concatenate in inheritance order. Other fields retain Oxlint’s merge semantics. Nested values remain shared with the input configs. + * + * @throws {Error} If extensions contain a cycle or additional restrictions replace a built-in restricted type. + */ +export const defineConfig = ({ + runtime, + frameworks = [], + additionalRestrictedTypes = {}, + ...config +}: Options): OxlintConfig => + inheritConfig({ + ...config, + extends: [ + createDefaults({ runtime, frameworks, additionalRestrictedTypes }), + ...(config.extends ?? []), + ], + }); diff --git a/libs/@local/oxlint/src/lib/inherit-config.test.ts b/libs/@local/oxlint/src/lib/inherit-config.test.ts new file mode 100644 index 00000000000..4cc41c73da9 --- /dev/null +++ b/libs/@local/oxlint/src/lib/inherit-config.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, test } from "vitest"; + +import { inheritConfig } from "./inherit-config.js"; + +import type { OxlintConfig } from "oxlint"; + +describe("inheritConfig", () => { + test("inherited_fields", () => { + expect.hasAssertions(); + + const parent: OxlintConfig = { + env: { node: true }, + globals: { shared: "readonly", parentOnly: "readonly" }, + settings: { react: { version: "18.2" }, custom: { values: [1, 2] } }, + ignorePatterns: ["generated/**"], + }; + const config = inheritConfig({ + extends: [ + { extends: [parent], env: { browser: true } }, + { env: { node: false }, globals: { shared: "writable" } }, + ], + env: { browser: false }, + globals: { shared: "off" }, + settings: { custom: { values: [3] } }, + ignorePatterns: ["!generated/keep.ts"], + }); + + expect(config.env).toStrictEqual({ node: false, browser: false }); + expect(config.globals).toStrictEqual({ + shared: "off", + parentOnly: "readonly", + }); + expect(config.settings).toStrictEqual({ + react: { version: "18.2" }, + custom: { values: [3] }, + }); + expect(config.ignorePatterns).toStrictEqual([ + "generated/**", + "!generated/keep.ts", + ]); + expect(parent).toStrictEqual({ + env: { node: true }, + globals: { shared: "readonly", parentOnly: "readonly" }, + settings: { react: { version: "18.2" }, custom: { values: [1, 2] } }, + ignorePatterns: ["generated/**"], + }); + }); + + test("plugin_settings_replacement", () => { + expect.hasAssertions(); + + const config = inheritConfig({ + extends: [{ settings: { react: { version: "18.2" } } }], + settings: { react: { linkComponents: ["Link"] } }, + }); + + expect(config.settings?.react).toStrictEqual({ linkComponents: ["Link"] }); + }); + + test("native_fields", () => { + expect.hasAssertions(); + + const input: OxlintConfig = { + categories: { correctness: "warn" }, + extends: [ + { + rules: { + "no-console": "deny", // Inherited rules remain native Oxlint input. + }, + }, + ], + jsPlugins: [{ name: "custom", specifier: "custom-plugin" }], + options: { typeAware: false, maxWarnings: 1 }, + overrides: [ + { + files: ["*.ts"], + rules: { + "no-console": "allow", // Preserve file-scoped exceptions. + }, + }, + ], + plugins: ["typescript"], + rules: { + "no-debugger": "deny", // Preserve the package rule map. + }, + }; + const config = inheritConfig(input); + + expect(config).toMatchObject(input); + expect(config.extends).toBe(input.extends); + expect(config.overrides).toBe(input.overrides); + }); + + test("shared_ancestor", () => { + expect.hasAssertions(); + + const parent: OxlintConfig = { env: { node: true } }; + const config = inheritConfig({ + extends: [ + { extends: [parent], env: { node: false } }, + { extends: [parent] }, + ], + }); + + expect(config.env).toStrictEqual({ node: true }); + }); + + test("circular_extension", () => { + expect.hasAssertions(); + + const parent: OxlintConfig = {}; + const child: OxlintConfig = { extends: [parent] }; + parent.extends = [child]; + + expect(() => inheritConfig(child)).toThrow( + "Circular Oxlint configuration inheritance.", + ); + }); +}); diff --git a/libs/@local/oxlint/src/lib/inherit-config.ts b/libs/@local/oxlint/src/lib/inherit-config.ts new file mode 100644 index 00000000000..d209113707d --- /dev/null +++ b/libs/@local/oxlint/src/lib/inherit-config.ts @@ -0,0 +1,35 @@ +import type { OxlintConfig } from "oxlint"; + +const configurations = function* ( + config: OxlintConfig, + ancestors: Set, +): Generator { + if (ancestors.has(config)) { + throw new Error("Circular Oxlint configuration inheritance."); + } + + ancestors.add(config); + for (const extension of config.extends ?? []) { + yield* configurations(extension, ancestors); + } + + ancestors.delete(config); + yield config; +}; + +export const inheritConfig = (config: OxlintConfig): OxlintConfig => { + const env: NonNullable = {}; + const globals: NonNullable = {}; + const settings: NonNullable = {}; + const ignorePatterns: string[] = []; + + // Oxlint does not inherit these fields. Keep its handling of rules, plugins and overrides, including rule-name normalization. + for (const inherited of configurations(config, new Set())) { + Object.assign(env, inherited.env); + Object.assign(globals, inherited.globals); + Object.assign(settings, inherited.settings); + ignorePatterns.push(...(inherited.ignorePatterns ?? [])); + } + + return { ...config, env, globals, settings, ignorePatterns }; +}; diff --git a/libs/@local/oxlint/src/rules/no-property-modifiers.ts b/libs/@local/oxlint/src/rules/no-property-modifiers.ts index 0d7b7325c68..ea35ccb7a94 100644 --- a/libs/@local/oxlint/src/rules/no-property-modifiers.ts +++ b/libs/@local/oxlint/src/rules/no-property-modifiers.ts @@ -293,9 +293,10 @@ const privateNameFix = ( return [ removal, { range: property.key.range, text: `#${name}` }, - ...accesses.map( - (member): Fix => ({ range: member.property.range, text: `#${name}` }), - ), + ...accesses.map((member): Fix => ({ + range: member.property.range, + text: `#${name}`, + })), ]; }; diff --git a/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts b/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts index e76e284695b..ab5e33d1ae2 100644 --- a/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts +++ b/libs/@local/oxlint/src/rules/prefer-rust-severities.test.ts @@ -78,11 +78,11 @@ tester.run("prefer-rust-severities", preferRustSeverities, { 'import type { DummyRuleMap } from "oxlint"; defineRules(({ one: "deny" }) satisfies DummyRuleMap);', }, { - code: 'import { createConfig } from "@local/oxlint"; const rules = { one: 0 } as const;', + code: 'import { defineConfig } from "@local/oxlint"; const rules = { one: 0 } as const;', errors: [severityError], filename: "config-factory.ts", output: - 'import { createConfig } from "@local/oxlint"; const rules = { one: "allow" } as const;', + 'import { defineConfig } from "@local/oxlint"; const rules = { one: "allow" } as const;', }, { code: 'export default { overrides: [{ files: ["test.ts"], rules: { one: 2 } }] };', diff --git a/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts b/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts index 00b71bf193e..44f92bfb967 100644 --- a/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts +++ b/libs/@local/oxlint/src/rules/require-rule-change-comment.test.ts @@ -78,7 +78,7 @@ tester.run("require-rule-change-comment", requireRuleChangeComment, { filename: "config-factory.ts", }, { - code: 'import { createConfig } from "@local/oxlint"; const rules = { one: "off" };', + code: 'import { defineConfig } from "@local/oxlint"; const rules = { one: "off" };', errors: [explanation], }, { diff --git a/libs/@local/oxlint/tests/config.integration.test.ts b/libs/@local/oxlint/tests/config.integration.test.ts new file mode 100644 index 00000000000..ee4fd9ed4a4 --- /dev/null +++ b/libs/@local/oxlint/tests/config.integration.test.ts @@ -0,0 +1,184 @@ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, test } from "vitest"; + +import type { SpawnSyncReturns } from "node:child_process"; + +const binary = fileURLToPath( + new URL("../bin/oxlint", import.meta.resolve("oxlint")), +); +const entry = new URL("../dist/index.js", import.meta.url).href; +const timeout = 10_000; + +const runOxlint = ( + directory: string, + arguments_: readonly string[], +): SpawnSyncReturns => { + const result = spawnSync( + process.execPath, + [ + binary, + "--disable-nested-config", + "-c", + "oxlint.config.mjs", + ...arguments_, + ], + { cwd: directory, encoding: "utf8", timeout }, + ); + if (result.error !== undefined) { + throw result.error; + } + + return result; +}; + +const prepareFiles = (directory: string): void => { + writeFileSync( + path.join(directory, "oxlint.config.mjs"), + `import { defineConfig } from ${JSON.stringify(entry)}; +export default defineConfig({ + runtime: "node", + frameworks: ["next"], + extends: [{ + extends: [{ + env: { browser: true }, + globals: { SHARED: "readonly" }, + settings: { react: { version: "18.2.0" } }, + ignorePatterns: ["generated/**"], + rules: { "no-console": "deny" }, + }], + ignorePatterns: ["middle/**"], + overrides: [{ files: ["*.js"], rules: { "no-debugger": "warn" } }], + }], + ignorePatterns: ["local/**", "!generated/keep.js"], + options: { typeAware: false }, + overrides: [{ files: ["*.js"], rules: { "no-debugger": "allow" } }], + rules: { "eslint/no-console": "allow" }, +}); +`, + ); + const files = { + "globals.js": "console.log(process.pid, window.location, SHARED);\n", + "unknown.js": "console.log(UNDECLARED);\n", + "overrides.js": "debugger;\nexport const marker = true;\n", + ".next/ignored.js": "UNDEFINED_BUILD;\n", + "generated/ignored.js": "UNDEFINED_GENERATED;\n", + "middle/ignored.js": "UNDEFINED_MIDDLE;\n", + "local/ignored.js": "UNDEFINED_LOCAL;\n", + "generated/keep.js": "UNDEFINED_REINCLUDED;\n", + }; + for (const [filename, content] of Object.entries(files)) { + const filenamePath = path.join(directory, filename); + mkdirSync(path.dirname(filenamePath), { recursive: true }); + writeFileSync(filenamePath, content); + } +}; + +const withFixture = (check: (directory: string) => void): void => { + const directory = mkdtempSync(path.join(tmpdir(), "hash-oxlint-config-")); + try { + prepareFiles(directory); + check(directory); + } finally { + rmSync(directory, { force: true, recursive: true }); + } +}; + +describe("resolved_config", () => { + test("inherited_fields", () => { + expect.hasAssertions(); + + withFixture((directory) => { + const result = runOxlint(directory, ["--print-config"]); + + expect(result).toMatchObject({ status: 0 }); + expect(JSON.parse(result.stdout)).toMatchObject({ + env: { builtin: true, es2026: true, node: true, browser: true }, + globals: { SHARED: "readonly" }, + settings: { react: { version: "18.2.0" } }, + options: { typeAware: false, reportUnusedDisableDirectives: "deny" }, + ignorePatterns: [ + ".next/**", + "next-env.d.ts", + "generated/**", + "middle/**", + "local/**", + "!generated/keep.js", + ], + }); + }); + }); + + test("environment_globals", () => { + expect.hasAssertions(); + + withFixture((directory) => { + const valid = runOxlint(directory, [ + "-A", + "all", + "-D", + "no-undef", + "globals.js", + ]); + const invalid = runOxlint(directory, [ + "-A", + "all", + "-D", + "no-undef", + "unknown.js", + ]); + + expect(valid).toMatchObject({ status: 0 }); + expect(invalid.status).toBe(1); + expect(invalid.stdout).toContain("UNDECLARED"); + }); + }); + + test("ignore_patterns", () => { + expect.hasAssertions(); + + withFixture((directory) => { + const ignored = runOxlint(directory, [ + "-A", + "all", + "-D", + "no-undef", + "globals.js", + ".next/ignored.js", + "generated/ignored.js", + "middle/ignored.js", + "local/ignored.js", + ]); + const included = runOxlint(directory, [ + "-A", + "all", + "-D", + "no-undef", + "generated/keep.js", + ]); + + expect(ignored).toMatchObject({ status: 0 }); + expect(included.status).toBe(1); + expect(included.stdout).toContain("UNDEFINED_REINCLUDED"); + }); + }); + + test("native_precedence", () => { + expect.hasAssertions(); + + withFixture((directory) => { + const result = runOxlint(directory, ["--deny-warnings", "overrides.js"]); + const printed = runOxlint(directory, ["--print-config"]); + + expect(result).toMatchObject({ status: 0 }); + expect(printed.status).toBe(0); + expect(JSON.parse(printed.stdout)).toMatchObject({ + rules: { "no-console": "allow" }, + }); + }); + }); +}); diff --git a/libs/@local/oxlint/tsconfig.json b/libs/@local/oxlint/tsconfig.json index d54c7cbc41c..9caf0e37c30 100644 --- a/libs/@local/oxlint/tsconfig.json +++ b/libs/@local/oxlint/tsconfig.json @@ -9,7 +9,8 @@ "src", "oxlint.config.ts", "tsdown.config.ts", - "vitest.config.ts" + "vitest.config.ts", + "tests" ], "exclude": ["dist"] } diff --git a/libs/@local/oxlint/turbo.json b/libs/@local/oxlint/turbo.json index 0ff73890dfa..417ca5aa4be 100644 --- a/libs/@local/oxlint/turbo.json +++ b/libs/@local/oxlint/turbo.json @@ -13,6 +13,9 @@ }, "test:unit": { "dependsOn": ["build"] + }, + "test:integration": { + "dependsOn": ["build"] } } } diff --git a/libs/@local/oxlint/vitest.config.ts b/libs/@local/oxlint/vitest.config.ts index 96dd0982ada..3215fc56f36 100644 --- a/libs/@local/oxlint/vitest.config.ts +++ b/libs/@local/oxlint/vitest.config.ts @@ -1,9 +1,26 @@ -import { defineConfig } from "vitest/config"; +import { configDefaults, defineConfig } from "vitest/config"; + +const integration = "**/*.integration.test.{ts,tsx}"; export default defineConfig({ test: { // Oxlint's RuleTester registers its cases through the test framework's globals. globals: true, - include: ["src/**/*.test.ts"], + projects: [ + { + extends: true, + test: { + name: "unit", + exclude: [...configDefaults.exclude, integration], + }, + }, + { + extends: true, + test: { + name: "integration", + include: [integration], + }, + }, + ], }, }); From 1d6316131a8e65c06a6e7b2fa31eea19e79b5ff0 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:46:27 +0200 Subject: [PATCH 06/13] chore: strengthen lint and return type checks --- libs/@local/oxlint/src/index.test.ts | 114 +--------- libs/@local/oxlint/src/index.ts | 47 ++++ .../oxlint/tests/config.integration.test.ts | 206 ++++++------------ libs/@local/tsconfig/policy.json | 1 + 4 files changed, 115 insertions(+), 253 deletions(-) diff --git a/libs/@local/oxlint/src/index.test.ts b/libs/@local/oxlint/src/index.test.ts index 17a5141f622..ff3d64a052d 100644 --- a/libs/@local/oxlint/src/index.test.ts +++ b/libs/@local/oxlint/src/index.test.ts @@ -3,117 +3,15 @@ import { describe, expect, test } from "vitest"; import { defineConfig } from "./index.js"; describe("defineConfig", () => { - test("strict_defaults", () => { + test("reserved_type", () => { expect.hasAssertions(); - const config = defineConfig({ runtime: "node" }); - - expect(config.extends?.[0]?.categories).toStrictEqual({ - correctness: "deny", - nursery: "deny", - pedantic: "deny", - perf: "deny", - restriction: "deny", - style: "deny", - suspicious: "deny", - }); - expect(config.extends?.[0]?.options?.typeAware).toBe(true); - expect(config.extends?.[0]?.options?.reportUnusedDisableDirectives).toBe( - "error", - ); - expect(config.extends?.[0]?.rules?.["hash/prefer-rust-severities"]).toBe( - "deny", - ); - expect( - config.extends?.[0]?.rules?.["hash/require-rule-change-comment"], - ).toBe("deny"); - }); - - test("vitest_boolean_matchers", () => { - expect.hasAssertions(); - - const config = defineConfig({ runtime: "node", frameworks: ["vitest"] }); - - expect(config.extends?.[0]?.rules?.["vitest/prefer-to-be-falsy"]).toBe( - "allow", - ); - expect(config.extends?.[0]?.rules?.["vitest/prefer-to-be-truthy"]).toBe( - "allow", - ); - }); - - test("vitest_effect_tests", () => { - expect.hasAssertions(); - - const effect = defineConfig({ - runtime: "node", - frameworks: ["vitest", "effect"], - }); - const plain = defineConfig({ runtime: "node", frameworks: ["vitest"] }); - - expect( - effect.extends?.[0]?.rules?.["vitest/no-standalone-expect"], - ).toStrictEqual([ - "deny", - { - additionalTestBlockFunctions: [ - "it", - "it.effect", - "it.effect.skip", - "it.effect.only", - "it.effect.each", - "it.live", - "it.live.skip", - "it.live.only", - "it.live.each", - ], - }, - ]); - expect(effect.extends?.[0]?.rules?.["vitest/require-hook"]).toStrictEqual([ - "deny", - { allowedFunctionCalls: ["layer"] }, - ]); - expect( - plain.extends?.[0]?.rules?.["vitest/no-standalone-expect"], - ).toBeUndefined(); - expect(plain.extends?.[0]?.rules?.["vitest/require-hook"]).toBeUndefined(); - }); - - test("ignore_patterns", () => { - expect.hasAssertions(); - - const config = defineConfig({ - ignorePatterns: ["generated/**"], - runtime: "node", - }); - - expect(config.ignorePatterns).toStrictEqual(["generated/**"]); - }); - - test("next_ignore_patterns", () => { - expect.hasAssertions(); - - const config = defineConfig({ - frameworks: ["next"], - ignorePatterns: ["generated/**"], - runtime: "node", - }); - - expect(config.ignorePatterns).toStrictEqual([ - ".next/**", - "next-env.d.ts", - "generated/**", - ]); - }); - - test.each(["unknown", "object"])("reserved_type_%s", (typeName) => { - expect.hasAssertions(); + const additionalRestrictedTypes: Record = { + unknown: "Override", + }; expect(() => - defineConfig({ - additionalRestrictedTypes: { [typeName]: "Override" }, - runtime: "node", - }), - ).toThrow(`Cannot override the built-in restriction for "${typeName}".`); + defineConfig({ additionalRestrictedTypes, runtime: "node" }), + ).toThrow('"unknown"'); }); }); diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index aa244e8c6a6..450a865ee7d 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -78,6 +78,13 @@ const createDefaults = ( const rules: DummyRuleMap = {}; const ignorePatterns: string[] = []; const overrides: Overrides = [ + { + files: ["**/*.{ts,tsx,mts,cts}"], + rules: { + "jsdoc/require-param-type": "allow", // TypeScript signatures supply parameter types. + "jsdoc/require-returns-type": "allow", // TypeScript signatures supply return types. + }, + }, { files: [ "**/*.config.js", @@ -85,6 +92,7 @@ const createDefaults = ( "**/*.config.mjs", "**/*.config.mts", ], + env: { browser: false, node: true }, rules: { "import/no-default-export": "allow", // config files always use `defineConfig` with a default export }, @@ -106,6 +114,39 @@ const createDefaults = ( switch (framework) { case "react": { plugins.push("react", "react-perf", "jsx-a11y"); + Object.assign( + rules, + defineRules({ + "react/function-component-definition": [ + "deny", // Named declarations distinguish components from helper arrows. + { + namedComponents: "function-declaration", + unnamedComponents: "function-expression", + }, + ], + "react/jsx-filename-extension": [ + "deny", // JSX belongs in TypeScript modules. + { extensions: [".tsx"] }, + ], + "react/jsx-max-depth": [ + "deny", // Deep JSX trees hide component structure. + { max: 6 }, + ], + "react/react-in-jsx-scope": "allow", // The automatic JSX runtime does not require a React import. + }), + ); + overrides.push( + defineOverride({ + files: ["**/*.tsx"], + rules: { + "func-style": [ + "deny", // Allow component declarations in TSX, accepting helper declarations too. + "declaration", + { allowArrowFunctions: true }, + ], + }, + }), + ); break; } @@ -129,6 +170,7 @@ const createDefaults = ( rules, defineRules({ "vitest/consistent-test-it": ["deny", { withinDescribe: "test" }], // Use the same declaration name inside and outside describe blocks. + "vitest/no-hooks": "allow", // Shared setup belongs in hooks, as required by vitest/require-hook. "vitest/no-importing-vitest-globals": "allow", // import Vitest APIs instead of relying on globals "vitest/no-restricted-vi-methods": [ "deny", // Module mocks hide dependencies. Method spies remain available. @@ -292,9 +334,11 @@ const createDefaults = ( ], "no-undefined": "allow", // comparisons need `undefined` "one-var": ["deny", "never"], // use one declaration per variable + "oxc/no-async-await": "allow", // Promise-based code uses native async functions. "oxc/no-optional-chaining": "allow", // optional chaining is useful for optional properties "oxc/no-rest-spread-properties": "allow", // central to functional programming "prefer-destructuring": "allow", // requiring destructuring for reassignment makes the code awkward + "eslint/require-await": "allow", // The TypeScript rule recognizes returned promises without an await expression. "sort-imports": [ "deny", // Sort members while preserving dependency groups and declaration order. { @@ -303,6 +347,7 @@ const createDefaults = ( }, ], "sort-keys": "allow", // declaration order is more important, and fix may be unsafe, sorting of keys does not increase clarity + "typescript/consistent-return": "allow", // TypeScript’s noImplicitReturns checks return paths through control-flow analysis. "typescript/no-floating-promises": [ "deny", // Discarded async failures must not disappear behind void or an IIFE. { @@ -344,6 +389,8 @@ const createDefaults = ( allowString: false, }, ], + "unicorn/no-negated-condition": "allow", // ESLint checks the same condition forms without duplicate diagnostics. + "unicorn/no-nested-ternary": "allow", // ESLint forbids all nested ternaries, including parenthesized ones. "unicorn/no-null": "allow", // `null` is a useful type to indicate explicit absence of a value "func-names": ["deny", "always", { generators: "never" }], // Name functions for stack traces without naming generator callbacks. "typescript/no-empty-interface": ["deny", { allowSingleExtends: true }], // Permit named interfaces for readable editor type hints. diff --git a/libs/@local/oxlint/tests/config.integration.test.ts b/libs/@local/oxlint/tests/config.integration.test.ts index ee4fd9ed4a4..33e9a3fe16e 100644 --- a/libs/@local/oxlint/tests/config.integration.test.ts +++ b/libs/@local/oxlint/tests/config.integration.test.ts @@ -14,171 +14,87 @@ const binary = fileURLToPath( const entry = new URL("../dist/index.js", import.meta.url).href; const timeout = 10_000; -const runOxlint = ( - directory: string, - arguments_: readonly string[], +const lintFiles = ( + files: Readonly>, ): SpawnSyncReturns => { - const result = spawnSync( - process.execPath, - [ - binary, - "--disable-nested-config", - "-c", - "oxlint.config.mjs", - ...arguments_, - ], - { cwd: directory, encoding: "utf8", timeout }, - ); - if (result.error !== undefined) { - throw result.error; - } - - return result; -}; - -const prepareFiles = (directory: string): void => { - writeFileSync( - path.join(directory, "oxlint.config.mjs"), - `import { defineConfig } from ${JSON.stringify(entry)}; -export default defineConfig({ - runtime: "node", - frameworks: ["next"], - extends: [{ - extends: [{ - env: { browser: true }, - globals: { SHARED: "readonly" }, - settings: { react: { version: "18.2.0" } }, - ignorePatterns: ["generated/**"], - rules: { "no-console": "deny" }, - }], - ignorePatterns: ["middle/**"], - overrides: [{ files: ["*.js"], rules: { "no-debugger": "warn" } }], - }], - ignorePatterns: ["local/**", "!generated/keep.js"], - options: { typeAware: false }, - overrides: [{ files: ["*.js"], rules: { "no-debugger": "allow" } }], - rules: { "eslint/no-console": "allow" }, -}); -`, - ); - const files = { - "globals.js": "console.log(process.pid, window.location, SHARED);\n", - "unknown.js": "console.log(UNDECLARED);\n", - "overrides.js": "debugger;\nexport const marker = true;\n", - ".next/ignored.js": "UNDEFINED_BUILD;\n", - "generated/ignored.js": "UNDEFINED_GENERATED;\n", - "middle/ignored.js": "UNDEFINED_MIDDLE;\n", - "local/ignored.js": "UNDEFINED_LOCAL;\n", - "generated/keep.js": "UNDEFINED_REINCLUDED;\n", - }; - for (const [filename, content] of Object.entries(files)) { - const filenamePath = path.join(directory, filename); - mkdirSync(path.dirname(filenamePath), { recursive: true }); - writeFileSync(filenamePath, content); - } -}; - -const withFixture = (check: (directory: string) => void): void => { const directory = mkdtempSync(path.join(tmpdir(), "hash-oxlint-config-")); try { - prepareFiles(directory); - check(directory); + for (const [filename, content] of Object.entries(files)) { + const filenamePath = path.join(directory, filename); + mkdirSync(path.dirname(filenamePath), { recursive: true }); + writeFileSync(filenamePath, content); + } + + const result = spawnSync( + process.execPath, + [ + binary, + "--disable-nested-config", + "-c", + "oxlint.config.mjs", + "-A", + "all", + "-D", + "no-undef", + "--format", + "json", + ".", + ], + { cwd: directory, encoding: "utf8", timeout }, + ); + if (result.error !== undefined) { + throw result.error; + } + + return result; } finally { rmSync(directory, { force: true, recursive: true }); } }; -describe("resolved_config", () => { - test("inherited_fields", () => { - expect.hasAssertions(); - - withFixture((directory) => { - const result = runOxlint(directory, ["--print-config"]); - - expect(result).toMatchObject({ status: 0 }); - expect(JSON.parse(result.stdout)).toMatchObject({ - env: { builtin: true, es2026: true, node: true, browser: true }, - globals: { SHARED: "readonly" }, - settings: { react: { version: "18.2.0" } }, - options: { typeAware: false, reportUnusedDisableDirectives: "deny" }, - ignorePatterns: [ - ".next/**", - "next-env.d.ts", - "generated/**", - "middle/**", - "local/**", - "!generated/keep.js", - ], - }); - }); - }); - +describe("config_inheritance", () => { test("environment_globals", () => { expect.hasAssertions(); - withFixture((directory) => { - const valid = runOxlint(directory, [ - "-A", - "all", - "-D", - "no-undef", - "globals.js", - ]); - const invalid = runOxlint(directory, [ - "-A", - "all", - "-D", - "no-undef", - "unknown.js", - ]); + const result = lintFiles({ + "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; +export default defineConfig({ + runtime: "node", + extends: [{ env: { browser: true }, globals: { SHARED: "readonly" } }], + options: { typeAware: false }, +}); +`, + "globals.js": "console.log(process.pid, window.location, SHARED);\n", + "unknown.js": "UNDECLARED;\n", + }); - expect(valid).toMatchObject({ status: 0 }); - expect(invalid.status).toBe(1); - expect(invalid.stdout).toContain("UNDECLARED"); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + diagnostics: [{ filename: "unknown.js", code: "eslint(no-undef)" }], }); }); test("ignore_patterns", () => { expect.hasAssertions(); - withFixture((directory) => { - const ignored = runOxlint(directory, [ - "-A", - "all", - "-D", - "no-undef", - "globals.js", - ".next/ignored.js", - "generated/ignored.js", - "middle/ignored.js", - "local/ignored.js", - ]); - const included = runOxlint(directory, [ - "-A", - "all", - "-D", - "no-undef", - "generated/keep.js", - ]); - - expect(ignored).toMatchObject({ status: 0 }); - expect(included.status).toBe(1); - expect(included.stdout).toContain("UNDEFINED_REINCLUDED"); + const result = lintFiles({ + "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; +export default defineConfig({ + runtime: "node", + extends: [{ ignorePatterns: ["generated/**"] }], + ignorePatterns: ["!generated/keep.js"], + options: { typeAware: false }, +}); +`, + "generated/ignored.js": "UNDEFINED_GENERATED;\n", + "generated/keep.js": "UNDEFINED_REINCLUDED;\n", }); - }); - - test("native_precedence", () => { - expect.hasAssertions(); - - withFixture((directory) => { - const result = runOxlint(directory, ["--deny-warnings", "overrides.js"]); - const printed = runOxlint(directory, ["--print-config"]); - expect(result).toMatchObject({ status: 0 }); - expect(printed.status).toBe(0); - expect(JSON.parse(printed.stdout)).toMatchObject({ - rules: { "no-console": "allow" }, - }); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + diagnostics: [ + { filename: "generated/keep.js", code: "eslint(no-undef)" }, + ], }); }); }); diff --git a/libs/@local/tsconfig/policy.json b/libs/@local/tsconfig/policy.json index f6c435db976..c15feb36958 100644 --- a/libs/@local/tsconfig/policy.json +++ b/libs/@local/tsconfig/policy.json @@ -5,6 +5,7 @@ "target": "es2024", "outDir": "${configDir}/dist", "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, "noUncheckedIndexedAccess": true } } From 44d2e7f7babe6609426234e695f0583b1d23142d Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:28:08 +0200 Subject: [PATCH 07/13] feat: add no-complex-ternary rule --- libs/@local/oxlint/README.md | 32 ++- libs/@local/oxlint/src/index.ts | 2 + libs/@local/oxlint/src/rules/index.ts | 2 + .../src/rules/no-complex-ternary.test.ts | 240 ++++++++++++++++++ .../oxlint/src/rules/no-complex-ternary.ts | 233 +++++++++++++++++ 5 files changed, 508 insertions(+), 1 deletion(-) create mode 100644 libs/@local/oxlint/src/rules/no-complex-ternary.test.ts create mode 100644 libs/@local/oxlint/src/rules/no-complex-ternary.ts diff --git a/libs/@local/oxlint/README.md b/libs/@local/oxlint/README.md index c4aa093df1d..ef80d9cadc0 100644 --- a/libs/@local/oxlint/README.md +++ b/libs/@local/oxlint/README.md @@ -19,7 +19,7 @@ Build the package before importing it. `defineConfig` accepts every native Oxlin The shared defaults precede the supplied `extends` entries, and the package's own fields take precedence. Oxlint handles rules, categories, plugins, options and ordered overrides. The helper resolves the fields Oxlint does not inherit: `env` and `globals` merge by name, `settings` merges by plugin name, and `ignorePatterns` concatenates in inheritance order. A later plugin settings value replaces that plugin's earlier value as a whole. Nested objects and arrays are not deep-merged. Cyclic `extends` references throw. Relative paths retain Oxlint's configuration-directory semantics. -The React and Next selections enable their native plugins. Next also ignores its generated `.next/**` output and `next-env.d.ts`. Vitest adds test rules and file overrides for runtime and type tests under `src`. Effect extends the strict native Effect preset and allows its namespace imports and functional composition conventions. +The React and Next selections enable their native plugins. The React profile permits truthiness checks in `.tsx` files for conditional rendering, while `.ts` files retain `strict-boolean-expressions`. This applies to the whole TSX file, not just JSX. Next also ignores its generated `.next/**` output and `next-env.d.ts`. Vitest adds test rules and file overrides for runtime and type tests under `src`. Effect extends the strict native Effect preset and allows its namespace imports and functional composition conventions. `additionalRestrictedTypes` adds messages for restricted types without replacing the built-in entries for `object`, `unknown` and `Function`. An attempt to replace one of those entries throws. `ignorePatterns` passes the package's exclusion globs to Oxlint. @@ -50,6 +50,36 @@ The check recognizes literal `rules` objects, `rules` variable initializers and A comment records an author's justification. These rules check for an explanation. A reviewer must judge whether it supports the assertion or exception. +### Readable ternary branches + +`hash/no-complex-ternary` replaces the blanket `no-ternary` ban. Choosing between values can read more directly beside the value's consumer. Choosing between operations hides conditional work inside an expression, even when the expression fits on one line. Use `if`/`else` for those branches. Inline functions embed another body for the reader to follow, so the rule rejects both arrow and non-arrow functions. Select named callbacks instead. + +Accepted examples: + +```tsx +const options = enabled ? { [key]: value } : {}; +const formatter = detailed + ? new DetailedFormatter(locale) + : new BriefFormatter(locale); +const label = enabled ? text`Enabled: ${name}` : text`Disabled`; +const view = enabled ? : ; +const callback = enabled ? refresh : fallback; +``` + +The rule checks both branches, not the condition. It accepts literals, references, object and array construction, member access, constructors and templates. Computed keys, spreads, constructor arguments and template interpolations undergo the same check. JSX remains opaque. Constructors, tags and getters may execute code, so this policy does not prove that an expression is pure. + +Rejected examples: + +```ts +const options = enabled ? { value: compute() } : {}; +const formatter = detailed ? new Formatter(loadLocale()) : fallback; +const callback = enabled ? () => refresh() : fallback; +``` + +The first two diagnostics highlight `compute()` and `loadLocale()`, respectively, and explain that a call hides conditional work. The third highlights the arrow function and suggests selecting a callback by reference. Neither example marks the whole ternary as merely “complex”. The rule reports independent problems in both branches: `{ first: loadFirst(), second: loadSecond() }` receives two findings. It stops inspecting inside a rejected expression, so `outer(inner())` receives one finding. A nested ternary inside accepted JSX still receives its own check. + +Calls, mutations, `await`, `yield`, `import()` expressions and further conditional evaluation require explicit control flow. The rule also rejects binary, logical and unary expressions rather than judging their complexity by length. It offers no autofix: turning a value expression into statements requires choosing where the result lives, and moving a condition inside a callback can change when it runs. + ## Preparation and checks The Effect rules require a patched Oxlint binary. From the repository root, run: diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index 450a865ee7d..9e0547e55a5 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -144,6 +144,7 @@ const createDefaults = ( "declaration", { allowArrowFunctions: true }, ], + "typescript/strict-boolean-expressions": "allow", // JSX commonly uses truthiness for conditional rendering. }, }), ); @@ -332,6 +333,7 @@ const createDefaults = ( ignoreTypeIndexes: true, }, ], + "no-ternary": "allow", // hash/no-complex-ternary restricts branch expressions without banning simple value selection. "no-undefined": "allow", // comparisons need `undefined` "one-var": ["deny", "never"], // use one declaration per variable "oxc/no-async-await": "allow", // Promise-based code uses native async functions. diff --git a/libs/@local/oxlint/src/rules/index.ts b/libs/@local/oxlint/src/rules/index.ts index fb165c8abfa..83729f6b372 100644 --- a/libs/@local/oxlint/src/rules/index.ts +++ b/libs/@local/oxlint/src/rules/index.ts @@ -1,6 +1,7 @@ import { definePlugin } from "@oxlint/plugins"; import { namingConventions } from "./naming-conventions.js"; +import { noComplexTernary } from "./no-complex-ternary.js"; import { noPropertyModifiers } from "./no-property-modifiers.js"; import { preferOptionsObject } from "./prefer-options-object.js"; import { preferRustSeverities } from "./prefer-rust-severities.js"; @@ -15,6 +16,7 @@ export default definePlugin({ }, rules: { "naming-conventions": namingConventions, + "no-complex-ternary": noComplexTernary, "no-property-modifiers": noPropertyModifiers, "prefer-options-object": preferOptionsObject, "prefer-rust-severities": preferRustSeverities, diff --git a/libs/@local/oxlint/src/rules/no-complex-ternary.test.ts b/libs/@local/oxlint/src/rules/no-complex-ternary.test.ts new file mode 100644 index 00000000000..c961096a2bc --- /dev/null +++ b/libs/@local/oxlint/src/rules/no-complex-ternary.test.ts @@ -0,0 +1,240 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { noComplexTernary } from "./no-complex-ternary.js"; + +const tester = new RuleTester({ + languageOptions: { parserOptions: { lang: "tsx" } }, +}); + +const rejects = ( + code: string, + ...findings: readonly [expression: string, messageId: string][] +): RuleTester.InvalidTestCase => ({ + code, + errors: findings.map(([expression, messageId]) => { + const offset = code.indexOf(expression); + if (offset === -1 || offset !== code.lastIndexOf(expression)) { + throw new Error(`Expected a unique diagnostic span: ${expression}`); + } + const before = code.slice(0, offset); + const through = code.slice(0, offset + expression.length); + return { + messageId, + line: before.split("\n").length, + column: before.length - before.lastIndexOf("\n") - 1, + endLine: through.split("\n").length, + endColumn: through.length - through.lastIndexOf("\n") - 1, + }; + }), + output: null, +}); + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("no-complex-ternary", noComplexTernary, { + invalid: [ + rejects("const result = enabled ? compute() : fallback;", [ + "compute()", + "call", + ]), + rejects("const result = enabled ? value : compute();", [ + "compute()", + "call", + ]), + rejects("const result = enabled ? { value: compute() } : {};", [ + "compute()", + "call", + ]), + rejects("const result = enabled ? { [getKey()]: value } : {};", [ + "getKey()", + "call", + ]), + rejects("const result = enabled ? { ...getOptions() } : {};", [ + "getOptions()", + "call", + ]), + rejects( + "const result = enabled ? { values: [value, { nested: compute() }] } : {};", + ["compute()", "call"], + ), + rejects("const result = enabled ? [...getValues()] : [];", [ + "getValues()", + "call", + ]), + rejects("const result = enabled ? getObject().value : fallback;", [ + "getObject()", + "call", + ]), + rejects("const result = enabled ? object[getKey()] : fallback;", [ + "getKey()", + "call", + ]), + rejects( + "const result = enabled ? new Formatter(loadLocale()) : fallback;", + ["loadLocale()", "call"], + ), + rejects("const result = enabled ? new (getConstructor())() : fallback;", [ + "getConstructor()", + "call", + ]), + rejects( + // oxlint-disable-next-line no-template-curly-in-string -- The source under test must retain its template interpolation. + "const result = enabled ? text`Value: ${compute()}` : text`Absent`;", + ["compute()", "call"], + ), + rejects("const result = enabled ? getTag()`Value` : fallback;", [ + "getTag()", + "call", + ]), + rejects( + // oxlint-disable-next-line no-template-curly-in-string -- The source under test must retain its template interpolation. + "const result = enabled ? `Value: ${compute()}` : fallback;", + ["compute()", "call"], + ), + rejects( + "async function choose() { return enabled ? await pending : fallback; }", + ["await pending", "await"], + ), + rejects("const result = enabled ? (target = value) : fallback;", [ + "target = value", + "assignment", + ]), + rejects("const result = enabled ? count++ : fallback;", [ + "count++", + "update", + ]), + rejects("const result = enabled ? ready && value : fallback;", [ + "ready && value", + "logical", + ]), + rejects("const result = enabled ? (ready ? first : second) : fallback;", [ + "ready ? first : second", + "nestedConditional", + ]), + rejects("const result = enabled ? (first, second) : fallback;", [ + "first, second", + "sequence", + ]), + rejects("const result = enabled ? count + 1 : fallback;", [ + "count + 1", + "binary", + ]), + rejects("const result = enabled ? !ready : fallback;", ["!ready", "unary"]), + rejects("const result = enabled ? object?.value : fallback;", [ + "object?.value", + "optionalChain", + ]), + rejects("const result = enabled ? import('module') : fallback;", [ + "import('module')", + "import", + ]), + rejects("function* choose() { return enabled ? yield value : fallback; }", [ + "yield value", + "yield", + ]), + rejects( + "const result = enabled ? class { static value = compute(); } : fallback;", + ["class { static value = compute(); }", "class"], + ), + rejects("const result = enabled ? (compute() as Value) : fallback;", [ + "compute()", + "call", + ]), + rejects( + "const result = enabled ? (compute() satisfies Value) : fallback;", + ["compute()", "call"], + ), + rejects("const result = enabled ? compute()! : fallback;", [ + "compute()", + "call", + ]), + rejects( + "const callback = enabled ? function run() { return compute(); } : fallback;", + ["function run() { return compute(); }", "inlineFunction"], + ), + rejects("const callback = enabled ? () => compute() : fallback;", [ + "() => compute()", + "inlineFunction", + ]), + rejects( + "const callback = enabled ? (value: string) => { return value; } : fallback;", + ["(value: string) => { return value; }", "inlineFunction"], + ), + rejects( + `enabled + ? { + first: loadFirst(), + [getKey()]: loadSecond(), + } + : fallback();`, + ["loadFirst()", "call"], + ["getKey()", "call"], + ["loadSecond()", "call"], + ["fallback()", "call"], + ), + rejects( + "const result = enabled ? getObject()[getKey()] : fallback;", + ["getObject()", "call"], + ["getKey()", "call"], + ), + rejects( + "const result = enabled ? new (getConstructor())(first(), second()) : fallback;", + ["getConstructor()", "call"], + ["first()", "call"], + ["second()", "call"], + ), + rejects( + // oxlint-disable-next-line no-template-curly-in-string -- The source under test must retain its template interpolation. + "const result = enabled ? getTag()`First: ${first()} Second: ${second()}` : fallback;", + ["getTag()", "call"], + ["first()", "call"], + ["second()", "call"], + ), + rejects("const result = enabled ? outer(inner()) : fallback;", [ + "outer(inner())", + "call", + ]), + rejects( + "const result = enabled ? outer(ready ? first() : second()) : fallback;", + ["outer(ready ? first() : second())", "call"], + ), + rejects( + "const result = enabled ? (ready ? first() : second()) : fallback;", + ["ready ? first() : second()", "nestedConditional"], + ), + rejects( + "const callback = enabled ? () => ready ? first() : second() : fallback;", + ["() => ready ? first() : second()", "inlineFunction"], + ), + rejects( + "const view = enabled ? {ready ? first() : second()} : null;", + ["first()", "call"], + ["second()", "call"], + ), + ], + valid: [ + "const result = enabled ? value : fallback;", + "const result = enabled ? 'present' : null;", + "const options = enabled ? { [key]: value } : {};", + "const result = enabled ? { ...defaults, values: [, value, ...rest] } : {};", + "const result = enabled ? object.value : object[key];", + "class State { #value = 0; read() { return enabled ? this.#value : this; } }", + "const formatter = detailed ? new DetailedFormatter(locale) : new BriefFormatter(locale);", + "const result = enabled ? new registry.Factory(...arguments_) : fallback;", + // oxlint-disable-next-line no-template-curly-in-string -- The source under test must retain its template interpolation. + "const label = enabled ? text`Enabled: ${name}` : text`Disabled`;", + // oxlint-disable-next-line no-template-curly-in-string -- The source under test must retain its template interpolation. + "const result = enabled ? tags.text`Value: ${object[key]}` : `Value: ${value}`;", + "const result = enabled ? ((value as Value) satisfies Value)! : fallback;", + { + code: "const result = enabled ? value : fallback;", + languageOptions: { parserOptions: { lang: "ts" } }, + }, + "const callback = enabled ? refresh : fallback;", + "const callback = enabled ? refresh : fallback;", + "const location = enabled ? import.meta : fallback;", + "class Child extends Parent { read() { return enabled ? super.value : fallback; } }", + "const view = enabled ? : ;", + "const view = enabled ? <>{render()} : null;", + "const result = isEnabled() ? { value } : {};", + ], +}); diff --git a/libs/@local/oxlint/src/rules/no-complex-ternary.ts b/libs/@local/oxlint/src/rules/no-complex-ternary.ts new file mode 100644 index 00000000000..6297300d378 --- /dev/null +++ b/libs/@local/oxlint/src/rules/no-complex-ternary.ts @@ -0,0 +1,233 @@ +/** + * Explains conditional work hidden inside ternary branches. + * + * Ternaries keep value selection beside its consumer. Calls and statement bodies make the reader follow a second operation inside that expression. Use explicit branching for conditional work, and select named callbacks instead of embedding functions. Moving a condition into a callback can change when it runs, so this rule offers no autofix. + * + * The rule inspects both branches, leaving the condition unrestricted. It accepts literals, references, object and array construction, member access, constructors and templates. Computed keys, spreads, constructor arguments and template interpolations undergo the same inspection. JSX remains opaque. Constructors, tags and getters can execute code: this policy does not establish purity. Binary, logical and unary operations remain outside the accepted forms, regardless of length. + * + * Each diagnostic identifies the rejected expression and explains its alternative. Inspection continues through siblings and the other branch, but stops inside a rejected expression to avoid overlapping reports. Nested ternaries inside otherwise accepted JSX receive their own inspection. + * + * @example Accepted + * ```tsx + * const options = enabled ? { [key]: value } : {}; + * const formatter = detailed ? new DetailedFormatter(locale) : new BriefFormatter(locale); + * const label = enabled ? text`Enabled: ${name}` : text`Disabled`; + * const view = enabled ? : ; + * const callback = enabled ? refresh : fallback; + * ``` + * + * @example Rejected + * ```ts + * const options = enabled ? { value: compute() } : {}; + * const formatter = detailed ? new Formatter(loadLocale()) : fallback; + * const callback = enabled ? () => refresh() : fallback; + * ``` + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +import type { ESTree } from "@oxlint/plugins"; + +const messages = { + call: "This call hides conditional work inside a ternary branch. Use an if/else to make that work explicit.", + inlineFunction: + "An inline function embeds another body inside a ternary branch. Name the callback separately and select its reference instead.", + assignment: + "This assignment hides a state change inside a ternary branch. Put the assignment in an explicit if/else branch.", + update: + "This increment or decrement hides a state change inside a ternary branch. Put the update in an explicit if/else branch.", + await: + "This await hides conditional suspension inside a ternary branch. Put the await in an explicit if/else branch.", + yield: + "This yield hides a conditional transfer to the caller inside a ternary branch. Put the yield in an explicit if/else branch.", + nestedConditional: + "This branch introduces another ternary decision. Use explicit if/else branches so the decisions remain visible.", + logical: + "This logical operation introduces short-circuit branching inside a ternary branch. Use explicit if/else branches for the additional decision.", + optionalChain: + "This optional chain introduces a nullish check inside a ternary branch. Use explicit branching to expose both decisions.", + binary: + "This binary operation computes a result inside a ternary branch. Keep ternaries for selecting or constructing values, and put this computation in an if/else branch.", + unary: + "This unary operation transforms a value inside a ternary branch. Keep ternaries for selecting or constructing values, and put this operation in an if/else branch.", + sequence: + "This comma expression combines several evaluations inside a ternary branch. Write those evaluations as statements in an if/else branch.", + import: + "This import starts module loading inside a ternary branch. Use an if/else to make conditional loading explicit.", + class: + "An inline class embeds declarations and possible initialization work inside a ternary branch. Use an if/else to make conditional class creation explicit.", + intrinsic: + "This engine intrinsic hides runtime work inside a ternary branch. Put it in an explicit if/else branch.", +}; + +type ViolationReason = keyof typeof messages; +interface Finding { + readonly node: ESTree.Node; + readonly reason: ViolationReason; +} + +type Expression = ESTree.Expression | ESTree.SpreadElement; +type Expressions = { [Node in Expression as Node["type"]]: Node }; + +// Keep each discriminant paired with its node when indexing the visitor. +type ExpressionOf = { + [Type in Kind]: Expressions[Type] & { type: Type }; +}[Kind]; + +type Inspect = (node: Expression | null) => Iterable; +type Visitors = { + [Kind in keyof Expressions]: + | ViolationReason + | null + | ((node: Expressions[Kind], inspect: Inspect) => Iterable); +}; + +const inspectProperty = function* ( + property: ESTree.ObjectPropertyKind, + inspect: Inspect, +): Generator { + if (property.type === "SpreadElement") { + yield* inspect(property.argument); + return; + } + + if (property.computed && property.key.type !== "PrivateIdentifier") { + yield* inspect(property.key); + } + + yield* inspect(property.value); +}; + +const visitors: Visitors = { + *ArrayExpression(node, inspect) { + for (const element of node.elements) { + yield* inspect(element); + } + }, + ArrowFunctionExpression: "inlineFunction", + AssignmentExpression: "assignment", + AwaitExpression: "await", + BinaryExpression: "binary", + CallExpression: "call", + ChainExpression: "optionalChain", + ClassDeclaration: "class", + ClassExpression: "class", + ConditionalExpression: "nestedConditional", + FunctionDeclaration: "inlineFunction", + FunctionExpression: "inlineFunction", + Identifier: null, + ImportExpression: "import", + JSXElement: null, + JSXFragment: null, + Literal: null, + LogicalExpression: "logical", + *MemberExpression(node, inspect) { + yield* inspect(node.object); + if (node.computed) { + yield* inspect(node.property); + } + }, + MetaProperty: null, + *NewExpression(node, inspect) { + yield* inspect(node.callee); + for (const argument of node.arguments) { + yield* inspect(argument); + } + }, + *ObjectExpression(node, inspect) { + for (const property of node.properties) { + yield* inspectProperty(property, inspect); + } + }, + ParenthesizedExpression: (node, inspect) => inspect(node.expression), + SequenceExpression: "sequence", + SpreadElement: (node, inspect) => inspect(node.argument), + Super: null, + TSAsExpression: (node, inspect) => inspect(node.expression), + TSDeclareFunction: "inlineFunction", + TSEmptyBodyFunctionExpression: "inlineFunction", + TSInstantiationExpression: (node, inspect) => inspect(node.expression), + TSNonNullExpression: (node, inspect) => inspect(node.expression), + TSSatisfiesExpression: (node, inspect) => inspect(node.expression), + TSTypeAssertion: (node, inspect) => inspect(node.expression), + *TaggedTemplateExpression(node, inspect) { + yield* inspect(node.tag); + yield* inspect(node.quasi); + }, + *TemplateLiteral(node, inspect) { + for (const expression of node.expressions) { + yield* inspect(expression); + } + }, + ThisExpression: null, + UnaryExpression: "unary", + UpdateExpression: "update", + V8IntrinsicExpression: "intrinsic", + YieldExpression: "yield", +}; + +const findViolations = function* ( + node: ExpressionOf | null, +): Generator { + if (node === null) { + return; + } + + const visitor = visitors[node.type]; + if (visitor === null) { + return; + } + if (typeof visitor === "string") { + yield { node, reason: visitor }; + return; + } + + yield* visitor(node, findViolations); +}; + +const isAlreadyRejected = ( + node: ESTree.Node, + rejected: ReadonlySet, +): boolean => { + for ( + let current: ESTree.Node | null = node; + current !== null; + current = current.parent + ) { + if (rejected.has(current)) { + return true; + } + } + + return false; +}; + +export const noComplexTernary = defineRule({ + createOnce: (context) => { + // Oxlint visits nested ternaries separately. Remember rejected nodes to suppress overlapping descendant reports. + const rejected = new Set(); + return { + before: (): void => { + rejected.clear(); + }, + after: (): void => { + rejected.clear(); + }, + ConditionalExpression: (node): void => { + if (isAlreadyRejected(node, rejected)) { + return; + } + + for (const branch of [node.consequent, node.alternate]) { + for (const finding of findViolations(branch)) { + rejected.add(finding.node); + context.report({ messageId: finding.reason, node: finding.node }); + } + } + }, + }; + }, + meta: { messages, schema: [], type: "suggestion" }, +}); From 5742ff8e9c803c15f2d5ee81fc0348854b66d084 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 23 Oct 2026 10:13:36 +0200 Subject: [PATCH 08/13] chore: align Effect tests and numeric literals in Oxlint --- libs/@local/oxlint/src/index.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index 9e0547e55a5..c59587c2a46 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -188,19 +188,28 @@ const createDefaults = ( ); if (options.frameworks?.includes("effect") ?? false) { - const effectTesters = ["it.effect", "it.live"].flatMap((tester) => [ - tester, - `${tester}.skip`, - `${tester}.only`, - `${tester}.each`, - ]); + const effectTesters = ["it.effect", "it.live", "it.prop"].flatMap( + (tester) => [ + tester, + `${tester}.skip`, + `${tester}.only`, + `${tester}.each`, + ], + ); Object.assign( rules, defineRules({ "vitest/no-standalone-expect": [ "deny", // @effect/vitest declares tests through `it.effect` and `it.live`, and `layer` hands its tests an `it` of their own. - { additionalTestBlockFunctions: ["it", ...effectTesters] }, + { + additionalTestBlockFunctions: [ + "it", + "it.effect.prop", + "it.live.prop", + ...effectTesters, + ], + }, ], "vitest/require-hook": [ "deny", // @effect/vitest's `layer` provides services to the tests it groups. @@ -394,6 +403,7 @@ const createDefaults = ( "unicorn/no-negated-condition": "allow", // ESLint checks the same condition forms without duplicate diagnostics. "unicorn/no-nested-ternary": "allow", // ESLint forbids all nested ternaries, including parenthesized ones. "unicorn/no-null": "allow", // `null` is a useful type to indicate explicit absence of a value + "unicorn/number-literal-case": "allow", // oxfmt owns numeric-literal formatting "func-names": ["deny", "always", { generators: "never" }], // Name functions for stack traces without naming generator callbacks. "typescript/no-empty-interface": ["deny", { allowSingleExtends: true }], // Permit named interfaces for readable editor type hints. "typescript/no-empty-object-type": [ From 2621c15476f9bda22b723e691f344fd132807254 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:29:49 +0100 Subject: [PATCH 09/13] chore: forbid runtime expect in type tests --- libs/@local/oxlint/src/index.ts | 13 ++++ .../oxlint/tests/config.integration.test.ts | 64 +++++++++++++++---- 2 files changed, 66 insertions(+), 11 deletions(-) diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index c59587c2a46..e37c0e572e6 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -226,6 +226,19 @@ const createDefaults = ( "vitest/prefer-expect-assertions": "allow", // type tests run through the compiler, not the runtime assertion counter. "no-magic-numbers": "allow", // magic numbers are often used in test fixtures "max-lines-per-function": "allow", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests + "no-restricted-imports": [ + "deny", // Vitest typechecks these files without running them, so a runtime assertion here never executes. + { + paths: [ + { + name: "vitest", + importNames: ["expect"], + message: + "Vitest only typechecks *.test-d.ts files. Use expectTypeOf here, and move runtime assertions to the matching *.test.ts file.", + }, + ], + }, + ], }, }), defineOverride({ diff --git a/libs/@local/oxlint/tests/config.integration.test.ts b/libs/@local/oxlint/tests/config.integration.test.ts index 33e9a3fe16e..ee0d933a2d7 100644 --- a/libs/@local/oxlint/tests/config.integration.test.ts +++ b/libs/@local/oxlint/tests/config.integration.test.ts @@ -16,6 +16,7 @@ const timeout = 10_000; const lintFiles = ( files: Readonly>, + rule: string, ): SpawnSyncReturns => { const directory = mkdtempSync(path.join(tmpdir(), "hash-oxlint-config-")); try { @@ -35,7 +36,7 @@ const lintFiles = ( "-A", "all", "-D", - "no-undef", + rule, "--format", "json", ".", @@ -56,17 +57,20 @@ describe("config_inheritance", () => { test("environment_globals", () => { expect.hasAssertions(); - const result = lintFiles({ - "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; + const result = lintFiles( + { + "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; export default defineConfig({ runtime: "node", extends: [{ env: { browser: true }, globals: { SHARED: "readonly" } }], options: { typeAware: false }, }); `, - "globals.js": "console.log(process.pid, window.location, SHARED);\n", - "unknown.js": "UNDECLARED;\n", - }); + "globals.js": "console.log(process.pid, window.location, SHARED);\n", + "unknown.js": "UNDECLARED;\n", + }, + "no-undef", + ); expect(result.status).toBe(1); expect(JSON.parse(result.stdout)).toMatchObject({ @@ -77,8 +81,9 @@ export default defineConfig({ test("ignore_patterns", () => { expect.hasAssertions(); - const result = lintFiles({ - "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; + const result = lintFiles( + { + "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; export default defineConfig({ runtime: "node", extends: [{ ignorePatterns: ["generated/**"] }], @@ -86,9 +91,11 @@ export default defineConfig({ options: { typeAware: false }, }); `, - "generated/ignored.js": "UNDEFINED_GENERATED;\n", - "generated/keep.js": "UNDEFINED_REINCLUDED;\n", - }); + "generated/ignored.js": "UNDEFINED_GENERATED;\n", + "generated/keep.js": "UNDEFINED_REINCLUDED;\n", + }, + "no-undef", + ); expect(result.status).toBe(1); expect(JSON.parse(result.stdout)).toMatchObject({ @@ -98,3 +105,38 @@ export default defineConfig({ }); }); }); + +describe("vitest_profile", () => { + test("type_tests_reject_runtime_expect", () => { + expect.hasAssertions(); + + const result = lintFiles( + { + "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; +export default defineConfig({ + frameworks: ["vitest"], + runtime: "node", + options: { typeAware: false }, +}); +`, + "src/runtime.test-d.ts": + 'import { expect } from "vitest";\n\nexpect(1).toBe(1);\n', + "src/types.test-d.ts": + 'import { expectTypeOf } from "vitest";\n\nexpectTypeOf(1).toBeNumber();\n', + "src/runtime.test.ts": + 'import { expect } from "vitest";\n\nexpect(1).toBe(1);\n', + }, + "no-restricted-imports", + ); + + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + diagnostics: [ + { + filename: "src/runtime.test-d.ts", + code: "eslint(no-restricted-imports)", + }, + ], + }); + }); +}); From 29106eebaecf5f52f6f282e1029659b3b01e06a8 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:39:29 +0100 Subject: [PATCH 10/13] chore: exempt test files from max-lines --- libs/@local/oxlint/src/index.ts | 2 ++ .../oxlint/tests/config.integration.test.ts | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index e37c0e572e6..7d309746cfc 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -226,6 +226,7 @@ const createDefaults = ( "vitest/prefer-expect-assertions": "allow", // type tests run through the compiler, not the runtime assertion counter. "no-magic-numbers": "allow", // magic numbers are often used in test fixtures "max-lines-per-function": "allow", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests + "max-lines": "allow", // one test file covers one module, so it grows with that module's cases "no-restricted-imports": [ "deny", // Vitest typechecks these files without running them, so a runtime assertion here never executes. { @@ -246,6 +247,7 @@ const createDefaults = ( rules: { "no-magic-numbers": "allow", // magic numbers are often used in test fixtures "max-lines-per-function": "allow", // tests are allowed to have more statements, because `describe` blocks are often used to group related tests + "max-lines": "allow", // one test file covers one module, so it grows with that module's cases }, }), ); diff --git a/libs/@local/oxlint/tests/config.integration.test.ts b/libs/@local/oxlint/tests/config.integration.test.ts index ee0d933a2d7..e72a8850234 100644 --- a/libs/@local/oxlint/tests/config.integration.test.ts +++ b/libs/@local/oxlint/tests/config.integration.test.ts @@ -139,4 +139,30 @@ export default defineConfig({ ], }); }); + + test("tests_exempt_from_max_lines", () => { + expect.hasAssertions(); + + const long = `${Array.from({ length: 501 }, (_, line) => `// ${line}`).join("\n")}\n`; + const result = lintFiles( + { + "oxlint.config.mjs": `import { defineConfig } from ${JSON.stringify(entry)}; +export default defineConfig({ + frameworks: ["vitest"], + runtime: "node", + options: { typeAware: false }, +}); +`, + "src/module.ts": long, + "src/module.test.ts": long, + "src/module.test-d.ts": long, + }, + "max-lines", + ); + + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + diagnostics: [{ filename: "src/module.ts", code: "eslint(max-lines)" }], + }); + }); }); From 4165c74e72d3cd047f81e5ec0131d8f3fae26e4b Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:08:18 +0100 Subject: [PATCH 11/13] feat: require ticket IDs in TODO comments --- libs/@local/oxlint/README.md | 2 +- libs/@local/oxlint/src/index.ts | 4 ++ libs/@local/oxlint/src/rules/index.ts | 2 + .../src/rules/require-todo-ticket.test.ts | 38 ++++++++++++++++ .../oxlint/src/rules/require-todo-ticket.ts | 44 +++++++++++++++++++ 5 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 libs/@local/oxlint/src/rules/require-todo-ticket.test.ts create mode 100644 libs/@local/oxlint/src/rules/require-todo-ticket.ts diff --git a/libs/@local/oxlint/README.md b/libs/@local/oxlint/README.md index ef80d9cadc0..3ac4bb7d081 100644 --- a/libs/@local/oxlint/README.md +++ b/libs/@local/oxlint/README.md @@ -25,7 +25,7 @@ The React and Next selections enable their native plugins. The React profile per ## Repository rules -The `hash` plugin enforces naming conventions, including mapped type parameters. Its naming fixes update references and avoid name collisions. Other rules cover JavaScript visibility and options-object parameters. Type assertions and individual lint suppressions require explanations. +The `hash` plugin enforces naming conventions, including mapped type parameters. Its naming fixes update references and avoid name collisions. Other rules cover JavaScript visibility and options-object parameters. Type assertions and individual lint suppressions require explanations, and a TODO comment names its ticket as `TODO(KEY-123): description`. Use `allow`, `warn` or `deny` for rule severities. The default `hash/prefer-rust-severities` rule checks literal settings and fixes equivalent ESLint aliases: diff --git a/libs/@local/oxlint/src/index.ts b/libs/@local/oxlint/src/index.ts index 7d309746cfc..94d2fa06939 100644 --- a/libs/@local/oxlint/src/index.ts +++ b/libs/@local/oxlint/src/index.ts @@ -359,6 +359,10 @@ const createDefaults = ( ], "no-ternary": "allow", // hash/no-complex-ternary restricts branch expressions without banning simple value selection. "no-undefined": "allow", // comparisons need `undefined` + "no-warning-comments": [ + "deny", // exclude TODO, as we use TODO(NN-XXX): [...] + { terms: ["fixme", "xxx"] }, + ], "one-var": ["deny", "never"], // use one declaration per variable "oxc/no-async-await": "allow", // Promise-based code uses native async functions. "oxc/no-optional-chaining": "allow", // optional chaining is useful for optional properties diff --git a/libs/@local/oxlint/src/rules/index.ts b/libs/@local/oxlint/src/rules/index.ts index 83729f6b372..44114983207 100644 --- a/libs/@local/oxlint/src/rules/index.ts +++ b/libs/@local/oxlint/src/rules/index.ts @@ -8,6 +8,7 @@ import { preferRustSeverities } from "./prefer-rust-severities.js"; import { requireRuleChangeComment } from "./require-rule-change-comment.js"; import { requireSafetyCommentForTypeAssertion } from "./require-safety-comment-for-type-assertion.js"; import { requireSuppressionComment } from "./require-suppression-comment.js"; +import { requireTodoTicket } from "./require-todo-ticket.js"; // oxlint-disable-next-line import/no-default-export -- required by the plugin API export default definePlugin({ @@ -24,5 +25,6 @@ export default definePlugin({ "require-safety-comment-for-type-assertion": requireSafetyCommentForTypeAssertion, "require-suppression-comment": requireSuppressionComment, + "require-todo-ticket": requireTodoTicket, }, }); diff --git a/libs/@local/oxlint/src/rules/require-todo-ticket.test.ts b/libs/@local/oxlint/src/rules/require-todo-ticket.test.ts new file mode 100644 index 00000000000..f4c9ea3bd30 --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-todo-ticket.test.ts @@ -0,0 +1,38 @@ +import { RuleTester } from "oxlint/plugins-dev"; + +import { requireTodoTicket } from "./require-todo-ticket.js"; + +const tester = new RuleTester(); + +const ticket = { messageId: "ticket" }; + +// oxlint-disable-next-line vitest/require-hook -- RuleTester declares and runs test cases rather than setting up shared state. +tester.run("require-todo-ticket", requireTodoTicket, { + invalid: [ + { code: "// TODO: cache the resolved path", errors: [ticket] }, + { code: "// TODO cache the resolved path", errors: [ticket] }, + { code: "// todo(BE-123): cache the resolved path", errors: [ticket] }, + { code: "// TODO(be-123): cache the resolved path", errors: [ticket] }, + { code: "// todo(be-123): cache the resolved path", errors: [ticket] }, + { code: "// Todo(BE-123): cache the resolved path", errors: [ticket] }, + { code: "// TODO(BE): cache the resolved path", errors: [ticket] }, + { code: "// TODO(BE-123) cache the resolved path", errors: [ticket] }, + { code: "// TODO(BE-123):", errors: [ticket] }, + { code: "/* TODO: cache the resolved path */", errors: [ticket] }, + // Each report points to its own comment. Oxlint's columns are 0-indexed. + { + code: [ + "// TODO(BE-123): cache the resolved path", + "const a = 1; // TODO: drop the fallback", + ].join("\n"), + errors: [{ column: 13, line: 2, messageId: "ticket" }], + }, + ], + valid: [ + "// TODO(BE-123): cache the resolved path", + "// TODO(SRE-1240): rotate the key", + "/* TODO(H-773): add the creation button */", + "// a comment that mentions a TODO later in its text", + "// TODOs live in Linear", + ], +}); diff --git a/libs/@local/oxlint/src/rules/require-todo-ticket.ts b/libs/@local/oxlint/src/rules/require-todo-ticket.ts new file mode 100644 index 00000000000..efdf9253e67 --- /dev/null +++ b/libs/@local/oxlint/src/rules/require-todo-ticket.ts @@ -0,0 +1,44 @@ +/** + * Requires a TODO comment to name the ticket that tracks its work, as `TODO(KEY-123): description`. + * + * Checks every comment whose text starts with `TODO` in any case, the position `no-warning-comments` checks for its own terms. A TODO later in a comment's text is not checked. Provides no autofix because the author must name the ticket. + * + * @example Incorrect + * ```ts + * // TODO: cache the resolved path. + * ``` + * + * @example Correct + * ```ts + * // TODO(BE-123): cache the resolved path. + * ``` + * + * @module + */ + +import { defineRule } from "@oxlint/plugins"; + +const todo = /^todo\b/iu; +const ticketed = /^TODO\([A-Z]+-\d+\): \S/u; + +export const requireTodoTicket = defineRule({ + createOnce: (context) => ({ + "Program:exit": (): void => { + for (const comment of context.sourceCode.getAllComments()) { + const text = comment.value.trimStart(); + + if (todo.test(text) && !ticketed.test(text)) { + context.report({ messageId: "ticket", node: comment }); + } + } + }, + }), + meta: { + messages: { + ticket: + 'Name the ticket that tracks this work, as "TODO(KEY-123): description".', + }, + schema: [], + type: "problem", + }, +}); From 68617bc187c7e92963e2b600196a769206e49edb Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:26:16 +0100 Subject: [PATCH 12/13] fix: check TODO tickets in JSDoc comments --- .../src/rules/require-todo-ticket.test.ts | 20 +++++++++++++++++++ .../oxlint/src/rules/require-todo-ticket.ts | 13 ++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/libs/@local/oxlint/src/rules/require-todo-ticket.test.ts b/libs/@local/oxlint/src/rules/require-todo-ticket.test.ts index f4c9ea3bd30..2dace4d865a 100644 --- a/libs/@local/oxlint/src/rules/require-todo-ticket.test.ts +++ b/libs/@local/oxlint/src/rules/require-todo-ticket.test.ts @@ -19,6 +19,17 @@ tester.run("require-todo-ticket", requireTodoTicket, { { code: "// TODO(BE-123) cache the resolved path", errors: [ticket] }, { code: "// TODO(BE-123):", errors: [ticket] }, { code: "/* TODO: cache the resolved path */", errors: [ticket] }, + { code: "/** TODO: cache the resolved path */", errors: [ticket] }, + { + code: [ + "/**", + " * Resolves the path.", + " *", + " * TODO: cache the resolved path", + " */", + ].join("\n"), + errors: [ticket], + }, // Each report points to its own comment. Oxlint's columns are 0-indexed. { code: [ @@ -32,6 +43,15 @@ tester.run("require-todo-ticket", requireTodoTicket, { "// TODO(BE-123): cache the resolved path", "// TODO(SRE-1240): rotate the key", "/* TODO(H-773): add the creation button */", + "/** TODO(BE-123): cache the resolved path */", + [ + "/**", + " * Resolves the path.", + " *", + " * TODO(BE-123): cache the resolved path", + " */", + ].join("\n"), + "/** Lists the TODO comments in a file. */", "// a comment that mentions a TODO later in its text", "// TODOs live in Linear", ], diff --git a/libs/@local/oxlint/src/rules/require-todo-ticket.ts b/libs/@local/oxlint/src/rules/require-todo-ticket.ts index efdf9253e67..f2284d841db 100644 --- a/libs/@local/oxlint/src/rules/require-todo-ticket.ts +++ b/libs/@local/oxlint/src/rules/require-todo-ticket.ts @@ -1,7 +1,7 @@ /** * Requires a TODO comment to name the ticket that tracks its work, as `TODO(KEY-123): description`. * - * Checks every comment whose text starts with `TODO` in any case, the position `no-warning-comments` checks for its own terms. A TODO later in a comment's text is not checked. Provides no autofix because the author must name the ticket. + * Checks every line of a comment that starts with `TODO` in any case, after the `*` that a JSDoc comment puts at the start of its lines. A TODO later in a line is not checked. Provides no autofix because the author must name the ticket. * * @example Incorrect * ```ts @@ -20,14 +20,19 @@ import { defineRule } from "@oxlint/plugins"; const todo = /^todo\b/iu; const ticketed = /^TODO\([A-Z]+-\d+\): \S/u; +const lineStart = /^[\s*]*/u; + +const isUnticketed = (line: string): boolean => { + const text = line.replace(lineStart, ""); + + return todo.test(text) && !ticketed.test(text); +}; export const requireTodoTicket = defineRule({ createOnce: (context) => ({ "Program:exit": (): void => { for (const comment of context.sourceCode.getAllComments()) { - const text = comment.value.trimStart(); - - if (todo.test(text) && !ticketed.test(text)) { + if (comment.value.split("\n").some(isUnticketed)) { context.report({ messageId: "ticket", node: comment }); } } From c9769e06e1e9ad5051008b7f9595b2966f7795da Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:57:14 +0100 Subject: [PATCH 13/13] chore: disable noImplicitReturns in tsconfigs --- apps/brunch-agent/tsconfig.json | 4 +++- apps/hash-ai-worker-ts/tsconfig.json | 4 +++- apps/hash-api/tsconfig.json | 5 ++++- apps/hash-frontend/tsconfig.json | 5 ++++- apps/petrinaut-website/api/tsconfig.json | 4 +++- apps/petrinaut-website/tsconfig.json | 5 ++++- apps/plugin-browser/tsconfig.json | 5 ++++- libs/@blockprotocol/graph/tsconfig.json | 5 ++++- libs/@hashintel/block-design-system/tsconfig.json | 4 +++- libs/@hashintel/design-system/tsconfig.json | 4 +++- libs/@hashintel/petrinaut/tsconfig.json | 5 ++++- libs/@hashintel/query-editor/tsconfig.json | 4 +++- libs/@hashintel/type-editor/tsconfig.json | 5 ++++- libs/@local/hash-isomorphic-utils/tsconfig.json | 4 +++- 14 files changed, 49 insertions(+), 14 deletions(-) diff --git a/apps/brunch-agent/tsconfig.json b/apps/brunch-agent/tsconfig.json index c6b509dab54..e848a06b21f 100644 --- a/apps/brunch-agent/tsconfig.json +++ b/apps/brunch-agent/tsconfig.json @@ -3,7 +3,9 @@ "compilerOptions": { "lib": ["DOM", "ESNext"], "types": ["node", "vite/client"], - "noUnusedLocals": false + "noUnusedLocals": false, + // Implicit returns remain in src/server/http/ownership.ts (TS7030). + "noImplicitReturns": false }, "include": ["src", "test", "evals", "*.config.ts"] } diff --git a/apps/hash-ai-worker-ts/tsconfig.json b/apps/hash-ai-worker-ts/tsconfig.json index aa15736c43f..bd9eafe5730 100644 --- a/apps/hash-ai-worker-ts/tsconfig.json +++ b/apps/hash-ai-worker-ts/tsconfig.json @@ -5,6 +5,8 @@ "checkJs": true, "module": "NodeNext", "moduleResolution": "NodeNext", - "lib": ["ES2024", "ESNext.Collection"] + "lib": ["ES2024", "ESNext.Collection"], + // Implicit returns remain in src/shared/testing-utilities/mock-get-flow-context.ts (TS7030). + "noImplicitReturns": false } } diff --git a/apps/hash-api/tsconfig.json b/apps/hash-api/tsconfig.json index f54b0430901..7437e4a490a 100644 --- a/apps/hash-api/tsconfig.json +++ b/apps/hash-api/tsconfig.json @@ -4,7 +4,10 @@ "checkJs": true, "lib": ["ES2024"], "module": "ESNext", - "moduleResolution": "Bundler" + "moduleResolution": "Bundler", + // Implicit returns remain in src/ai/infer-entities-websocket/handle-infer-entities-request.ts, + // src/auth/oauth-consent-handlers.ts and src/graphql/resolvers/embed/index.ts (TS7030). + "noImplicitReturns": false }, "include": ["src", "codegen.config.ts", "vitest.config.ts"] } diff --git a/apps/hash-frontend/tsconfig.json b/apps/hash-frontend/tsconfig.json index b252f28a850..c463d4c64a1 100644 --- a/apps/hash-frontend/tsconfig.json +++ b/apps/hash-frontend/tsconfig.json @@ -3,7 +3,10 @@ "compilerOptions": { "checkJs": true, "target": "ES2021", - "types": ["gapi", "google.accounts", "google.picker"] + "types": ["gapi", "google.accounts", "google.picker"], + // Implicit returns remain across src, and in the @hashintel/design-system and + // @hashintel/type-editor sources this program checks (TS7030). + "noImplicitReturns": false }, "include": [ "next-env.d.ts", diff --git a/apps/petrinaut-website/api/tsconfig.json b/apps/petrinaut-website/api/tsconfig.json index c85f3d3b3d3..99f3c452cd5 100644 --- a/apps/petrinaut-website/api/tsconfig.json +++ b/apps/petrinaut-website/api/tsconfig.json @@ -7,7 +7,9 @@ "moduleResolution": "NodeNext", "noEmit": true, "rootDir": "..", - "verbatimModuleSyntax": true + "verbatimModuleSyntax": true, + // Implicit returns remain in ../src/server/voice/voice-request-guard.ts (TS7030). + "noImplicitReturns": false }, "include": ["./**/*.ts"] } diff --git a/apps/petrinaut-website/tsconfig.json b/apps/petrinaut-website/tsconfig.json index 7143af959eb..22b62eb5f3b 100644 --- a/apps/petrinaut-website/tsconfig.json +++ b/apps/petrinaut-website/tsconfig.json @@ -4,7 +4,10 @@ "lib": ["DOM", "ESNext"], // Parameter properties remain in src/main/app/voice-interview/voice-audio-settings.ts // and two tests (TS1294). - "erasableSyntaxOnly": false + "erasableSyntaxOnly": false, + // Implicit returns remain in src/main/app/plugins/brunch/chat/ai-assistant-panel.tsx, both + // tool-summaries.ts files and src/server/voice/voice-request-guard.ts (TS7030). + "noImplicitReturns": false }, "include": ["src", "router-codegen-config.ts"] } diff --git a/apps/plugin-browser/tsconfig.json b/apps/plugin-browser/tsconfig.json index e496b54a4a8..842927b781d 100644 --- a/apps/plugin-browser/tsconfig.json +++ b/apps/plugin-browser/tsconfig.json @@ -6,7 +6,10 @@ "module": "ESNext", "noEmit": false, "rootDir": "../..", - "target": "ES2021" + "target": "ES2021", + // Implicit returns remain in src/scripts/background.ts, flow-metadata-cell-contents.tsx and + // the @hashintel/design-system sources this program checks (TS7030). + "noImplicitReturns": false }, "include": [ "src", diff --git a/libs/@blockprotocol/graph/tsconfig.json b/libs/@blockprotocol/graph/tsconfig.json index 2f4034438d2..0b8ea186356 100644 --- a/libs/@blockprotocol/graph/tsconfig.json +++ b/libs/@blockprotocol/graph/tsconfig.json @@ -4,7 +4,10 @@ "checkJs": true, "lib": ["dom", "ES2024"], "module": "NodeNext", - "types": ["node"] + "types": ["node"], + // Implicit returns remain in src/codegen/parameters.ts and + // src/stdlib/subgraph/element/entity.ts (TS7030). + "noImplicitReturns": false }, "include": ["src", "eslint.config.js"] } diff --git a/libs/@hashintel/block-design-system/tsconfig.json b/libs/@hashintel/block-design-system/tsconfig.json index 8f5859d8147..f8cc3a43104 100644 --- a/libs/@hashintel/block-design-system/tsconfig.json +++ b/libs/@hashintel/block-design-system/tsconfig.json @@ -4,7 +4,9 @@ "jsx": "preserve", "lib": ["dom", "ESNext"], "module": "ESNext", - "noEmit": true + "noEmit": true, + // Implicit returns remain in the @hashintel/design-system sources this program checks (TS7030). + "noImplicitReturns": false }, "include": ["assets.d.ts", "theme-override.d.ts", "./src/"] } diff --git a/libs/@hashintel/design-system/tsconfig.json b/libs/@hashintel/design-system/tsconfig.json index 8f5859d8147..a6df9037704 100644 --- a/libs/@hashintel/design-system/tsconfig.json +++ b/libs/@hashintel/design-system/tsconfig.json @@ -4,7 +4,9 @@ "jsx": "preserve", "lib": ["dom", "ESNext"], "module": "ESNext", - "noEmit": true + "noEmit": true, + // Implicit returns remain in src/data-type-selector.tsx and src/e-chart.tsx (TS7030). + "noImplicitReturns": false }, "include": ["assets.d.ts", "theme-override.d.ts", "./src/"] } diff --git a/libs/@hashintel/petrinaut/tsconfig.json b/libs/@hashintel/petrinaut/tsconfig.json index 69213721878..7ddd06e9655 100644 --- a/libs/@hashintel/petrinaut/tsconfig.json +++ b/libs/@hashintel/petrinaut/tsconfig.json @@ -4,7 +4,10 @@ "lib": ["DOM", "ESNext"], // Parameter properties remain in src/ui/monaco/code-editor-activity.test.tsx and in // @local/petrinaut-optimizer-client, whose source this program checks (TS1294). - "erasableSyntaxOnly": false + "erasableSyntaxOnly": false, + // Implicit returns remain in src/ui/views/Editor/panels/ai-assistant-panel.tsx and its + // tool-summaries.ts (TS7030). + "noImplicitReturns": false }, "include": ["src", ".storybook/**/*"] } diff --git a/libs/@hashintel/query-editor/tsconfig.json b/libs/@hashintel/query-editor/tsconfig.json index 8f5859d8147..f8cc3a43104 100644 --- a/libs/@hashintel/query-editor/tsconfig.json +++ b/libs/@hashintel/query-editor/tsconfig.json @@ -4,7 +4,9 @@ "jsx": "preserve", "lib": ["dom", "ESNext"], "module": "ESNext", - "noEmit": true + "noEmit": true, + // Implicit returns remain in the @hashintel/design-system sources this program checks (TS7030). + "noImplicitReturns": false }, "include": ["assets.d.ts", "theme-override.d.ts", "./src/"] } diff --git a/libs/@hashintel/type-editor/tsconfig.json b/libs/@hashintel/type-editor/tsconfig.json index 8f5859d8147..6e764234ebe 100644 --- a/libs/@hashintel/type-editor/tsconfig.json +++ b/libs/@hashintel/type-editor/tsconfig.json @@ -4,7 +4,10 @@ "jsx": "preserve", "lib": ["dom", "ESNext"], "module": "ESNext", - "noEmit": true + "noEmit": true, + // Implicit returns remain in src/entity-type-editor/shared/entity-type-table.tsx and + // the @hashintel/design-system sources this program checks (TS7030). + "noImplicitReturns": false }, "include": ["assets.d.ts", "theme-override.d.ts", "./src/"] } diff --git a/libs/@local/hash-isomorphic-utils/tsconfig.json b/libs/@local/hash-isomorphic-utils/tsconfig.json index dc0d67066ad..4d67dcf7f43 100644 --- a/libs/@local/hash-isomorphic-utils/tsconfig.json +++ b/libs/@local/hash-isomorphic-utils/tsconfig.json @@ -13,6 +13,8 @@ * but we have some functions which reference DOM APIs – these should be moved out */ "lib": ["dom", "ES2024"], - "module": "NodeNext" + "module": "NodeNext", + // Implicit returns remain in src/generate-entity-label.ts (TS7030). + "noImplicitReturns": false } }