@inflexa-ai/typecheck 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,62 @@
1
+ @inflexa-ai/typecheck
2
+ Copyright 2026 Inflexa, Inc.
3
+
4
+ This package holds rules that are ports of rules of other packages. The
5
+ notice and the license of each upstream package follow.
6
+
7
+ must-use-result is a port of the rule of the same name of
8
+ @ninoseki/eslint-plugin-neverthrow 0.3.2
9
+ (https://github.com/ninoseki/eslint-plugin-neverthrow).
10
+
11
+ ----------------------------------------------------------------------
12
+
13
+ MIT License
14
+
15
+ Copyright (c) 2024 Manabu Niseki
16
+
17
+ Permission is hereby granted, free of charge, to any person obtaining a copy
18
+ of this software and associated documentation files (the "Software"), to deal
19
+ in the Software without restriction, including without limitation the rights
20
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21
+ copies of the Software, and to permit persons to whom the Software is
22
+ furnished to do so, subject to the following conditions:
23
+
24
+ The above copyright notice and this permission notice shall be included in all
25
+ copies or substantial portions of the Software.
26
+
27
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33
+ SOFTWARE.
34
+
35
+ ----------------------------------------------------------------------
36
+
37
+ no-generated-empty-object-type is a port of the rule of the same name of
38
+ typescript-eslint 8.70.1 (https://github.com/typescript-eslint/typescript-eslint).
39
+
40
+ ----------------------------------------------------------------------
41
+
42
+ MIT License
43
+
44
+ Copyright (c) 2019 typescript-eslint and other contributors
45
+
46
+ Permission is hereby granted, free of charge, to any person obtaining a copy
47
+ of this software and associated documentation files (the "Software"), to deal
48
+ in the Software without restriction, including without limitation the rights
49
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
50
+ copies of the Software, and to permit persons to whom the Software is
51
+ furnished to do so, subject to the following conditions:
52
+
53
+ The above copyright notice and this permission notice shall be included in all
54
+ copies or substantial portions of the Software.
55
+
56
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
57
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
58
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
59
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
60
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
61
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
62
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # @inflexa-ai/typecheck
2
+
3
+ The command `inflexa-typecheck`. It does the type check of `tsc --noEmit` on TypeScript 7, and it runs the typed rules of Inflexa on the same program. One run gives the diagnostics of `tsc` and the reports of the rules that read types.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install --save-dev @inflexa-ai/typecheck typescript@7.0.2
9
+ ```
10
+
11
+ The package reads the program through `typescript/unstable/sync`, which is not under semver. Thus the peer dependency is the exact version of TypeScript that the CI of this package uses. Install that version.
12
+
13
+ ## Run
14
+
15
+ ```sh
16
+ inflexa-typecheck
17
+ inflexa-typecheck -p apps/web -p packages/ui/tsconfig.json
18
+ inflexa-typecheck --config lint/typecheck.config.ts
19
+ ```
20
+
21
+ - `-p <path>` names a tsconfig, or a folder with a `tsconfig.json`. Give `-p` one time for each project. The command checks the projects in the sequence of the flags, in one TypeScript process. Without `-p`, the command checks `tsconfig.json` of the working folder.
22
+ - `--config <path>` names the configuration file, relative to the working folder. Without `--config`, the command reads `typecheck.config.ts` of the working folder. Without that file, it uses `typecheck()`.
23
+
24
+ The command replaces `tsc --noEmit` and the ESLint run of the typed rules. It does not emit, and it has no `--build`, `--watch` or `--pretty`.
25
+
26
+ ## Output
27
+
28
+ For each project, the command prints the lines that `tsc --noEmit --pretty false -p <project>` prints, in the same sequence. The paths are relative to the working folder. The command checks each project with the options of `tsc --noEmit`, also when its tsconfig does not set `noEmit`.
29
+
30
+ Then the command prints the reports of the rules and the problems of the directives of all projects, sorted by path, line and column:
31
+
32
+ ```text
33
+ src/run.ts(4,3): error must-use-result: Result must be handled with either of match, unwrapOr, _unsafeUnwrap or _unsafeUnwrapErr.
34
+ src/run.ts(9,1): error typecheck-disable: The directive gives no reason. Write the reason after ` -- `.
35
+ ```
36
+
37
+ A report has the id of the rule in the place of `TS<code>`. A problem matcher that expects `error TS<digits>:` reads the diagnostics of `tsc`, but it does not read the reports of the rules. To read both, match `error <id>:`, where the id is `TS<digits>`, a rule id, or `typecheck-disable`.
38
+
39
+ One difference from `tsc` exists. For a project with `references`, the command reads the source files of each referenced project, as the project service of an editor does. It does not read their built declarations. Thus it prints no TS6305 for a referenced project that is not built, and it checks each import against the source.
40
+
41
+ The command exits with 1 when it prints a line. It also exits with 1 when it cannot load a project, the configuration, a plugin or the options of a rule. Otherwise it exits with 0.
42
+
43
+ A rule runs on each file of a project that is not a declaration file, not under `node_modules`, and under the working folder. A file in more than one project gets the rule of the first project of the `-p` sequence that holds it. Thus the sequence of the flags selects the options of the program for a shared file.
44
+
45
+ ## Configuration
46
+
47
+ `typecheck.config.ts` default-exports the value of `typecheck()`:
48
+
49
+ ```ts
50
+ import { plugin as react } from '@inflexa-ai/oxlint-plugin-react/typecheck'
51
+ import { typecheck } from '@inflexa-ai/typecheck'
52
+
53
+ export default typecheck({
54
+ plugins: [react],
55
+ overrides: [
56
+ { files: ['src/**'], rules: { 'must-use-result': ['error', { consumers: ['unwrapOrThrow'] }] } },
57
+ { files: ['src/legacy/**'], rules: { 'must-use-result': 'off' } },
58
+ { files: ['src/**/*.tsx'], rules: { '@inflexa-ai/react/no-void-query-fn': 'error' } },
59
+ ],
60
+ })
61
+ ```
62
+
63
+ - `files` holds globs, relative to the working folder.
64
+ - `rules` maps a rule id to `'error'`, `'off'`, or `['error', options]`.
65
+ - For a file and a rule, the last override that matches the file and names the rule sets the severity.
66
+ - `['error', options]` sets the options. `'error'` alone keeps the options of an earlier override that matches the file.
67
+ - `typecheck()` puts its own block first. That block turns on `no-generated-empty-object-type` for `**/*.{ts,tsx}`.
68
+
69
+ Each of these problems stops the run with a message: an unknown rule id, a plugin that loads two times under one name, and options that the rule refuses.
70
+
71
+ Node.js removes the types of the file when it loads it. Thus the file uses only the syntax that Node.js can remove, as the other TypeScript configuration files do.
72
+
73
+ ## Rules
74
+
75
+ | Rule | Document |
76
+ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
77
+ | `must-use-result` | [must-use-result](https://github.com/inflexa-ai/lint/blob/main/docs/rules/must-use-result.md) |
78
+ | `require-abort-signal` | [require-abort-signal](https://github.com/inflexa-ai/lint/blob/main/docs/rules/require-abort-signal.md) |
79
+ | `no-generated-empty-object-type` | [no-generated-empty-object-type](https://github.com/inflexa-ai/lint/blob/main/docs/rules/no-generated-empty-object-type.md) |
80
+
81
+ The rules of this package have no prefix. The rules of a plugin have the id `<plugin name>/<rule name>`, where the plugin name is the `name` of the plugin object. The `./typecheck` entry of `@inflexa-ai/oxlint-plugin-react` gives the plugin `@inflexa-ai/react`.
82
+
83
+ ## Directive
84
+
85
+ To disable a rule on the next line, write a comment with the directive, the ids of the rules, and the reason after `--`:
86
+
87
+ ```ts
88
+ // typecheck-disable-next-line must-use-result -- the caller logs the error
89
+ getResult()
90
+ ```
91
+
92
+ - The directive suppresses the reports of the named rules on the line after the last line of the comment. A block comment can hold the directive too.
93
+ - A directive with no reason is a problem. It still suppresses the reports, thus one mistake gives one line.
94
+ - A directive that names no rule is a problem.
95
+ - A named rule that suppresses nothing is a problem, also when the id is unknown or the rule is off for the file.
96
+ - A directive does not suppress a diagnostic of `tsc`.
97
+ - The command reads directives in comments only, not in a string or a template.
98
+
99
+ ## Write a rule
100
+
101
+ A repository gives its own rules as a plugin:
102
+
103
+ ```ts
104
+ import { isCallExpression, SyntaxKind } from 'typescript/unstable/ast'
105
+ import type { Plugin, RuleModule } from '@inflexa-ai/typecheck'
106
+
107
+ const noRawDate: RuleModule<{ allowIn: string[] }> = {
108
+ meta: {
109
+ docs: { description: 'Use the clock of the app', url: 'https://example.com/no-raw-date' },
110
+ messages: { rawDate: 'Read the time from the clock of the app, not from `{{call}}`.' },
111
+ defaultOptions: { allowIn: [] },
112
+ },
113
+ create(context) {
114
+ return {
115
+ [SyntaxKind.CallExpression]: (node) => {
116
+ if (isCallExpression(node) && node.expression.getText(context.sourceFile) === 'Date.now') {
117
+ context.report({ node, messageId: 'rawDate', data: { call: 'Date.now' } })
118
+ }
119
+ },
120
+ }
121
+ },
122
+ }
123
+
124
+ export const himmel: Plugin = { name: 'himmel', rules: { 'no-raw-date': noRawDate } }
125
+ ```
126
+
127
+ - `create` receives a context with `id`, `options`, `sourceFile`, `program`, `checker` and `report`. It returns the functions that the command calls for the nodes of each syntax kind. The command walks each file one time for all rules.
128
+ - A report starts at the start of its node, without the leading trivia. The data fills the `{{name}}` placeholders of the message.
129
+ - The command merges the configured options over `defaultOptions`. It refuses a key that the defaults do not have, and a value of another JSON kind. An optional `checkOptions` returns a problem with the merged options. `stringArraysOnly` refuses an array option with an element that is not a string.
130
+
131
+ ## Rule tester
132
+
133
+ `@inflexa-ai/typecheck/rule-tester` runs the cases of a rule in a test framework:
134
+
135
+ ```ts
136
+ import { createRuleTester, RuleTester } from '@inflexa-ai/typecheck/rule-tester'
137
+ import { afterAll, describe, it } from 'vitest'
138
+
139
+ RuleTester.describe = describe
140
+ RuleTester.it = it
141
+ RuleTester.afterAll = afterAll
142
+
143
+ createRuleTester({ fixtures: new URL('./fixtures/', import.meta.url).pathname }).run('himmel/no-raw-date', noRawDate, {
144
+ valid: ['export const now = clock.now()'],
145
+ invalid: [{ code: 'export const now = Date.now()', errors: [{ messageId: 'rawDate', data: { call: 'Date.now' }, line: 1, column: 20 }] }],
146
+ })
147
+ ```
148
+
149
+ - The fixture folder holds a `tsconfig.json` that includes the file names of the cases, `case.ts` by default. A case can give another `filename`, and `options`.
150
+ - The tester fails a valid case that reports anything. It fails an invalid case whose reports differ in number, in sequence, in message id, or in a given data, line or column.
151
+ - Each case is a file of the fixture folder that the tester gives to TypeScript. One TypeScript process serves each `run`.
152
+
153
+ ## License
154
+
155
+ Apache-2.0. The rules `must-use-result` and `no-generated-empty-object-type` are ports of rules of `@ninoseki/eslint-plugin-neverthrow` and of typescript-eslint, which have the MIT license. Refer to `NOTICE`.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { TypecheckLoadError } from './errors.js';
4
+ import { runTypecheck } from './run.js';
5
+ function fail(message) {
6
+ process.stderr.write(`inflexa-typecheck: ${message}\n`);
7
+ process.exitCode = 1;
8
+ }
9
+ let values;
10
+ try {
11
+ ;
12
+ ({ values } = parseArgs({ options: { project: { type: 'string', short: 'p', multiple: true }, config: { type: 'string' } } }));
13
+ }
14
+ catch (error) {
15
+ if (!(error instanceof TypeError))
16
+ throw error;
17
+ fail(error.message);
18
+ }
19
+ if (values !== undefined) {
20
+ try {
21
+ const { output, exitCode } = await runTypecheck({ cwd: process.cwd(), projects: values.project ?? [], config: values.config });
22
+ process.stdout.write(output);
23
+ process.exitCode = exitCode;
24
+ }
25
+ catch (error) {
26
+ if (!(error instanceof TypecheckLoadError))
27
+ throw error;
28
+ fail(error.message);
29
+ }
30
+ }
@@ -0,0 +1,61 @@
1
+ import type { Plugin, RuleModule, RuleOptions } from './rule.ts';
2
+ export type Severity = 'error' | 'off';
3
+ /** `'error'` keeps the options of an earlier override, and `['error', options]` sets them. */
4
+ export type RuleSetting = Severity | ['error', RuleOptions];
5
+ /** The rules of the files that `files` matches: globs relative to the working folder, as `path.matchesGlob` reads them. */
6
+ export type Override = {
7
+ files: string[];
8
+ rules: Record<string, RuleSetting>;
9
+ };
10
+ export type TypecheckOptions = {
11
+ /** The plugins of the repository, each with the rule modules under its name. */
12
+ plugins?: Plugin[];
13
+ /**
14
+ * The blocks of the repository. They come after the block of this package,
15
+ * and for a file and a rule the last block that matches the file and names
16
+ * the rule decides.
17
+ */
18
+ overrides?: Override[];
19
+ };
20
+ /**
21
+ * The value of `typecheck()`, which a configuration file default-exports. The
22
+ * command accepts only an instance, thus a configuration always passed through
23
+ * the factory and its default block.
24
+ */
25
+ export declare class TypecheckConfig {
26
+ readonly plugins: readonly Plugin[];
27
+ readonly overrides: readonly Override[];
28
+ constructor(plugins: readonly Plugin[], overrides: readonly Override[]);
29
+ }
30
+ /** A rule that is on for a file, with its options for that file. */
31
+ export type ActiveRule = {
32
+ id: string;
33
+ rule: RuleModule;
34
+ options: RuleOptions;
35
+ };
36
+ export declare const CONFIG_FILE = "typecheck.config.ts";
37
+ /**
38
+ * The configuration of `inflexa-typecheck`. Its own block comes first and
39
+ * turns on `no-generated-empty-object-type` for each TypeScript file, as the
40
+ * former ESLint configuration did. Each other typed rule is on only where an
41
+ * override of the repository turns it on.
42
+ */
43
+ export declare function typecheck({ plugins, overrides }?: TypecheckOptions): TypecheckConfig;
44
+ /**
45
+ * The configuration of the run: the file of `--config`, relative to the
46
+ * working folder, or `typecheck.config.ts` of the working folder, or
47
+ * `typecheck()` when the folder has none. Node strips the types of the file
48
+ * when it loads it.
49
+ */
50
+ export declare function loadConfig(cwd: string, file?: string): Promise<TypecheckConfig>;
51
+ /** The options of a rule merged over its defaults, after the check of each key, each kind, and the check of the rule. */
52
+ export declare function mergeRuleOptions(id: string, rule: RuleModule, configured: RuleOptions): RuleOptions;
53
+ /**
54
+ * The rules of the configuration by id: the rules of this package with no
55
+ * prefix, and each rule of a plugin as `<plugin name>/<rule name>`. It checks
56
+ * each id and each option once, before any file, and stops on the first
57
+ * problem with a message that names the rule or the plugin.
58
+ */
59
+ export declare function resolveRules(config: TypecheckConfig, builtins: Record<string, RuleModule>): {
60
+ rulesFor(file: string): ActiveRule[];
61
+ };
package/dist/config.js ADDED
@@ -0,0 +1,120 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { inspect } from 'node:util';
13
+ import { TypecheckLoadError } from './errors.js';
14
+ export class TypecheckConfig {
15
+ plugins;
16
+ overrides;
17
+ constructor(plugins, overrides) {
18
+ this.plugins = plugins;
19
+ this.overrides = overrides;
20
+ }
21
+ }
22
+ export const CONFIG_FILE = 'typecheck.config.ts';
23
+ export function typecheck({ plugins = [], overrides = [] } = {}) {
24
+ return new TypecheckConfig(plugins, [{ files: ['**/*.{ts,tsx}'], rules: { 'no-generated-empty-object-type': 'error' } }, ...overrides]);
25
+ }
26
+ export async function loadConfig(cwd, file) {
27
+ const target = path.resolve(cwd, file ?? CONFIG_FILE);
28
+ if (!existsSync(target)) {
29
+ if (file === undefined)
30
+ return typecheck();
31
+ throw new TypecheckLoadError(`Cannot find the configuration ${file}.`);
32
+ }
33
+ const name = path.relative(cwd, target);
34
+ let exported;
35
+ try {
36
+ exported = await import(__rewriteRelativeImportExtension(pathToFileURL(target).href)).then((namespace) => namespace.default);
37
+ }
38
+ catch (error) {
39
+ throw new TypecheckLoadError(`Cannot load the configuration ${name}: ${inspect(error)}`, { cause: error });
40
+ }
41
+ if (!(exported instanceof TypecheckConfig))
42
+ throw new TypecheckLoadError(`${name} must default-export the value of \`typecheck()\` of @inflexa-ai/typecheck.`);
43
+ return exported;
44
+ }
45
+ function kindOf(value) {
46
+ if (value === null)
47
+ return 'null';
48
+ if (Array.isArray(value))
49
+ return 'array';
50
+ if (typeof value === 'string')
51
+ return 'string';
52
+ if (typeof value === 'number')
53
+ return 'number';
54
+ if (typeof value === 'boolean')
55
+ return 'boolean';
56
+ return 'object';
57
+ }
58
+ function withArticle(kind) {
59
+ return `${kind === 'array' || kind === 'object' ? 'an' : 'a'} ${kind}`;
60
+ }
61
+ export function mergeRuleOptions(id, rule, configured) {
62
+ const defaults = rule.meta.defaultOptions;
63
+ for (const [key, value] of Object.entries(configured)) {
64
+ if (!Object.hasOwn(defaults, key))
65
+ throw new TypecheckLoadError(`${id} has no option ${key}.`);
66
+ const expected = kindOf(defaults[key]);
67
+ const actual = kindOf(value);
68
+ if (actual !== expected)
69
+ throw new TypecheckLoadError(`${id}: the option ${key} is ${withArticle(actual)}, and it must be ${withArticle(expected)}.`);
70
+ }
71
+ const merged = { ...defaults, ...configured };
72
+ const problem = rule.checkOptions?.(merged);
73
+ if (problem !== undefined)
74
+ throw new TypecheckLoadError(`${id}: ${problem}`);
75
+ return merged;
76
+ }
77
+ function checkSetting(id, setting) {
78
+ const parts = Array.isArray(setting) && setting.length === 2 ? setting : [];
79
+ const [severity, options] = parts;
80
+ if (severity !== 'error' || Object(options) !== options || Array.isArray(options)) {
81
+ throw new TypecheckLoadError(`${id}: a setting is 'error', 'off' or ['error', options], where options is an object.`);
82
+ }
83
+ }
84
+ export function resolveRules(config, builtins) {
85
+ const registry = new Map(Object.entries(builtins));
86
+ const pluginNames = new Set();
87
+ for (const plugin of config.plugins) {
88
+ if (pluginNames.has(plugin.name))
89
+ throw new TypecheckLoadError(`The plugin ${plugin.name} loads twice.`);
90
+ pluginNames.add(plugin.name);
91
+ for (const [name, rule] of Object.entries(plugin.rules))
92
+ registry.set(`${plugin.name}/${name}`, rule);
93
+ }
94
+ const overrides = config.overrides.map(({ files, rules }) => ({
95
+ files,
96
+ settings: Object.entries(rules).map(([id, setting]) => {
97
+ const rule = registry.get(id);
98
+ if (rule === undefined)
99
+ throw new TypecheckLoadError(`No rule has the id ${id}.`);
100
+ if (setting === 'off')
101
+ return { id, rule, on: false, options: undefined };
102
+ if (setting === 'error')
103
+ return { id, rule, on: true, options: undefined };
104
+ checkSetting(id, setting);
105
+ return { id, rule, on: true, options: mergeRuleOptions(id, rule, setting[1]) };
106
+ }),
107
+ }));
108
+ return {
109
+ rulesFor(file) {
110
+ const state = new Map();
111
+ for (const { files, settings } of overrides) {
112
+ if (!files.some((glob) => path.matchesGlob(file, glob)))
113
+ continue;
114
+ for (const { id, rule, on, options } of settings)
115
+ state.set(id, { rule, on, options: options ?? state.get(id)?.options });
116
+ }
117
+ return [...state].filter(([, { on }]) => on).map(([id, { rule, options }]) => ({ id, rule, options: options ?? rule.meta.defaultOptions }));
118
+ },
119
+ };
120
+ }