@jupyter/eslint-plugin 1.1.0 → 1.2.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.
@@ -0,0 +1,308 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) Jupyter Development Team.
4
+ * Distributed under the terms of the Modified BSD License.
5
+ */
6
+ const utils_1 = require("@typescript-eslint/utils");
7
+ const plugin_utils_1 = require("../utils/plugin-utils");
8
+ const lazy_imports_1 = require("../utils/lazy-imports");
9
+ const module_size_1 = require("../utils/module-size");
10
+ const shared_packages_1 = require("../utils/shared-packages");
11
+ const create_rule_1 = require("../utils/create-rule");
12
+ const DEFAULT_OPTIONS = {
13
+ allowedPackages: lazy_imports_1.DEFAULT_ALLOWED_PACKAGES,
14
+ ignoreImports: [],
15
+ minimumSize: lazy_imports_1.DEFAULT_MINIMUM_SIZE,
16
+ reportInteractionCallbacks: false,
17
+ reportModuleLevelUsage: false
18
+ };
19
+ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
20
+ name: 'prefer-lazy-imports',
21
+ meta: {
22
+ type: 'suggestion',
23
+ docs: {
24
+ description: 'Prefer deferred imports for heavy dependencies of JupyterLab plugins',
25
+ url: 'https://eslint-plugin.readthedocs.io/en/latest/rules/prefer-lazy-imports/'
26
+ },
27
+ messages: {
28
+ preferLazyImport: "'{{ source }}' is imported at the top of a plugin module but only used inside functions, so it loads before the application starts. " +
29
+ 'Import it where it is used instead: `{{ snippet }}`',
30
+ eagerModuleLevelUse: "'{{ source }}' is used at module level in a plugin module, so it loads before the application starts. " +
31
+ "Move the usage into a function and import it there with `await import('{{ source }}')`.",
32
+ preferLazyImportInteraction: "'{{ source }}' is only used inside user-interaction handlers, so it is not needed until the user acts. " +
33
+ 'Import it where it is used instead: `{{ snippet }}`'
34
+ },
35
+ schema: [
36
+ {
37
+ type: 'object',
38
+ properties: {
39
+ allowedPackages: {
40
+ type: 'array',
41
+ items: { type: 'string' },
42
+ default: lazy_imports_1.DEFAULT_ALLOWED_PACKAGES,
43
+ description: 'Packages already loaded eagerly by the application, which are therefore free to import at the top of a plugin module. Supports `*` wildcards, and `!` to deny a package whatever else in the list matches it. Replaces the default list.'
44
+ },
45
+ ignoreImports: {
46
+ type: 'array',
47
+ items: { type: 'string' },
48
+ default: [],
49
+ description: 'Import specifiers to skip, matched the same way as `allowedPackages`: `*` wildcards, `!` to deny a specifier whatever else in the list matches it, and a bare specifier tested both as written and against its owning package. For example `./tokens` or `*.css`.'
50
+ },
51
+ minimumSize: {
52
+ type: 'number',
53
+ minimum: 0,
54
+ default: lazy_imports_1.DEFAULT_MINIMUM_SIZE,
55
+ description: 'Smallest module worth deferring, in bytes of code once comments and type declarations are removed, counted over the module and everything it statically imports by relative path. Set to 0 to report every module regardless of size.'
56
+ },
57
+ reportInteractionCallbacks: {
58
+ type: 'boolean',
59
+ default: false,
60
+ description: 'Also check modules which do not define a plugin, reporting an import there when every use sits inside a user-interaction handler: a command `execute` implementation, a listener for an interaction event such as `click`, or a JSX handler prop such as `onClick`.'
61
+ },
62
+ reportModuleLevelUsage: {
63
+ type: 'boolean',
64
+ default: false,
65
+ description: 'Also report imports used at module level, excluding tokens referenced in `requires`, `optional` and `provides`.'
66
+ }
67
+ },
68
+ additionalProperties: false
69
+ }
70
+ ]
71
+ },
72
+ defaultOptions: [DEFAULT_OPTIONS],
73
+ create(context, [options]) {
74
+ const { allowedPackages, ignoreImports, minimumSize, reportInteractionCallbacks, reportModuleLevelUsage } = options;
75
+ let services = null;
76
+ let checker = null;
77
+ try {
78
+ services = utils_1.ESLintUtils.getParserServices(context, true);
79
+ checker = services.program ? services.program.getTypeChecker() : null;
80
+ }
81
+ catch {
82
+ // Parser services unavailable (non-TS file or no type information)
83
+ services = null;
84
+ }
85
+ const getTSNode = services
86
+ ? (node) => services?.esTreeNodeToTSNodeMap.get(node)
87
+ : null;
88
+ let isPluginModule = false;
89
+ const importDeclarations = [];
90
+ // Sources kept in the startup bundle by a value re-export.
91
+ const reExportedSources = new Set();
92
+ function mentionsPluginType(typeNode) {
93
+ return (0, plugin_utils_1.typeMentionsJupyterPlugin)(typeNode, checker, getTSNode);
94
+ }
95
+ // Packages this extension declares as provided by the application, read
96
+ // from `jupyterlab.sharedPackages` in its own manifest. They extend
97
+ // `allowedPackages` rather than replacing it, and are only looked up once
98
+ // the file turns out to need checking.
99
+ let hostProvided = null;
100
+ /**
101
+ * Returns true when the specifier is exempt from the rule, either because
102
+ * the application loads it eagerly anyway or because it was ignored
103
+ * explicitly.
104
+ */
105
+ function isExempt(source) {
106
+ return ((0, lazy_imports_1.matchesPatterns)(source, lazy_imports_1.ALWAYS_IGNORED_IMPORTS) ||
107
+ (0, lazy_imports_1.matchesPatterns)(source, allowedPackages) ||
108
+ (0, lazy_imports_1.matchesPatterns)(source, hostProvided ?? []) ||
109
+ (0, lazy_imports_1.matchesPatterns)(source, ignoreImports));
110
+ }
111
+ /**
112
+ * Returns true when the module holds too little code for a separate chunk
113
+ * to pay off. Only relative imports can be measured; a package which is not
114
+ * in the shared runtime is bundled into the extension, so it always counts
115
+ * as worth deferring. An unreadable module counts as worth deferring too,
116
+ * so a missing file never hides a finding.
117
+ */
118
+ function isTooSmall(source) {
119
+ if (minimumSize <= 0) {
120
+ return false;
121
+ }
122
+ const resolved = (0, module_size_1.resolveRelativeModule)(source, context.filename);
123
+ if (!resolved) {
124
+ return false;
125
+ }
126
+ const size = (0, module_size_1.getTransitiveCodeSize)(resolved);
127
+ return size !== null && size < minimumSize;
128
+ }
129
+ /**
130
+ * Returns true when an identifier sits inside `typeof X`, which TypeScript
131
+ * erases even though the scope manager records it as a value reference.
132
+ */
133
+ function isInTypeQuery(node) {
134
+ let current = node;
135
+ while (current && current.type !== 'Program') {
136
+ if (current.type === 'TSTypeQuery') {
137
+ return true;
138
+ }
139
+ current = current.parent;
140
+ }
141
+ return false;
142
+ }
143
+ /**
144
+ * Collects the value references of every runtime binding of an import
145
+ * declaration. Type-only specifiers and type positions are left out
146
+ * because TypeScript erases them.
147
+ */
148
+ function getValueReferences(declaration) {
149
+ const references = [];
150
+ for (const specifier of declaration.specifiers) {
151
+ if (specifier.type === 'ImportSpecifier' &&
152
+ specifier.importKind === 'type') {
153
+ continue;
154
+ }
155
+ for (const variable of context.sourceCode.getDeclaredVariables(specifier)) {
156
+ for (const reference of variable.references) {
157
+ // `isValueReference` comes from the typescript-eslint scope
158
+ // manager. Under the default parser there are no type references,
159
+ // so every reference is a value reference.
160
+ const isValue = reference.isValueReference ?? true;
161
+ if (isValue && !isInTypeQuery(reference.identifier)) {
162
+ references.push(reference);
163
+ }
164
+ }
165
+ }
166
+ }
167
+ return references;
168
+ }
169
+ /**
170
+ * Checks every declaration importing one source together. A source pulled
171
+ * in eagerly by any one of them is already in the startup bundle, so
172
+ * deferring the others would not remove it.
173
+ */
174
+ function checkSource(source, declarations) {
175
+ if (isExempt(source) || reExportedSources.has(source)) {
176
+ return;
177
+ }
178
+ const references = declarations.flatMap(getValueReferences);
179
+ if (references.length === 0) {
180
+ // Unused, or used only in type positions which TypeScript erases.
181
+ return;
182
+ }
183
+ if (isTooSmall(source)) {
184
+ return;
185
+ }
186
+ if (!isPluginModule) {
187
+ // Outside a plugin module an ordinary function proves nothing, since
188
+ // it may run while the application starts. Only a position which
189
+ // provably waits for the user shows the import can load later.
190
+ if (references.every(({ identifier }) => (0, lazy_imports_1.isInInteractionCallback)(identifier))) {
191
+ context.report({
192
+ node: declarations[0],
193
+ messageId: 'preferLazyImportInteraction',
194
+ data: {
195
+ source,
196
+ snippet: (0, lazy_imports_1.buildDeferredImportSnippet)(declarations)
197
+ }
198
+ });
199
+ }
200
+ return;
201
+ }
202
+ let deferrable = 0;
203
+ let eager = 0;
204
+ let tokenList = 0;
205
+ for (const { identifier } of references) {
206
+ if ((0, lazy_imports_1.isInPluginTokenList)(identifier)) {
207
+ // A token in `requires`, `optional` or `provides` is read when the
208
+ // plugin is registered, so it can never be deferred.
209
+ tokenList += 1;
210
+ }
211
+ else if ((0, lazy_imports_1.isEagerlyReached)(identifier, context.sourceCode)) {
212
+ eager += 1;
213
+ }
214
+ else {
215
+ deferrable += 1;
216
+ }
217
+ }
218
+ if (tokenList === 0 && eager === 0 && deferrable > 0) {
219
+ context.report({
220
+ node: declarations[0],
221
+ messageId: 'preferLazyImport',
222
+ data: {
223
+ source,
224
+ snippet: (0, lazy_imports_1.buildDeferredImportSnippet)(declarations)
225
+ }
226
+ });
227
+ return;
228
+ }
229
+ if (reportModuleLevelUsage && eager > 0 && tokenList === 0) {
230
+ context.report({
231
+ node: declarations[0],
232
+ messageId: 'eagerModuleLevelUse',
233
+ data: { source }
234
+ });
235
+ }
236
+ }
237
+ return {
238
+ VariableDeclarator(node) {
239
+ if (!isPluginModule &&
240
+ node.id.type === 'Identifier' &&
241
+ mentionsPluginType(node.id.typeAnnotation?.typeAnnotation)) {
242
+ isPluginModule = true;
243
+ }
244
+ },
245
+ 'TSAsExpression, TSSatisfiesExpression'(node) {
246
+ if (!isPluginModule && mentionsPluginType(node.typeAnnotation)) {
247
+ isPluginModule = true;
248
+ }
249
+ },
250
+ 'FunctionDeclaration, FunctionExpression, ArrowFunctionExpression'(node) {
251
+ if (!isPluginModule &&
252
+ mentionsPluginType(node.returnType?.typeAnnotation)) {
253
+ isPluginModule = true;
254
+ }
255
+ },
256
+ ObjectExpression(node) {
257
+ if (!isPluginModule && (0, plugin_utils_1.looksLikePluginObject)(node)) {
258
+ isPluginModule = true;
259
+ }
260
+ },
261
+ ImportDeclaration(node) {
262
+ if (node.parent.type === 'Program' &&
263
+ node.importKind !== 'type' &&
264
+ // A side-effect import has no binding to move into a function.
265
+ node.specifiers.length > 0) {
266
+ importDeclarations.push(node);
267
+ }
268
+ },
269
+ ExportNamedDeclaration(node) {
270
+ // A value re-export keeps the source in the startup bundle, so nothing
271
+ // is gained by deferring the import of it.
272
+ if (!node.source || node.exportKind === 'type') {
273
+ return;
274
+ }
275
+ const hasValueSpecifier = node.specifiers.some(specifier => specifier.exportKind !== 'type');
276
+ if (hasValueSpecifier) {
277
+ reExportedSources.add(node.source.value);
278
+ }
279
+ },
280
+ ExportAllDeclaration(node) {
281
+ if (node.exportKind !== 'type') {
282
+ reExportedSources.add(node.source.value);
283
+ }
284
+ },
285
+ 'Program:exit'() {
286
+ if (!isPluginModule && !reportInteractionCallbacks) {
287
+ return;
288
+ }
289
+ hostProvided = (0, shared_packages_1.getHostProvidedPackages)(context.filename);
290
+ const bySource = new Map();
291
+ for (const declaration of importDeclarations) {
292
+ const source = declaration.source.value;
293
+ const group = bySource.get(source);
294
+ if (group) {
295
+ group.push(declaration);
296
+ }
297
+ else {
298
+ bySource.set(source, [declaration]);
299
+ }
300
+ }
301
+ for (const [source, declarations] of bySource) {
302
+ checkSource(source, declarations);
303
+ }
304
+ }
305
+ };
306
+ }
307
+ });
308
+ module.exports = jupyterPreferLazyImports;
@@ -0,0 +1,70 @@
1
+ import { TSESTree } from '@typescript-eslint/types';
2
+ import { TSESLint } from '@typescript-eslint/utils';
3
+ export interface LazyImportOptions {
4
+ allowedPackages: string[];
5
+ ignoreImports: string[];
6
+ minimumSize: number;
7
+ reportInteractionCallbacks: boolean;
8
+ reportModuleLevelUsage: boolean;
9
+ }
10
+ /**
11
+ * An async chunk carries a few hundred bytes of bundler runtime, so around one
12
+ * kilobyte of code the saving cancels out. The default sits well above that
13
+ * break-even point: across the Jupyter extensions this rule was measured on,
14
+ * four kilobytes reports half as many imports as one kilobyte while still
15
+ * covering 95% of the code which could be deferred.
16
+ */
17
+ export declare const DEFAULT_MINIMUM_SIZE = 4096;
18
+ /**
19
+ * Packages shared through Module Federation, which the application therefore
20
+ * loads whether or not a plugin module imports them at the top.
21
+ *
22
+ * This is the singleton list from `jupyterlab/staging/package.json`, minus
23
+ * `@lumino/datagrid` which core itself defers (see `packages/csvviewer`).
24
+ * Entries prefixed with `!` are denied even when another pattern allows them.
25
+ */
26
+ export declare const DEFAULT_ALLOWED_PACKAGES: string[];
27
+ /**
28
+ * Assets which a bundler turns into a URL or a style side effect rather than
29
+ * into bundled bytes, so deferring the import saves nothing.
30
+ *
31
+ * Images and fonts are `asset/resource` in the builder configuration, so they
32
+ * are always emitted as separate files and the browser fetches them only when
33
+ * they are used. A stylesheet goes through `style-loader`, which applies it
34
+ * when it is imported, so deferring it would change when the styles take
35
+ * effect rather than only what is downloaded.
36
+ *
37
+ * Assets which are inlined into the bundle as text are deliberately absent:
38
+ * `.svg` imported from JavaScript, `.raw.css`, `.md`, `.txt` and `.json` all
39
+ * add their full size to the startup chunk, so they are measured like any
40
+ * other module.
41
+ */
42
+ export declare const ALWAYS_IGNORED_IMPORTS: string[];
43
+ /**
44
+ * Matches an import specifier against a list of glob patterns. The specifier is
45
+ * tested both as written and as its owning package name. A matching `!` pattern
46
+ * denies the specifier regardless of any other match.
47
+ */
48
+ export declare function matchesPatterns(specifier: string, patterns: string[]): boolean;
49
+ /**
50
+ * Returns true when the node runs while the module is evaluated, either
51
+ * directly or through a named function which is called at module level.
52
+ */
53
+ export declare function isEagerlyReached(node: TSESTree.Node, sourceCode: TSESLint.SourceCode, seen?: Set<TSESTree.Node>, depth?: number): boolean;
54
+ /**
55
+ * Returns true when the node sits inside a user-interaction handler, so it
56
+ * cannot run until the user acts, however the module itself is loaded. The
57
+ * closure only exists once the enclosing handler runs, so anything nested
58
+ * deeper inside it waits for the user as well.
59
+ */
60
+ export declare function isInInteractionCallback(node: TSESTree.Node): boolean;
61
+ /**
62
+ * Returns true when the node sits in a plugin's `requires`, `optional` or
63
+ * `provides` entry, where a token has to be referenced at module load.
64
+ */
65
+ export declare function isInPluginTokenList(node: TSESTree.Node): boolean;
66
+ /**
67
+ * Builds the deferred import snippet suggested in the report message, merging
68
+ * every declaration which imports the same source.
69
+ */
70
+ export declare function buildDeferredImportSnippet(declarations: TSESTree.ImportDeclaration[]): string;