@jupyter/eslint-plugin 1.1.0 → 1.3.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.
Files changed (40) hide show
  1. package/lib/index.d.ts +49 -2
  2. package/lib/index.js +35 -5
  3. package/lib/rules/galata-prefer-context-menu-helper.d.ts +6 -0
  4. package/lib/rules/galata-prefer-context-menu-helper.js +394 -0
  5. package/lib/rules/galata-prefer-menu-helper.d.ts +6 -0
  6. package/lib/rules/galata-prefer-menu-helper.js +394 -0
  7. package/lib/rules/galata-prefer-notebook-cell-helper.d.ts +6 -0
  8. package/lib/rules/galata-prefer-notebook-cell-helper.js +403 -0
  9. package/lib/rules/galata-prefer-sidebar-activity-helper.d.ts +6 -0
  10. package/lib/rules/galata-prefer-sidebar-activity-helper.js +332 -0
  11. package/lib/rules/no-schema-enum.d.ts +1 -1
  12. package/lib/rules/no-schema-enum.js +54 -2
  13. package/lib/rules/no-untranslated-string.d.ts +2 -1
  14. package/lib/rules/no-untranslated-string.js +191 -113
  15. package/lib/rules/plugin-id-convention.d.ts +7 -0
  16. package/lib/rules/plugin-id-convention.js +296 -0
  17. package/lib/rules/prefer-lazy-imports.d.ts +6 -0
  18. package/lib/rules/prefer-lazy-imports.js +476 -0
  19. package/lib/rules/require-disposable-ownership.js +1 -16
  20. package/lib/rules/require-disposable-transfer.js +7 -2
  21. package/lib/utils/ast.d.ts +12 -0
  22. package/lib/utils/ast.js +49 -0
  23. package/lib/utils/disposables.d.ts +12 -0
  24. package/lib/utils/disposables.js +101 -10
  25. package/lib/utils/lazy-imports.d.ts +93 -0
  26. package/lib/utils/lazy-imports.js +600 -0
  27. package/lib/utils/module-size.d.ts +18 -0
  28. package/lib/utils/module-size.js +249 -0
  29. package/lib/utils/package-json.d.ts +8 -0
  30. package/lib/utils/package-json.js +76 -0
  31. package/lib/utils/playwright-selectors.d.ts +56 -5
  32. package/lib/utils/playwright-selectors.js +205 -12
  33. package/lib/utils/plugin-utils.d.ts +50 -2
  34. package/lib/utils/plugin-utils.js +221 -38
  35. package/lib/utils/shared-packages.d.ts +9 -0
  36. package/lib/utils/shared-packages.js +128 -0
  37. package/lib/utils/signal-lifetime.js +66 -5
  38. package/lib/utils/signals.d.ts +2 -8
  39. package/lib/utils/signals.js +7 -42
  40. package/package.json +1 -1
