@sshkeda/check 4.3.0 → 4.4.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/README.md CHANGED
@@ -83,6 +83,8 @@ Check passes.
83
83
 
84
84
  ## Why these rules
85
85
 
86
+ The rules keep code type-safe, observable and predictable. [How to Make Check Pass](docs/how-to-make-check-pass.md) gives each goal and how to decide if a new rule is worth it.
87
+
86
88
  - **No comments.** When code is hard to follow, the fix is better names and simpler code, which stay true as the code changes. Comments drift out of date, and agents fill them with noise. When you need more explanation, ask your agent to explain the code.
87
89
  - **No `type` or `interface` declarations.** Types are inferred from the code that produces each value, so every type has one source of truth and nothing to keep in sync.
88
90
  - **No `let`, and no `while` or counting `for` loops.** Values don't change after they're made, which leaves an agent fewer ways to get state wrong.
@@ -1,6 +1,6 @@
1
1
  # How to Grant a Permission
2
2
 
3
- Grant a permission to one file or directory in `oxlint.config.ts`. The key is the path from the folder that holds `oxlint.config.ts`, with no glob. Each name in `allow` lifts one ban for that path only.
3
+ Grant a permission to one file or directory in `oxlint.config.ts`. The key is the path from the directory that holds `oxlint.config.ts`, with no glob. Each name in `allow` lifts one ban for that path only.
4
4
 
5
5
  ```ts
6
6
  export default lintConfig({
@@ -9,6 +9,8 @@ export default lintConfig({
9
9
  });
10
10
  ```
11
11
 
12
+ Move the code that needs a grant into its own small file and grant that file. A grant covers the whole file, so Check stops reporting that ban for everything else in it.
13
+
12
14
  - `readsConfig`: Allows Effect `Config`, `process.env` and `process.argv`.
13
15
  - `spawnsCommands`: Allows Effect `ChildProcess`, `Bun.spawn` and `spawn` from `node:child_process`.
14
16
  - `locksFiles`: Allows `open` from `node:fs/promises` and `constants` from `node:fs`.
