@jupyter/eslint-plugin 1.2.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.
@@ -0,0 +1,296 @@
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
+ const fs = __importStar(require("fs"));
40
+ const path = __importStar(require("path"));
41
+ const utils_1 = require("@typescript-eslint/utils");
42
+ const create_rule_1 = require("../utils/create-rule");
43
+ const plugin_utils_1 = require("../utils/plugin-utils");
44
+ const package_json_1 = require("../utils/package-json");
45
+ const MAX_PACKAGE_LEVELS = 12;
46
+ const packageManifestCache = new Map();
47
+ const packagePathCache = new Map();
48
+ /**
49
+ * Reads manifest metadata used to detect package boundaries.
50
+ */
51
+ function readPackageManifest(packagePath) {
52
+ const packageJson = (0, package_json_1.readPackageJson)(packagePath);
53
+ if (!packageJson) {
54
+ return null;
55
+ }
56
+ const cached = packageManifestCache.get(packagePath);
57
+ if (cached?.mtimeMs === packageJson.mtimeMs) {
58
+ return cached;
59
+ }
60
+ const data = packageJson.data;
61
+ const jupyterlab = data.jupyterlab;
62
+ const name = typeof data.name === 'string' ? data.name : null;
63
+ const isExtension = name !== null &&
64
+ !!jupyterlab &&
65
+ typeof jupyterlab === 'object' &&
66
+ (('extension' in jupyterlab && Boolean(jupyterlab.extension)) ||
67
+ ('mimeExtension' in jupyterlab && Boolean(jupyterlab.mimeExtension)));
68
+ const info = {
69
+ mtimeMs: packageJson.mtimeMs,
70
+ name,
71
+ isExtension
72
+ };
73
+ packageManifestCache.set(packagePath, info);
74
+ return info;
75
+ }
76
+ /**
77
+ * Reads the package name from a manifest that declares an extension entry.
78
+ */
79
+ function readExtensionPackage(packagePath) {
80
+ const manifest = readPackageManifest(packagePath);
81
+ if (!manifest?.isExtension || manifest.name === null) {
82
+ return null;
83
+ }
84
+ const info = {
85
+ mtimeMs: manifest.mtimeMs,
86
+ name: manifest.name
87
+ };
88
+ return info;
89
+ }
90
+ /**
91
+ * Finds the nearest extension package manifest that governs a linted file.
92
+ */
93
+ function getExtensionPackageName(fromFile) {
94
+ const start = path.dirname(path.resolve(fromFile));
95
+ const cachedPath = packagePathCache.get(start);
96
+ if (cachedPath !== undefined) {
97
+ return cachedPath === null
98
+ ? null
99
+ : (readExtensionPackage(cachedPath)?.name ?? null);
100
+ }
101
+ const visited = [];
102
+ let found = null;
103
+ let directory = start;
104
+ for (let level = 0; level < MAX_PACKAGE_LEVELS; level++) {
105
+ visited.push(directory);
106
+ const packagePath = path.join(directory, 'package.json');
107
+ if (fs.existsSync(packagePath)) {
108
+ found = packagePath;
109
+ break;
110
+ }
111
+ if (fs.existsSync(path.join(directory, '.git'))) {
112
+ break;
113
+ }
114
+ const parent = path.dirname(directory);
115
+ if (parent === directory) {
116
+ break;
117
+ }
118
+ directory = parent;
119
+ }
120
+ for (const seen of visited) {
121
+ packagePathCache.set(seen, found);
122
+ }
123
+ return found === null ? null : (readExtensionPackage(found)?.name ?? null);
124
+ }
125
+ const pluginIdConvention = (0, create_rule_1.createRule)({
126
+ name: 'plugin-id-convention',
127
+ meta: {
128
+ type: 'problem',
129
+ docs: {
130
+ description: 'Ensure JupyterLab plugin IDs are prefixed with the extension package name',
131
+ url: 'https://eslint-plugin.readthedocs.io/en/latest/rules/plugin-id-convention/'
132
+ },
133
+ messages: {
134
+ mismatchedPrefix: 'JupyterLab plugin ID "{{ pluginId }}" should start with "{{ packageName }}:" so extension-level configuration (disable, defer, lock) applies to it.',
135
+ idEqualsPackageName: 'JupyterLab plugin ID "{{ pluginId }}" is the package name alone; the convention is "{{ packageName }}:<plugin>".'
136
+ },
137
+ schema: [
138
+ {
139
+ type: 'object',
140
+ properties: {
141
+ reportIdEqualToPackageName: {
142
+ type: 'boolean',
143
+ default: false,
144
+ description: 'Also report a plugin whose ID is exactly the package name. Extension-level configuration matches such an ID in full, so it has no user impact, but it does not follow the `<package>:<plugin>` convention.'
145
+ }
146
+ },
147
+ additionalProperties: false
148
+ }
149
+ ]
150
+ },
151
+ defaultOptions: [{ reportIdEqualToPackageName: false }],
152
+ create(context, [options]) {
153
+ let services = null;
154
+ let checker = null;
155
+ try {
156
+ services = utils_1.ESLintUtils.getParserServices(context, true);
157
+ checker = services.program ? services.program.getTypeChecker() : null;
158
+ }
159
+ catch {
160
+ services = null;
161
+ }
162
+ const getTSNode = services
163
+ ? (node) => services?.esTreeNodeToTSNodeMap.get(node)
164
+ : null;
165
+ /**
166
+ * Returns true when a type annotation refers to a plugin descriptor or to
167
+ * a MIME renderer extension entry, which JupyterLab registers as a plugin
168
+ * under the entry's `id`.
169
+ */
170
+ function mentionsPluginType(typeNode) {
171
+ return ((0, plugin_utils_1.typeMentionsJupyterPlugin)(typeNode, checker, getTSNode) ||
172
+ (0, plugin_utils_1.typeMentionsMimeExtension)(typeNode, checker, getTSNode));
173
+ }
174
+ /**
175
+ * Checks whether an object literal is typed as a plugin descriptor or as
176
+ * a MIME renderer extension entry.
177
+ */
178
+ function hasPluginType(node) {
179
+ const parent = node.parent;
180
+ if (!parent) {
181
+ return false;
182
+ }
183
+ if (parent.type === 'VariableDeclarator') {
184
+ return ((0, plugin_utils_1.getJupyterPluginKind)(parent, checker, getTSNode) !== null ||
185
+ (parent.id.type === 'Identifier' &&
186
+ mentionsPluginType(parent.id.typeAnnotation?.typeAnnotation)));
187
+ }
188
+ if (parent.type === 'TSAsExpression' ||
189
+ parent.type === 'TSSatisfiesExpression' ||
190
+ parent.type === 'TSTypeAssertion') {
191
+ return (mentionsPluginType(parent.typeAnnotation) ||
192
+ isReturnedFromPluginFactory(node));
193
+ }
194
+ if (isReturnedFromPluginFactory(node)) {
195
+ return true;
196
+ }
197
+ if (parent.type !== 'ArrayExpression') {
198
+ return false;
199
+ }
200
+ const grandparent = parent.parent;
201
+ if (!grandparent) {
202
+ return false;
203
+ }
204
+ if (grandparent.type === 'VariableDeclarator') {
205
+ return (grandparent.id.type === 'Identifier' &&
206
+ mentionsPluginType(grandparent.id.typeAnnotation?.typeAnnotation));
207
+ }
208
+ if (grandparent.type === 'TSAsExpression' ||
209
+ grandparent.type === 'TSSatisfiesExpression' ||
210
+ grandparent.type === 'TSTypeAssertion') {
211
+ return (mentionsPluginType(grandparent.typeAnnotation) ||
212
+ isReturnedFromPluginFactory(parent));
213
+ }
214
+ return isReturnedFromPluginFactory(parent);
215
+ }
216
+ /**
217
+ * Checks whether an object or array literal is returned by a factory whose
218
+ * return type is a plugin descriptor.
219
+ */
220
+ function isReturnedFromPluginFactory(node) {
221
+ let expression = node;
222
+ let parent = expression.parent;
223
+ while (parent?.type === 'TSAsExpression' ||
224
+ parent?.type === 'TSSatisfiesExpression' ||
225
+ parent?.type === 'TSTypeAssertion') {
226
+ expression = parent;
227
+ parent = parent.parent;
228
+ }
229
+ if (parent?.type === 'ReturnStatement' &&
230
+ parent.argument === expression) {
231
+ const fn = getEnclosingFunction(parent);
232
+ return mentionsPluginType(fn?.returnType?.typeAnnotation);
233
+ }
234
+ if (parent?.type === 'ArrowFunctionExpression' &&
235
+ parent.body === expression) {
236
+ return mentionsPluginType(parent.returnType?.typeAnnotation);
237
+ }
238
+ return false;
239
+ }
240
+ /**
241
+ * Finds the function that owns a return statement.
242
+ */
243
+ function getEnclosingFunction(node) {
244
+ let current = node.parent;
245
+ while (current) {
246
+ if (current.type === 'FunctionDeclaration' ||
247
+ current.type === 'FunctionExpression' ||
248
+ current.type === 'ArrowFunctionExpression') {
249
+ return current;
250
+ }
251
+ current = current.parent;
252
+ }
253
+ return null;
254
+ }
255
+ /**
256
+ * Reports plugin IDs that do not use the owning extension package prefix.
257
+ */
258
+ function reportIfNeeded(node) {
259
+ // The shape and annotation checks are syntactic, so they run before the
260
+ // ID is resolved: resolving may ask the type checker, and most object
261
+ // literals with an `id` are commands, menu items or DOM nodes.
262
+ const hasId = (0, plugin_utils_1.getObjectProperties)(node).has('id');
263
+ if (!hasId ||
264
+ (!(0, plugin_utils_1.looksLikePluginObject)(node, hasId) &&
265
+ !(0, plugin_utils_1.looksLikeMimeExtensionObject)(node, hasId) &&
266
+ !hasPluginType(node))) {
267
+ return;
268
+ }
269
+ const pluginId = (0, plugin_utils_1.getPluginId)(node, context.sourceCode.getScope(node), checker, getTSNode);
270
+ if (pluginId === null) {
271
+ return;
272
+ }
273
+ const packageName = getExtensionPackageName(context.filename);
274
+ if (!packageName || pluginId.startsWith(`${packageName}:`)) {
275
+ return;
276
+ }
277
+ // An ID that is exactly the package name follows no convention, but
278
+ // `disabledExtensions`, `deferredExtensions` and `lockedExtensions`
279
+ // match it in full, so it is reported only when asked for.
280
+ const isPackageName = pluginId === packageName;
281
+ if (isPackageName && !options.reportIdEqualToPackageName) {
282
+ return;
283
+ }
284
+ const idProperty = (0, plugin_utils_1.getObjectProperties)(node).get('id');
285
+ context.report({
286
+ node: idProperty?.value ?? node,
287
+ messageId: isPackageName ? 'idEqualsPackageName' : 'mismatchedPrefix',
288
+ data: { pluginId, packageName }
289
+ });
290
+ }
291
+ return {
292
+ ObjectExpression: reportIfNeeded
293
+ };
294
+ }
295
+ });
296
+ module.exports = pluginIdConvention;
@@ -11,6 +11,7 @@ const shared_packages_1 = require("../utils/shared-packages");
11
11
  const create_rule_1 = require("../utils/create-rule");