@@ -0,0 +1,249 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) Jupyter Development Team.
4
+ * Distributed under the terms of the Modified BSD License.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.resolveRelativeModule = resolveRelativeModule;
41
+ exports.getTransitiveCodeSize = getTransitiveCodeSize;
42
+ const fs = __importStar(require("fs"));
43
+ const path = __importStar(require("path"));
44
+ const ts = __importStar(require("typescript"));
45
+ const lazy_imports_1 = require("./lazy-imports");
46
+ const CODE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
47
+ /** Suffixes an ESM specifier may carry which the source file does not. */
48
+ const OUTPUT_TO_SOURCE = {
49
+ '.js': ['.ts', '.tsx', '.js', '.jsx'],
50
+ '.mjs': ['.mts', '.mjs'],
51
+ '.cjs': ['.cts', '.cjs']
52
+ };
53
+ /** Stops a pathological import graph from dominating lint time. */
54
+ const MAX_FILES = 300;
55
+ const MAX_DEPTH = 12;
56
+ const fileCache = new Map();
57
+ /**
58
+ * Resolves a relative import specifier to a file, trying the usual extensions
59
+ * and an `index` file inside a directory. A specifier written for ESM output,
60
+ * such as `./widget.js`, also resolves to the source it was compiled from.
61
+ * Returns null for a bare package specifier, or when nothing matches.
62
+ */
63
+ function resolveRelativeModule(specifier, fromFile) {
64
+ if (!specifier.startsWith('.')) {
65
+ return null;
66
+ }
67
+ const base = path.resolve(path.dirname(fromFile), specifier);
68
+ const outputExtension = path.extname(base);
69
+ const sourceExtensions = OUTPUT_TO_SOURCE[outputExtension];
70
+ if (sourceExtensions) {
71
+ const withoutExtension = base.slice(0, -outputExtension.length);
72
+ for (const extension of sourceExtensions) {
73
+ const candidate = withoutExtension + extension;
74
+ if (isFile(candidate)) {
75
+ return candidate;
76
+ }
77
+ }
78
+ }
79
+ const candidates = [
80
+ ...CODE_EXTENSIONS.map(extension => base + extension),
81
+ ...CODE_EXTENSIONS.map(extension => path.join(base, `index${extension}`))
82
+ ];
83
+ for (const candidate of candidates) {
84
+ if (isFile(candidate)) {
85
+ return candidate;
86
+ }
87
+ }
88
+ return isFile(base) ? base : null;
89
+ }
90
+ function isFile(candidate) {
91
+ try {
92
+ return fs.statSync(candidate).isFile();
93
+ }
94
+ catch {
95
+ return false;
96
+ }
97
+ }
98
+ /**
99
+ * Compiles a module and returns the bytes it contributes to a bundle. Comments
100
+ * and everything TypeScript erases are gone from the result, so a file of
101
+ * interface declarations measures near zero.
102
+ */
103
+ function compiledSize(filePath, source) {
104
+ const isTsx = filePath.endsWith('.tsx') || filePath.endsWith('.jsx');
105
+ let emitted;
106
+ try {
107
+ emitted = ts.transpileModule(source, {
108
+ fileName: filePath,
109
+ reportDiagnostics: false,
110
+ compilerOptions: {
111
+ target: ts.ScriptTarget.ES2020,
112
+ module: ts.ModuleKind.ESNext,
113
+ removeComments: true,
114
+ isolatedModules: true,
115
+ jsx: isTsx ? ts.JsxEmit.Preserve : undefined
116
+ }
117
+ }).outputText;
118
+ }
119
+ catch {
120
+ emitted = source;
121
+ }
122
+ return Buffer.byteLength(emitted.replace(/\s+/g, ' ').trim(), 'utf8');
123
+ }
124
+ /**
125
+ * Collects the relative modules a file imports at run time. Type-only imports
126
+ * are skipped because TypeScript erases them, and so are dynamic imports,
127
+ * which are deferred already.
128
+ */
129
+ function collectDependencies(filePath, source) {
130
+ const dependencies = [];
131
+ let sourceFile;
132
+ try {
133
+ sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.ES2020, false);
134
+ }
135
+ catch {
136
+ return dependencies;
137
+ }
138
+ for (const statement of sourceFile.statements) {
139
+ let specifier;
140
+ if (ts.isImportDeclaration(statement)) {
141
+ if (statement.importClause?.isTypeOnly) {
142
+ continue;
143
+ }
144
+ specifier = statement.moduleSpecifier;
145
+ }
146
+ else if (ts.isExportDeclaration(statement)) {
147
+ if (statement.isTypeOnly) {
148
+ continue;
149
+ }
150
+ specifier = statement.moduleSpecifier;
151
+ }
152
+ if (!specifier || !ts.isStringLiteral(specifier)) {
153
+ continue;
154
+ }
155
+ if ((0, lazy_imports_1.matchesPatterns)(specifier.text, lazy_imports_1.ALWAYS_IGNORED_IMPORTS)) {
156
+ // An asset the bundler turns into a URL adds nothing to the bundle.
157
+ continue;
158
+ }
159
+ const resolved = resolveRelativeModule(specifier.text, filePath);
160
+ if (resolved) {
161
+ dependencies.push(resolved);
162
+ }
163
+ }
164
+ return dependencies;
165
+ }
166
+ /**
167
+ * Reads a file and records the size of its code and the relative modules it
168
+ * imports. Cached until the file changes on disk.
169
+ */
170
+ function readFileInfo(filePath) {
171
+ let stats;
172
+ try {
173
+ stats = fs.statSync(filePath);
174
+ }
175
+ catch {
176
+ return null;
177
+ }
178
+ const mtimeMs = stats.mtimeMs;
179
+ const cached = fileCache.get(filePath);
180
+ if (cached && cached.mtimeMs === mtimeMs) {
181
+ return cached;
182
+ }
183
+ // An asset inlined into the bundle, such as an SVG or a raw stylesheet,
184
+ // contributes its bytes as they are and imports nothing.
185
+ if (!CODE_EXTENSIONS.includes(path.extname(filePath))) {
186
+ const info = { mtimeMs, size: stats.size, dependencies: [] };
187
+ fileCache.set(filePath, info);
188
+ return info;
189
+ }
190
+ let source;
191
+ try {
192
+ source = fs.readFileSync(filePath, 'utf8');
193
+ }
194
+ catch {
195
+ fileCache.set(filePath, null);
196
+ return null;
197
+ }
198
+ const info = {
199
+ mtimeMs,
200
+ size: compiledSize(filePath, source),
201
+ dependencies: collectDependencies(filePath, source)
202
+ };
203
+ fileCache.set(filePath, info);
204
+ return info;
205
+ }
206
+ /**
207
+ * Sums the code size of a module and of every relative module it statically
208
+ * imports. Returns null when the file cannot be read.
209
+ *
210
+ * Callers which only compare the total against a threshold can pass it as
211
+ * `budget`. The walk then stops as soon as the running total reaches it and
212
+ * returns that partial sum, because a module already over the threshold stays
213
+ * over it however much more its imports hold. The files behind the threshold
214
+ * are never read.
215
+ */
216
+ function getTransitiveCodeSize(entry, budget = Number.POSITIVE_INFINITY) {
217
+ const root = readFileInfo(entry);
218
+ if (!root) {
219
+ return null;
220
+ }
221
+ const seen = new Set([entry]);
222
+ const queue = [
223
+ { file: entry, depth: 0 }
224
+ ];
225
+ let total = 0;
226
+ while (queue.length > 0) {
227
+ const { file, depth } = queue.shift();
228
+ const info = readFileInfo(file);
229
+ if (!info) {
230
+ // The size is unknown rather than small, and a module which cannot be
231
+ // measured is reported rather than filtered out.
232
+ return null;
233
+ }
234
+ total += info.size;
235
+ if (total >= budget) {
236
+ return total;
237
+ }
238
+ if (depth >= MAX_DEPTH || seen.size >= MAX_FILES) {
239
+ continue;
240
+ }
241
+ for (const dependency of info.dependencies) {
242
+ if (!seen.has(dependency)) {
243
+ seen.add(dependency);
244
+ queue.push({ file: dependency, depth: depth + 1 });
245
+ }
246
+ }
247
+ }
248
+ return total;
249
+ }
@@ -0,0 +1,8 @@
1
+ export interface PackageJsonFile {
2
+ mtimeMs: number;
3
+ data: Record<string, unknown>;
4
+ }
5
+ /**
6
+ * Reads and caches a package.json file until its mtime changes.
7
+ */
8
+ export declare function readPackageJson(packagePath: string): PackageJsonFile | null;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) Jupyter Development Team.
4
+ * Distributed under the terms of the Modified BSD License.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.readPackageJson = readPackageJson;
41
+ const fs = __importStar(require("fs"));
42
+ const packageJsonCache = new Map();
43
+ /**
44
+ * Reads and caches a package.json file until its mtime changes.
45
+ */
46
+ function readPackageJson(packagePath) {
47
+ let mtimeMs;
48
+ try {
49
+ mtimeMs = fs.statSync(packagePath).mtimeMs;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ const cached = packageJsonCache.get(packagePath);
55
+ if (cached?.mtimeMs === mtimeMs) {
56
+ return cached.data === null ? null : cached;
57
+ }
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
61
+ }
62
+ catch {
63
+ packageJsonCache.set(packagePath, { mtimeMs, data: null });
64
+ return null;
65
+ }
66
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
67
+ packageJsonCache.set(packagePath, { mtimeMs, data: null });
68
+ return null;
69
+ }
70
+ const info = {
71
+ mtimeMs,
72
+ data: parsed
73
+ };
74
+ packageJsonCache.set(packagePath, info);
75
+ return info;
76
+ }
@@ -1,4 +1,4 @@
1
- import { TSESTree } from '@typescript-eslint/utils';
1
+ import { TSESLint, TSESTree } from '@typescript-eslint/utils';
2
2
  /**
3
3
  * Playwright locator-producing methods.
4
4
  */