@@ -26,4 +28,4 @@ export default lintConfig({
26
28
  - `handlesEveryFailure`: Allows catching every error, through `Effect.catch`, `Effect.exit`, a forked fiber or `Effect.runPromise`.
27
29
  - `fallsBackToFixedValues`: Allows answering every failure, or a whole library error such as `PlatformError`, with a fixed value that never reads the failure.
28
30
  - `replacesTheConsole`: Allows `Console` from `node:console`, and reading, calling and assigning these members of the global `console` by name: `log`, `warn`, `error`, `info`, `debug`, `dir`, `dirxml`, `table`, `trace`, `assert`, `clear`, `count`, `countReset`, `group`, `groupCollapsed`, `groupEnd`, `time`, `timeEnd` and `timeLog`.
29
- - `isGeneratedByATool`: Check skips this path, so it can't have any other permission.
31
+ - `isGeneratedByATool`: Check skips this path, so it can't have any other permission. Grant it only to a file a tool generates.
@@ -1,33 +1,29 @@
1
1
  # How to Make Check Pass
2
2
 
3
- Fix the cause of each failure, keep the code simple, make program output clear and prevent mistakes from happening again.
3
+ Each rule removes one way to write code that is wrong, hidden or hard to change, so one correct way stays.
4
4
 
5
- Check may not catch every violation of these principles. Review your code against this guide.
5
+ Fix the cause of each failure and keep the code simple. Use a grant only for an unavoidable exception. [How to Grant a Permission](how-to-grant-a-permission.md) lists each grant and what it allows.
6
6
 
7
- ## Meet the requirement behind the error
7
+ Each rule serves one of three goals.
8
8
 
9
- - Use a grant only for an unavoidable exception. [How to Grant a Permission](how-to-grant-a-permission.md) lists each grant and what it allows.
10
- - Move the code that needs a grant into its own small file and grant that file. A grant covers the whole file, so Check stops reporting that ban for everything else in it.
11
- - Design for the current requirement as if you were starting fresh. Delete code the new design doesn't need.
12
- - Handle a forked effect's failure before the fork, or keep the fiber and join it.
13
- - Wrap a Promise in `Effect.tryPromise` and `yield*` it instead of using `await`.
14
- - Read a fact from where a tool states it, such as an error's fields, a command's exit code or its JSON output. Text written for people changes between releases, and code that searches it breaks quietly when it does.
15
- - Return a fixed value only for the one failure you expect, such as a file that isn't there. Let every other failure fail.
16
- - Write a job that moves through stages as an explicit state machine, with one tagged case per stage in one union, so the job is always in exactly one stage.
17
- - Give each status its own struct holding the fields that status always has, and join them in a union.
18
- - Grant `isGeneratedByATool` only to a file a tool generates.
9
+ ## Type-safe
19
10
 
20
- ## Make the code explain itself
11
+ TypeScript knows the true type of every value. Each type has one source, and data from outside the program is checked where it enters.
21
12
 
22
- - Use what Effect, Bun or a dependency already provides.
23
- - Write each fact or decision once and derive the rest from it.
24
- - Give each value a name that says what it holds.
25
13
  - Let TypeScript infer types, or derive them from values and schemas you already use. Don't create a schema only to name a type.
26
14
  - Validate unchecked data with a Schema before treating it as a typed value. A type assertion doesn't validate data.
15
+ - Use the known type for data the program made or already checked. Don't decode it again or make it `unknown`.
16
+
17
+ ## Observable
18
+
19
+ You can see what the program does and why it fails. Every failure has a name and goes to a caller. Risky access is visible and limited.
20
+
21
+ - Handle a forked effect's failure before the fork, or keep the fiber and join it.
22
+ - Wrap a Promise in `Effect.tryPromise` and `yield*` it instead of using `await`.
23
+ - Return a fixed value only for the one failure you expect, such as a file that isn't there. Let every other failure fail.
27
24
  - Name errors so they say what went wrong.
28
- - Keep code near the files that use it. Extract shared code when other files need it.
29
25
 
30
- ## Make program output clear
26
+ ### Make program output clear
31
27
 
32
28
  - Follow Git and uv's style. Say what failed, name the affected file or value and explain the cause.
33
29
  - Give the reader enough context to choose a fix.
@@ -36,6 +32,25 @@ Check may not catch every violation of these principles. Review your code agains
36
32
  - Preserve useful messages from underlying tools, including error codes and exact names.
37
33
  - Write short, full sentences. Use periods instead of semicolons between sentences.
38
34
 
39
- ## Prevent the same mistake
35
+ ## Predictable
36
+
37
+ The code has one shape. Values do not change after they are made. Names stay true when the code changes.
38
+
39
+ - Design for the current requirement as if you were starting fresh. Delete code the new design doesn't need.
40
+ - Use what Effect, Bun or a dependency already provides.
41
+ - Write each fact or decision once and derive the rest from it.
42
+ - Give each value a name that says what it holds.
43
+ - Keep code near the files that use it. Extract shared code when other files need it.
44
+ - Read a fact from where a tool states it, such as an error's fields, a command's exit code or its JSON output. Text written for people changes between releases, and code that searches it breaks quietly when it does.
45
+ - Write a job that moves through stages as an explicit state machine, with one tagged case per stage in one union, so the job is always in exactly one stage.
46
+
47
+ ## Decide if a rule is worth it
48
+
49
+ When the user corrects a mistake, consider a rule or a test that prevents it. A rule is worth building when all of these are true:
50
+
51
+ 1. It serves one of the three goals.
52
+ 2. It removes a way to be wrong and does not add one.
53
+ 3. One correct way stays.
54
+ 4. It catches a real problem. Run it on real projects to confirm.
40
55
 
41
- When the user corrects a mistake, consider adding a lint rule or test to prevent it, or changing an existing rule if it enforces the wrong requirement.
56
+ A change that loosens a rule adds a way. Make it only when the rule rejects code that already meets the goal.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sshkeda/check",
3
- "version": "4.3.0",
3
+ "version": "4.4.0",
4
4
  "homepage": "https://github.com/sshkeda/check#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/sshkeda/check/issues"
@@ -0,0 +1,273 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import type { ESTree, SourceCode, Variable } from "@oxlint/plugins";
3
+
4
+ import {
5
+ constantValue,
6
+ isAssignmentTarget,
7
+ isGlobalReference,
8
+ memberName,
9
+ propertyKeyName,
10
+ resolvedVariable,
11
+ staticKeyName,
12
+ unwrappedExpression,
13
+ } from "./resolve-what-an-expression-imports.ts";
14
+
15
+ const OBJECT = "Object";
16
+
17
+ const ERROR = "Error";
18
+
19
+ const REFLECT = "Reflect";
20
+
21
+ const PROTOTYPE = "prototype";
22
+
23
+ const PARENT_PROTOTYPE = "__proto__";
24
+
25
+ const OBJECT_ASSIGN = "Object.assign";
26
+
27
+ const REFLECT_SET = "Reflect.set";
28
+
29
+ const CONSTRUCTORS_UNDER_OBJECT = [
30
+ "Array",
31
+ "ArrayBuffer",
32
+ "BigInt",
33
+ "Boolean",
34
+ "AsyncDisposableStack",
35
+ "DataView",
36
+ "Date",
37
+ "DisposableStack",
38
+ "Error",
39
+ "FinalizationRegistry",
40
+ "Function",
41
+ "Iterator",
42
+ "Map",
43
+ "Number",
44
+ "Promise",
45
+ "RegExp",
46
+ "Set",
47
+ "SharedArrayBuffer",
48
+ "String",
49
+ "Symbol",
50
+ "WeakMap",
51
+ "WeakRef",
52
+ "WeakSet",
53
+ ] as const;
54
+
55
+ const ERROR_SUBCLASSES = [
56
+ "AggregateError",
57
+ "EvalError",
58
+ "RangeError",
59
+ "ReferenceError",
60
+ "SuppressedError",
61
+ "SyntaxError",
62
+ "TypeError",
63
+ "URIError",
64
+ ] as const;
65
+
66
+ const TYPED_ARRAYS = [
67
+ "BigInt64Array",
68
+ "BigUint64Array",
69
+ "Float16Array",
70
+ "Float32Array",
71
+ "Float64Array",
72
+ "Int16Array",
73
+ "Int32Array",
74
+ "Int8Array",
75
+ "Uint16Array",
76
+ "Uint32Array",
77
+ "Uint8Array",
78
+ "Uint8ClampedArray",
79
+ ] as const;
80
+
81
+ const PARENT_PROTOTYPES = new Map<string, string | undefined>([
82
+ [OBJECT, undefined],
83
+ ...CONSTRUCTORS_UNDER_OBJECT.map((name) => [name, OBJECT] as const),
84
+ ...ERROR_SUBCLASSES.map((name) => [name, ERROR] as const),
85
+ ...TYPED_ARRAYS.map((name) => [name, undefined] as const),
86
+ ]);
87
+
88
+ const GLOBAL_CONTAINERS: ReadonlySet<string> = new Set(["global", "globalThis", "self", "window"]);
89
+
90
+ const OBJECT_WRITES: ReadonlySet<string> = new Set([
91
+ "assign",
92
+ "defineProperties",
93
+ "defineProperty",
94
+ "setPrototypeOf",
95
+ ]);
96
+
97
+ const REFLECT_WRITES: ReadonlySet<string> = new Set([
98
+ "defineProperty",
99
+ "deleteProperty",
100
+ "set",
101
+ "setPrototypeOf",
102
+ ]);
103
+
104
+ const intrinsic = (
105
+ kind: "constructor" | "container" | "prototype" | "reflect" | "write",
106
+ name: string,
107
+ ) => ({ kind, name });
108
+
109
+ const globalIntrinsic = (name: string) => {
110
+ if (PARENT_PROTOTYPES.has(name)) {
111
+ return intrinsic("constructor", name);
112
+ }
113
+ if (name === REFLECT) {
114
+ return intrinsic("reflect", name);
115
+ }
116
+ return GLOBAL_CONTAINERS.has(name) ? intrinsic("container", name) : undefined;
117
+ };
118
+
119
+ const memberOfIntrinsic = (owner: ReturnType<typeof intrinsic> | undefined, key: string) => {
120
+ if (owner === undefined) {
121
+ return;
122
+ }
123
+ if (owner.kind === "container") {
124
+ return globalIntrinsic(key);
125
+ }
126
+ const isPrototypeOfConstructor = owner.kind === "constructor" && key === PROTOTYPE;
127
+ if (isPrototypeOfConstructor) {
128
+ return intrinsic("prototype", owner.name);
129
+ }
130
+ const isObjectWrite =
131
+ owner.kind === "constructor" && owner.name === OBJECT && OBJECT_WRITES.has(key);
132
+ const isReflectWrite = owner.kind === "reflect" && REFLECT_WRITES.has(key);
133
+ const isWrite = isObjectWrite || isReflectWrite;
134
+ if (isWrite) {
135
+ return intrinsic("write", `${owner.name}.${key}`);
136
+ }
137
+ const isParentOfPrototype = owner.kind === "prototype" && key === PARENT_PROTOTYPE;
138
+ const parent = isParentOfPrototype ? PARENT_PROTOTYPES.get(owner.name) : undefined;
139
+ return parent === undefined ? undefined : intrinsic("prototype", parent);
140
+ };
141
+
142
+ const staticMemberKey = (node: ESTree.MemberExpression, sourceCode: SourceCode) => {
143
+ const name = memberName(node);
144
+ const isUnresolvedComputedKey = name === undefined && node.computed;
145
+ return isUnresolvedComputedKey ? staticKeyName(constantValue(node.property, sourceCode)) : name;
146
+ };
147
+
148
+ const constantAlias = (node: ESTree.Node, sourceCode: SourceCode) => {
149
+ const variable = resolvedVariable(node, sourceCode);
150
+ const definitions = variable?.defs ?? [];
151
+ const [definition] = definitions;
152
+ const declarator = definitions.length === 1 ? definition?.node : undefined;
153
+ const isConstantDeclarator =
154
+ declarator?.type === "VariableDeclarator" &&
155
+ declarator.parent.type === "VariableDeclaration" &&
156
+ declarator.parent.kind === "const";
157
+ const value = isConstantDeclarator ? declarator.init : null;
158
+ const isConstantWithAValue =
159
+ variable !== undefined && definition !== undefined && isConstantDeclarator && value !== null;
160
+ if (!isConstantWithAValue) {
161
+ return;
162
+ }
163
+ if (declarator.id.type === "Identifier") {
164
+ return { variable, value, key: undefined };
165
+ }
166
+ const property = definition.name.parent;
167
+ const isDestructuredByKey =
168
+ property.type === "Property" &&
169
+ property.value === definition.name &&
170
+ property.parent === declarator.id;
171
+ const key = isDestructuredByKey ? propertyKeyName(property) : undefined;
172
+ return key === undefined ? undefined : { variable, value, key };
173
+ };
174
+
175
+ const intrinsicOf = (
176
+ expression: ESTree.Node,
177
+ sourceCode: SourceCode,
178
+ seen: ReadonlySet<Variable> = new Set(),
179
+ ): ReturnType<typeof intrinsic> | undefined => {
180
+ const node = unwrappedExpression(expression);
181
+ if (node.type === "ChainExpression") {
182
+ return intrinsicOf(node.expression, sourceCode, seen);
183
+ }
184
+ if (node.type === "MemberExpression") {
185
+ const key = staticMemberKey(node, sourceCode);
186
+ return key === undefined
187
+ ? undefined
188
+ : memberOfIntrinsic(intrinsicOf(node.object, sourceCode, seen), key);
189
+ }
190
+ if (node.type !== "Identifier") {
191
+ return;
192
+ }
193
+ if (isGlobalReference(node, sourceCode, node.name)) {
194
+ return globalIntrinsic(node.name);
195
+ }
196
+ const alias = constantAlias(node, sourceCode);
197
+ const isUnknownOrSeen = alias === undefined || seen.has(alias.variable);
198
+ if (isUnknownOrSeen) {
199
+ return;
200
+ }
201
+ const value = intrinsicOf(alias.value, sourceCode, new Set([...seen, alias.variable]));
202
+ return alias.key === undefined ? value : memberOfIntrinsic(value, alias.key);
203
+ };
204
+
205
+ const prototypeWrittenThrough = (target: ESTree.Node, sourceCode: SourceCode) => {
206
+ const node = unwrappedExpression(target);
207
+ if (node.type !== "MemberExpression") {
208
+ return;
209
+ }
210
+ const owner = intrinsicOf(node.object, sourceCode);
211
+ if (owner?.kind === "prototype") {
212
+ return owner.name;
213
+ }
214
+ const isPrototypeOfConstructor =
215
+ owner?.kind === "constructor" && staticMemberKey(node, sourceCode) === PROTOTYPE;
216
+ return isPrototypeOfConstructor ? owner.name : undefined;
217
+ };
218
+
219
+ const isChangedInPlace = (node: ESTree.MemberExpression) => {
220
+ const changed = node.parent.type === "ChainExpression" ? node.parent : node;
221
+ const { parent } = changed;
222
+ const isUpdated = parent.type === "UpdateExpression" && parent.argument === changed;
223
+ const isDeleted =
224
+ parent.type === "UnaryExpression" &&
225
+ parent.operator === "delete" &&
226
+ parent.argument === changed;
227
+ return isUpdated || isDeleted;
228
+ };
229
+
230
+ const targetOfWrite = (write: string, callArguments: readonly ESTree.Node[]) => {
231
+ const firstSpread = callArguments.findIndex((argument) => argument.type === "SpreadElement");
232
+ const hasSpread = firstSpread !== -1;
233
+ const argumentsBeforeSpread = hasSpread ? callArguments.slice(0, firstSpread) : callArguments;
234
+ const [target, , , receiver] = argumentsBeforeSpread;
235
+ if (write === REFLECT_SET) {
236
+ return hasSpread ? receiver : (receiver ?? target);
237
+ }
238
+ const isAssignWithoutSources = write === OBJECT_ASSIGN && callArguments.length === 1;
239
+ return isAssignWithoutSources ? undefined : target;
240
+ };
241
+
242
+ const prototypeWrittenByCall = (node: ESTree.CallExpression, sourceCode: SourceCode) => {
243
+ const callee = intrinsicOf(node.callee, sourceCode);
244
+ const target = callee?.kind === "write" ? targetOfWrite(callee.name, node.arguments) : undefined;
245
+ const written = target === undefined ? undefined : intrinsicOf(target, sourceCode);
246
+ return written?.kind === "prototype" ? written.name : undefined;
247
+ };
248
+
249
+ export const noNativePrototypeWrites = defineRule({
250
+ meta: {
251
+ type: "problem",
252
+ messages: {
253
+ nativePrototype: "the {{name}} prototype is changed",
254
+ },
255
+ },
256
+ create(context) {
257
+ return {
258
+ MemberExpression(node) {
259
+ const isWritten = isAssignmentTarget(node) || isChangedInPlace(node);
260
+ const name = isWritten ? prototypeWrittenThrough(node, context.sourceCode) : undefined;
261
+ if (name !== undefined) {
262
+ context.report({ node, messageId: "nativePrototype", data: { name } });
263
+ }
264
+ },
265
+ CallExpression(node) {
266
+ const name = prototypeWrittenByCall(node, context.sourceCode);
267
+ if (name !== undefined) {
268
+ context.report({ node, messageId: "nativePrototype", data: { name } });
269
+ }
270
+ },
271
+ };
272
+ },
273
+ });
@@ -61,6 +61,7 @@ import { noVagueErrorNames } from "./ban-vague-error-class-names.ts";
61
61
  import { noVagueFileNames } from "./ban-vague-file-names.ts";
62
62
  import { permissionBanRule } from "./ban-what-a-file-is-not-granted.ts";
63
63
  import { noWhile } from "./ban-while-do-while-and-for-loops.ts";
64
+ import { noNativePrototypeWrites } from "./ban-writes-to-native-prototypes.ts";
64
65
  import { noSharedHolders } from "./ban-writing-captured-objects-inside-effect-callbacks.ts";
65
66
  import { noNodeConsole } from "./confine-node-console-to-its-console-export.ts";
66
67
  import {
@@ -143,6 +144,7 @@ const NAMED_RULES = {
143
144
  [UNUSED_CODE_GRANTS_RULE]: noUnusedCodeGrants,
144
145
  "no-glob-scan": noGlobScan,
145
146
  "no-unknown-boundaries": noUnknownBoundaries,
147
+ "no-native-prototype-writes": noNativePrototypeWrites,
146
148
  "no-loose-literal-constants": noLooseLiteralConstants,
147
149
  "no-type-declarations": noTypeDeclarations,
148
150
  "no-declared-values": noDeclaredValues,
@@ -235,7 +237,6 @@ const baseConfig = {
235
237
  "eslint/no-else-return": "error",
236
238
  "eslint/no-empty": "error",
237
239
  "eslint/no-empty-function": ["error", { allow: ["privateConstructors"] }],
238
- "eslint/no-extend-native": "error",
239
240
  "eslint/no-implicit-coercion": "error",
240
241
  "eslint/no-lone-blocks": "error",
241
242
  "eslint/no-lonely-if": "error",
@@ -225,6 +225,15 @@ export class PackageEntryNotTypeScript extends Schema.TaggedError<PackageEntryNo
225
225
  }
226
226
  }
227
227
 
228
+ export class PackageExportPattern extends Schema.TaggedError<PackageExportPattern>()(
229
+ "PackageExportPattern",
230
+ { location: Schema.String, field: Schema.String, pattern: Schema.String },
231
+ ) {
232
+ public override get message() {
233
+ return `${this.field} contains package export pattern "${this.pattern}"`;
234
+ }
235
+ }
236
+
228
237
  export class RepositoryRootNotFound extends Schema.TaggedError<RepositoryRootNotFound>()(
229
238
  "RepositoryRootNotFound",
230
239
  { directory: Schema.String, reason: Schema.String },
@@ -400,6 +409,7 @@ export class FileLayoutViolations extends Schema.TaggedError<FileLayoutViolation
400
409
  DependencyOutsideRepository,
401
410
  ExportPathMismatch,
402
411
  PackageEntryNotTypeScript,
412
+ PackageExportPattern,
403
413
  UngrantedDocument,
404
414
  UngrantedDirectory,
405
415
  DirectoryGrantOnFile,
@@ -6,6 +6,7 @@ import {
6
6
  ExportPathMismatch,
7
7
  moduleDirectoryNamedBy,
8
8
  PackageEntryNotTypeScript,
9
+ PackageExportPattern,
9
10
  } from "./file-layout-errors.ts";
10
11
 
11
12
  const ROOT_SUBPATH = ".";
@@ -16,6 +17,7 @@ const CODE_FILE = /\.[cm]?[jt]sx?$/u;
16
17
  const FILE_EXTENSION = /\.[^./]+$/u;
17
18
  const INDEX_FILE = /^index\.tsx?$/u;
18
19
  const PACKAGE_PATTERN_WILDCARD = "*";
20
+ const DIRECTORY_MAPPING_END = "/";
19
21
  const ENTRY_FIELDS = ["main", "module", "types", "typings"] as const;
20
22
  const PROPERTY_NAME = /^[A-Za-z_$][\w$]*$/u;
21
23
  const isJsonObject = Schema.is(JSON_OBJECT);
@@ -42,6 +44,12 @@ const targetsUnderEveryCondition = (
42
44
  );
43
45
  };
44
46
 
47
+ const isPackageExportPattern = (path: string) =>
48
+ path.includes(PACKAGE_PATTERN_WILDCARD) || path.endsWith(DIRECTORY_MAPPING_END);
49
+
50
+ const isPackageExportPatternTarget = (target: string) =>
51
+ isPackageExportPattern(target.replace(QUERY_OR_FRAGMENT, ""));
52
+
45
53
  const subpathsWithTheirFields = (exports: Schema.Json) => {
46
54
  const isSubpathMap =
47
55
  isJsonObject(exports) && Object.keys(exports).some((key) => key.startsWith(ROOT_SUBPATH));
@@ -50,8 +58,39 @@ const subpathsWithTheirFields = (exports: Schema.Json) => {
50
58
  subpath,
51
59
  field: fieldWithKey("exports", subpath),
52
60
  value,
61
+ isPatternKey: isPackageExportPattern(subpath),
53
62
  }))
54
- : [{ subpath: ROOT_SUBPATH, field: "exports", value: exports }];
63
+ : [{ subpath: ROOT_SUBPATH, field: "exports", value: exports, isPatternKey: false }];
64
+ };
65
+
66
+ const namedExportTargets = (exports: Schema.Json) =>
67
+ subpathsWithTheirFields(exports).flatMap(({ subpath, field, value, isPatternKey }) =>
68
+ isPatternKey
69
+ ? []
70
+ : targetsUnderEveryCondition(field, value)
71
+ .filter(({ target }) => !isPackageExportPatternTarget(target))
72
+ .map(({ field: targetField, target }) => ({ subpath, field: targetField, target })),
73
+ );
74
+
75
+ export const packageExportPatterns = (path: string, manifest: typeof JSON_OBJECT.Type) => {
76
+ const exports = manifest["exports"];
77
+ if (exports === undefined) {
78
+ return [];
79
+ }
80
+ return subpathsWithTheirFields(exports).flatMap(({ subpath, field, value, isPatternKey }) => {
81
+ const targets = targetsUnderEveryCondition(field, value);
82
+ if (isPatternKey) {
83
+ return targets.length > 0
84
+ ? [new PackageExportPattern({ location: path, field, pattern: subpath })]
85
+ : [];
86
+ }
87
+ return targets
88
+ .filter(({ target }) => isPackageExportPatternTarget(target))
89
+ .map(
90
+ ({ field: targetField, target }) =>
91
+ new PackageExportPattern({ location: path, field: targetField, pattern: target }),
92
+ );
93
+ });
55
94
  };
56
95
 
57
96
  const isIndexOfTheDirectoryTheSubpathNames = (subpath: string, target: string) => {
@@ -76,18 +115,16 @@ export const exportPathMismatches = (path: string, manifest: typeof JSON_OBJECT.
76
115
  if (exports === undefined) {
77
116
  return [];
78
117
  }
79
- return subpathsWithTheirFields(exports).flatMap(({ subpath, field, value }) =>
80
- targetsUnderEveryCondition(field, value)
81
- .filter(
82
- ({ target }) =>
83
- isTypeScriptSourceFile(target.replace(QUERY_OR_FRAGMENT, "")) &&
84
- !isIndexOfTheDirectoryTheSubpathNames(subpath, target),
85
- )
86
- .map(
87
- ({ field: conditionField, target }) =>
88
- new ExportPathMismatch({ location: path, field: conditionField, target, subpath }),
89
- ),
90
- );
118
+ return namedExportTargets(exports)
119
+ .filter(
120
+ ({ subpath, target }) =>
121
+ isTypeScriptSourceFile(target.replace(QUERY_OR_FRAGMENT, "")) &&
122
+ !isIndexOfTheDirectoryTheSubpathNames(subpath, target),
123
+ )
124
+ .map(
125
+ ({ subpath, field, target }) =>
126
+ new ExportPathMismatch({ location: path, field, target, subpath }),
127
+ );
91
128
  };
92
129
 
93
130
  const isCodeOtherThanTypeScriptSource = (target: string) => {
@@ -104,11 +141,7 @@ export const packageEntriesNotTypeScript = (path: string, manifest: typeof JSON_
104
141
  const target = manifest[field];
105
142
  return typeof target === "string" ? [{ field, target }] : [];
106
143
  }),
107
- ...(exports === undefined
108
- ? []
109
- : subpathsWithTheirFields(exports).flatMap(({ field, value }) =>
110
- targetsUnderEveryCondition(field, value),
111
- )),
144
+ ...(exports === undefined ? [] : namedExportTargets(exports)),
112
145
  ]
113
146
  .filter(({ target }) => isCodeOtherThanTypeScriptSource(target))
114
147
  .map(({ field, target }) => new PackageEntryNotTypeScript({ location: path, field, target }));
@@ -96,6 +96,7 @@ import {
96
96
  import {
97
97
  exportPathMismatches,
98
98
  packageEntriesNotTypeScript,
99
+ packageExportPatterns,
99
100
  } from "./find-export-path-mismatches.ts";
100
101
  import {
101
102
  directoriesOutsideModuleLayoutAmong,
@@ -459,6 +460,7 @@ export const manifestViolations = (
459
460
  ...(yield* dependenciesOutsideRepository(path, manifest.success, repository)),
460
461
  ...packageEntriesNotTypeScript(path, manifest.success),
461
462
  ...exportPathMismatches(path, manifest.success),
463
+ ...packageExportPatterns(path, manifest.success),
462
464
  ];
463
465
  });
464
466