12
12
  const DEFAULT_OPTIONS = {
13
13
  allowedPackages: lazy_imports_1.DEFAULT_ALLOWED_PACKAGES,
14
+ deferredPackages: lazy_imports_1.DEFAULT_DEFERRED_PACKAGES,
14
15
  ignoreImports: [],
15
16
  minimumSize: lazy_imports_1.DEFAULT_MINIMUM_SIZE,
16
17
  reportInteractionCallbacks: false,
@@ -29,8 +30,24 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
29
30
  'Import it where it is used instead: `{{ snippet }}`',
30
31
  eagerModuleLevelUse: "'{{ source }}' is used at module level in a plugin module, so it loads before the application starts. " +
31
32
  "Move the usage into a function and import it there with `await import('{{ source }}')`.",
33
+ usedInAutostartActivate: "'{{ source }}' is imported at the top of a plugin module and used in `activate()` of an autostart plugin, so it loads before the application starts either way. " +
34
+ 'Do not `await import(...)` inside `activate()`: that delays the whole application start. ' +
35
+ "Register the extension point synchronously and load '{{ source }}' in the callback that first needs it, or ignore this import if activation needs it at once.",
32
36
  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 }}`'
37
+ 'Import it where it is used instead: `{{ snippet }}`',
38
+ deferredPackageImport: "'{{ source }}' is in `deferredPackages`, so it must only be loaded with `await import()`, but this static import loads it together with the module. " +
39
+ 'Import it where it is used instead: `{{ snippet }}`',
40
+ deferredPackageEagerUse: "'{{ source }}' is in `deferredPackages`, so it must only be loaded with `await import()`, but it is used while this module is evaluated. " +
41
+ "Move the usage into a function and import it there with `await import('{{ source }}')`. " +
42
+ 'If this module is itself only loaded with `import()`, disable the rule for this import.',
43
+ deferredPackageAutostartUse: "'{{ source }}' is imported at the top of a plugin module and used in `activate()` of an autostart plugin, so it loads before the application starts either way. " +
44
+ 'It is also in `deferredPackages`, so it must only be loaded with `await import()`. ' +
45
+ 'Do not `await import(...)` inside `activate()`: that delays the whole application start. ' +
46
+ "Register the extension point synchronously and load '{{ source }}' in the callback that first needs it, or ignore this import if activation needs it at once.",
47
+ deferredPackageNotTypeOnly: "'{{ source }}' is in `deferredPackages`, and this import has no runtime use, but it is not written as `import type`, so a build with `verbatimModuleSyntax` or plain JavaScript loads the package anyway. " +
48
+ 'Remove the import, or make it `import type`.',
49
+ deferredPackageReExport: "'{{ source }}' is in `deferredPackages`, so it must only be loaded with `await import()`, but this re-export loads it together with the module. " +
50
+ "Remove the re-export and use `await import('{{ source }}')` where the package is needed."
34
51
  },
35
52
  schema: [
36
53
  {
@@ -42,6 +59,12 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
42
59
  default: lazy_imports_1.DEFAULT_ALLOWED_PACKAGES,
43
60
  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
61
  },
62
+ deferredPackages: {
63
+ type: 'array',
64
+ items: { type: 'string' },
65
+ default: lazy_imports_1.DEFAULT_DEFERRED_PACKAGES,
66
+ description: 'Packages which must only be loaded with `await import()`. A static import of one is reported in every module, however its bindings are used. Matched like `allowedPackages`, takes precedence over it and over the manifest, and replaces the default list.'
67
+ },
45
68
  ignoreImports: {
46
69
  type: 'array',
47
70
  items: { type: 'string' },
@@ -71,7 +94,7 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
71
94
  },
72
95
  defaultOptions: [DEFAULT_OPTIONS],
73
96
  create(context, [options]) {
74
- const { allowedPackages, ignoreImports, minimumSize, reportInteractionCallbacks, reportModuleLevelUsage } = options;
97
+ const { allowedPackages, deferredPackages, ignoreImports, minimumSize, reportInteractionCallbacks, reportModuleLevelUsage } = options;
75
98
  let services = null;
76
99
  let checker = null;
77
100
  try {
@@ -95,18 +118,36 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
95
118
  // Packages this extension declares as provided by the application, read
96
119
  // from `jupyterlab.sharedPackages` in its own manifest. They extend
97
120
  // `allowedPackages` rather than replacing it, and are only looked up once
98
- // the file turns out to need checking.
121
+ // an import turns out to need them.
99
122
  let hostProvided = null;
100
123
  /**
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.
124
+ * Returns true when the specifier is exempt from the usage check, either
125
+ * because the application loads it eagerly anyway or because it was
126
+ * ignored explicitly.
104
127
  */
105
128
  function isExempt(source) {
106
- return ((0, lazy_imports_1.matchesPatterns)(source, lazy_imports_1.ALWAYS_IGNORED_IMPORTS) ||
129
+ if ((0, lazy_imports_1.matchesPatterns)(source, lazy_imports_1.ALWAYS_IGNORED_IMPORTS) ||
107
130
  (0, lazy_imports_1.matchesPatterns)(source, allowedPackages) ||
108
- (0, lazy_imports_1.matchesPatterns)(source, hostProvided ?? []) ||
109
- (0, lazy_imports_1.matchesPatterns)(source, ignoreImports));
131
+ (0, lazy_imports_1.matchesPatterns)(source, ignoreImports)) {
132
+ return true;
133
+ }
134
+ if (hostProvided === null) {
135
+ hostProvided = (0, shared_packages_1.getHostProvidedPackages)(context.filename);
136
+ }
137
+ return (0, lazy_imports_1.matchesPatterns)(source, hostProvided);
138
+ }
139
+ /**
140
+ * Returns true when the package must only be loaded with `import()`. The
141
+ * list wins over `allowedPackages` and the manifest, which describe what
142
+ * the application loads at startup, since this one describes what it
143
+ * keeps out of startup on purpose. `ignoreImports` still wins as the
144
+ * explicit way to skip a specifier, and an asset from such a package is
145
+ * left to the bundler like any other asset.
146
+ */
147
+ function isDeferredPackage(source) {
148
+ return ((0, lazy_imports_1.matchesPatterns)(source, deferredPackages) &&
149
+ !(0, lazy_imports_1.matchesPatterns)(source, lazy_imports_1.ALWAYS_IGNORED_IMPORTS) &&
150
+ !(0, lazy_imports_1.matchesPatterns)(source, ignoreImports));
110
151
  }
111
152
  /**
112
153
  * Returns true when the module holds too little code for a separate chunk
@@ -123,7 +164,7 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
123
164
  if (!resolved) {
124
165
  return false;
125
166
  }
126
- const size = (0, module_size_1.getTransitiveCodeSize)(resolved);
167
+ const size = (0, module_size_1.getTransitiveCodeSize)(resolved, minimumSize);
127
168
  return size !== null && size < minimumSize;
128
169
  }
129
170
  /**
@@ -180,15 +221,21 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
180
221
  // Unused, or used only in type positions which TypeScript erases.
181
222
  return;
182
223
  }
183
- if (isTooSmall(source)) {
184
- return;
224
+ // Measuring a module compiles it, which costs far more than the checks
225
+ // below, and most candidates are ruled out by them. The measurement
226
+ // therefore happens at the point of reporting rather than here.
227
+ function reportUnlessTooSmall(descriptor) {
228
+ if (isTooSmall(source)) {
229
+ return;
230
+ }
231
+ context.report(descriptor);
185
232
  }
186
233
  if (!isPluginModule) {
187
234
  // Outside a plugin module an ordinary function proves nothing, since
188
235
  // it may run while the application starts. Only a position which
189
236
  // provably waits for the user shows the import can load later.
190
237
  if (references.every(({ identifier }) => (0, lazy_imports_1.isInInteractionCallback)(identifier))) {
191
- context.report({
238
+ reportUnlessTooSmall({
192
239
  node: declarations[0],
193
240
  messageId: 'preferLazyImportInteraction',
194
241
  data: {
@@ -201,22 +248,42 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
201
248
  }
202
249
  let deferrable = 0;
203
250
  let eager = 0;
251
+ let activation = 0;
204
252
  let tokenList = 0;
205
253
  for (const { identifier } of references) {
206
254
  if ((0, lazy_imports_1.isInPluginTokenList)(identifier)) {
207
255
  // A token in `requires`, `optional` or `provides` is read when the
208
256
  // plugin is registered, so it can never be deferred.
209
257
  tokenList += 1;
258
+ continue;
210
259
  }
211
- else if ((0, lazy_imports_1.isEagerlyReached)(identifier, context.sourceCode)) {
212
- eager += 1;
213
- }
214
- else {
215
- deferrable += 1;
260
+ switch ((0, lazy_imports_1.getReach)(identifier, context.sourceCode)) {
261
+ case 'module':
262
+ eager += 1;
263
+ break;
264
+ case 'activation':
265
+ activation += 1;
266
+ break;
267
+ default:
268
+ deferrable += 1;
216
269
  }
217
270
  }
271
+ if (tokenList === 0 && eager === 0 && activation > 0) {
272
+ // `Application.start` waits for every autostart plugin before it
273
+ // attaches the shell, so the module is fetched before the application
274
+ // starts whatever this file does, and an `await import()` inside
275
+ // `activate` would hold the start back by one more request. The usual
276
+ // snippet is therefore the wrong advice here, even when other uses
277
+ // sit in callbacks which could defer it.
278
+ reportUnlessTooSmall({
279
+ node: declarations[0],
280
+ messageId: 'usedInAutostartActivate',
281
+ data: { source }
282
+ });
283
+ return;
284
+ }
218
285
  if (tokenList === 0 && eager === 0 && deferrable > 0) {
219
- context.report({
286
+ reportUnlessTooSmall({
220
287
  node: declarations[0],
221
288
  messageId: 'preferLazyImport',
222
289
  data: {
@@ -227,13 +294,114 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
227
294
  return;
228
295
  }
229
296
  if (reportModuleLevelUsage && eager > 0 && tokenList === 0) {
230
- context.report({
297
+ reportUnlessTooSmall({
231
298
  node: declarations[0],
232
299
  messageId: 'eagerModuleLevelUse',
233
300
  data: { source }
234
301
  });
235
302
  }
236
303
  }
304
+ /**
305
+ * Reports a static import of a package which must only be loaded with
306
+ * `import()`. Where the bindings are used makes no difference here: a
307
+ * binding used only inside a function still loads the package together
308
+ * with this module, and whether this module is part of the startup bundle
309
+ * cannot be seen from this file. So the import is reported wherever it
310
+ * appears, and the usage only picks the advice.
311
+ *
312
+ * Only `import type` is exempt, and that never gets here. A value import
313
+ * whose bindings have no runtime use, an inline `type` specifier included,
314
+ * is erased by TypeScript without `verbatimModuleSyntax` but kept with it
315
+ * (`import { type X }` becomes `import {} from '...'`), and JavaScript
316
+ * never erases anything, so it counts as loading the package as well.
317
+ */
318
+ function checkDeferredPackage(source, declarations) {
319
+ // The snippet is built from the declarations with a runtime use, plus a
320
+ // side-effect import, which has nothing to erase. Each of the others is
321
+ // reported on its own line, because deleting the reported declarations
322
+ // would leave it behind, still loading the package under
323
+ // `verbatimModuleSyntax` or in JavaScript.
324
+ const loading = [];
325
+ const references = [];
326
+ for (const declaration of declarations) {
327
+ const own = getValueReferences(declaration);
328
+ if (own.length > 0 || declaration.specifiers.length === 0) {
329
+ loading.push(declaration);
330
+ references.push(...own);
331
+ }
332
+ else {
333
+ context.report({
334
+ node: declaration,
335
+ messageId: 'deferredPackageNotTypeOnly',
336
+ data: { source }
337
+ });
338
+ }
339
+ }
340
+ if (loading.length === 0) {
341
+ return;
342
+ }
343
+ let eager = false;
344
+ let activation = false;
345
+ for (const { identifier } of references) {
346
+ if ((0, lazy_imports_1.isInPluginTokenList)(identifier)) {
347
+ eager = true;
348
+ break;
349
+ }
350
+ const reach = (0, lazy_imports_1.getReach)(identifier, context.sourceCode);
351
+ if (reach === 'module') {
352
+ eager = true;
353
+ break;
354
+ }
355
+ if (reach === 'activation') {
356
+ activation = true;
357
+ }
358
+ }
359
+ if (eager) {
360
+ context.report({
361
+ node: loading[0],
362
+ messageId: 'deferredPackageEagerUse',
363
+ data: { source }
364
+ });
365
+ return;
366
+ }
367
+ if (activation) {
368
+ // The snippet would put the `await import()` into `activate`, which
369
+ // holds the whole start back, so the advice is the one for any import
370
+ // used during the activation of an autostart plugin, with the list
371
+ // named as well.
372
+ context.report({
373
+ node: loading[0],
374
+ messageId: 'deferredPackageAutostartUse',
375
+ data: { source }
376
+ });
377
+ return;
378
+ }
379
+ context.report({
380
+ node: loading[0],
381
+ messageId: 'deferredPackageImport',
382
+ data: { source, snippet: (0, lazy_imports_1.buildDeferredImportSnippet)(loading) }
383
+ });
384
+ }
385
+ /**
386
+ * A re-export of a package which must only be loaded with `import()` is a
387
+ * finding in itself, `export { type X } from` included: only `export type`
388
+ * is erased under `verbatimModuleSyntax`, the rest stays as
389
+ * `export {} from '...'` and loads the source. For any other source a
390
+ * value re-export keeps it in the startup bundle, so deferring the
391
+ * matching import would gain nothing and the usage check skips it.
392
+ */
393
+ function checkReExport(node, source, hasValueSpecifier) {
394
+ if (isDeferredPackage(source)) {
395
+ context.report({
396
+ node,
397
+ messageId: 'deferredPackageReExport',
398
+ data: { source }
399
+ });
400
+ }
401
+ else if (hasValueSpecifier) {
402
+ reExportedSources.add(source);
403
+ }
404
+ }
237
405
  return {
238
406
  VariableDeclarator(node) {
239
407
  if (!isPluginModule &&
@@ -259,34 +427,22 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
259
427
  }
260
428
  },
261
429
  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) {
430
+ if (node.parent.type === 'Program' && node.importKind !== 'type') {
266
431
  importDeclarations.push(node);
267
432
  }
268
433
  },
269
434
  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
435
  if (!node.source || node.exportKind === 'type') {
273
436
  return;
274
437
  }
275
- const hasValueSpecifier = node.specifiers.some(specifier => specifier.exportKind !== 'type');
276
- if (hasValueSpecifier) {
277
- reExportedSources.add(node.source.value);
278
- }
438
+ checkReExport(node, node.source.value, node.specifiers.some(specifier => specifier.exportKind !== 'type'));
279
439
  },
280
440
  ExportAllDeclaration(node) {
281
441
  if (node.exportKind !== 'type') {
282
- reExportedSources.add(node.source.value);
442
+ checkReExport(node, node.source.value, true);
283
443
  }
284
444
  },
285
445
  'Program:exit'() {
286
- if (!isPluginModule && !reportInteractionCallbacks) {
287
- return;
288
- }
289
- hostProvided = (0, shared_packages_1.getHostProvidedPackages)(context.filename);
290
446
  const bySource = new Map();
291
447
  for (const declaration of importDeclarations) {
292
448
  const source = declaration.source.value;
@@ -298,8 +454,20 @@ const jupyterPreferLazyImports = (0, create_rule_1.createRule)({
298
454
  bySource.set(source, [declaration]);
299
455
  }
300
456
  }
457
+ // A package which must stay deferred is checked in every module. The
458
+ // usage check needs a plugin module, or the interaction option.
459
+ const checkUsage = isPluginModule || reportInteractionCallbacks;
301
460
  for (const [source, declarations] of bySource) {
302
- checkSource(source, declarations);
461
+ if (isDeferredPackage(source)) {
462
+ checkDeferredPackage(source, declarations);
463
+ }
464
+ else if (checkUsage) {
465
+ // A side-effect import has no binding to move into a function.
466
+ const withBindings = declarations.filter(declaration => declaration.specifiers.length > 0);
467
+ if (withBindings.length > 0) {
468
+ checkSource(source, withBindings);
469
+ }
470
+ }
303
471
  }
304
472
  }
305
473
  };