@@ -17,6 +17,11 @@ export interface SelectorPart {
17
17
  method: string;
18
18
  /** The selector or text argument. */
19
19
  argNode: TSESTree.Expression;
20
+ /**
21
+ * For `getByRole(role, { name })`, the accessible-name option. `argNode`
22
+ * holds the role. Undefined for every other locator method.
23
+ */
24
+ nameArgNode?: TSESTree.Expression;
20
25
  }
21
26
  export interface SelectorInteractionMatch {
22
27
  /** The outer CallExpression performing the interaction (report anchor). */
@@ -33,6 +38,29 @@ export interface SelectorInteractionMatch {
33
38
  /** true when the call passes `{ button: 'right' }` (context menu open). */
34
39
  isRightClick: boolean;
35
40
  }
41
+ export interface StaticSelectorTextOptions {
42
+ /** Whether to combine static pieces of interpolated template selectors. */
43
+ allowPartialTemplate?: boolean;
44
+ }
45
+ /**
46
+ * Resolves an identifier holding a locator to the expression it was assigned,
47
+ * or returns null when the binding must not be followed. Passed in by a rule
48
+ * that has a scope to look the name up in.
49
+ */
50
+ export type LocatorBindingResolver = (node: TSESTree.Identifier) => TSESTree.Node | null;
51
+ /**
52
+ * The expression a locator-holding identifier was assigned, or null when the
53
+ * binding must not be followed. A locator held in a variable then reaches the
54
+ * same `page` root as the inline chain.
55
+ *
56
+ * Only a `const` declared with an initializer is followed. `const` is what
57
+ * makes the assignment the single write, so the expression read here is the
58
+ * one the gesture acts on; a `let` could hold a different locator by then.
59
+ *
60
+ * This is the resolver a rule normally passes as the `resolveBinding`
61
+ * argument of {@link matchSelectorInteraction}.
62
+ */
63
+ export declare function resolveLocatorBinding(node: TSESTree.Identifier, scope: TSESLint.Scope.Scope): TSESTree.Node | null;
36
64
  /**
37
65
  * True when an interaction call passes `{ button: 'right' }` option.
38
66
  */
@@ -46,21 +74,44 @@ export declare function isRightClick(node: TSESTree.CallExpression): boolean;
46
74
  * `page.locator('#filebrowser').getByText('notebooks').dblclick()`
47
75
  *
48
76
  * Returns null for any other shape
77
+ *
78
+ * `resolveBinding` is optional. Without it a chain has to be written inline
79
+ * from `page`; with it a locator held in a variable is followed to its
80
+ * assignment first.
49
81
  */
50
- export declare function matchSelectorInteraction(node: TSESTree.CallExpression): SelectorInteractionMatch | null;
82
+ export declare function matchSelectorInteraction(node: TSESTree.CallExpression, resolveBinding?: LocatorBindingResolver): SelectorInteractionMatch | null;
51
83
  /**
52
84
  * Extracts a best-effort static string from a selector argument so it can be
53
85
  * matched against known patterns. String literals return their value;
54
86
  * template literals return their static parts joined by a space, so
55
87
  * `` `.jp-DirListing-item span:has-text("${name}")` `` still exposes its
56
- * static prefix. Fully dynamic expressions return null.
88
+ * static prefix. Pass `allowPartialTemplate: false` when interpolated
89
+ * templates should be treated as dynamic. Fully dynamic expressions return
90
+ * null.
57
91
  */
58
- export declare function extractStaticSelectorText(node: TSESTree.Expression): string | null;
92
+ export declare function extractStaticSelectorText(node: TSESTree.Expression, options?: StaticSelectorTextOptions): string | null;
59
93
  /**
60
94
  * Joins the statically extractable selector parts of a match into a single
61
95
  * pattern-matchable string. Arguments of text-matching locators (`getByText`,
62
96
  * `getByTitle`, …) are normalized to the `text=` selector form, so patterns
63
97
  * written against `text=` selectors also match the locator-method shape.
64
- * Returns null when no part is static.
98
+ * `getByRole(role, { name })` is normalized to the CSS-attribute form
99
+ * `[role="<role>"] text=<name>` for the same reason. Returns null when no part
100
+ * is static.
65
101
  */
66
102
  export declare function combineStaticSelectorText(match: SelectorInteractionMatch): string | null;
103
+ /**
104
+ * Whether `node` bounds the statements a rule may read as "what ran before".
105
+ *
106
+ * A rule that reasons about UI state — which menu is open, what was selected —
107
+ * reads the statements preceding a gesture. That reading has to stop somewhere,
108
+ * and the boundary is the unit that runs as one: a test callback or a named
109
+ * function.
110
+ */
111
+ export declare function isTestScopeBoundary(node: TSESTree.Node): boolean;
112
+ /**
113
+ * The innermost test callback or named function containing `node`, which is
114
+ * where a lookback over preceding statements has to stop. Falls back to the
115
+ * `Program` for a gesture written at the top level of a file.
116
+ */
117
+ export declare function enclosingTestScope(node: TSESTree.Node): TSESTree.Node;