@jupyter/eslint-plugin 1.2.0 → 1.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.
Files changed (48) hide show
  1. package/lib/index.d.ts +27 -1
  2. package/lib/index.js +21 -3
  3. package/lib/rules/command-id-convention.d.ts +5 -0
  4. package/lib/rules/command-id-convention.js +87 -0
  5. package/lib/rules/galata-prefer-context-menu-helper.d.ts +6 -0
  6. package/lib/rules/galata-prefer-context-menu-helper.js +394 -0
  7. package/lib/rules/galata-prefer-menu-helper.js +18 -102
  8. package/lib/rules/no-untranslated-string.d.ts +2 -1
  9. package/lib/rules/no-untranslated-string.js +191 -113
  10. package/lib/rules/plugin-activation-args.d.ts +3 -3
  11. package/lib/rules/plugin-activation-args.js +173 -142
  12. package/lib/rules/plugin-description.js +12 -9
  13. package/lib/rules/plugin-id-convention.d.ts +6 -0
  14. package/lib/rules/plugin-id-convention.js +199 -0
  15. package/lib/rules/prefer-lazy-imports.d.ts +2 -2
  16. package/lib/rules/prefer-lazy-imports.js +257 -58
  17. package/lib/rules/prefer-signal-this-arg.d.ts +2 -3
  18. package/lib/rules/prefer-signal-this-arg.js +2 -10
  19. package/lib/rules/require-disposable-ownership.d.ts +1 -2
  20. package/lib/rules/require-disposable-ownership.js +3 -26
  21. package/lib/rules/require-disposable-transfer.d.ts +1 -2
  22. package/lib/rules/require-disposable-transfer.js +14 -14
  23. package/lib/rules/require-signal-cleanup.d.ts +2 -3
  24. package/lib/rules/require-signal-cleanup.js +2 -10
  25. package/lib/rules/require-signal-this-arg.d.ts +1 -2
  26. package/lib/rules/require-signal-this-arg.js +2 -10
  27. package/lib/utils/ast.d.ts +12 -0
  28. package/lib/utils/ast.js +49 -0
  29. package/lib/utils/commands.d.ts +17 -0
  30. package/lib/utils/commands.js +205 -0
  31. package/lib/utils/disposables.d.ts +12 -0
  32. package/lib/utils/disposables.js +101 -10
  33. package/lib/utils/lazy-imports.d.ts +27 -3
  34. package/lib/utils/lazy-imports.js +130 -36
  35. package/lib/utils/module-size.d.ts +7 -1
  36. package/lib/utils/module-size.js +10 -1
  37. package/lib/utils/package-json.d.ts +8 -0
  38. package/lib/utils/package-json.js +76 -0
  39. package/lib/utils/playwright-selectors.d.ts +15 -0
  40. package/lib/utils/playwright-selectors.js +80 -0
  41. package/lib/utils/plugin-utils.d.ts +66 -6
  42. package/lib/utils/plugin-utils.js +485 -59
  43. package/lib/utils/shared-packages.js +6 -16
  44. package/lib/utils/signals.d.ts +2 -8
  45. package/lib/utils/signals.js +7 -42
  46. package/lib/utils/type-services.d.ts +13 -0
  47. package/lib/utils/type-services.js +27 -0
  48. package/package.json +1 -1
@@ -36,15 +36,36 @@ var __importStar = (this && this.__importStar) || (function () {
36
36
  return result;
37
37
  };
38
38
  })();
39
- const utils_1 = require("@typescript-eslint/utils");
40
39
  const ts = __importStar(require("typescript"));
41
40
  const plugin_utils_1 = require("../utils/plugin-utils");
41
+ const type_services_1 = require("../utils/type-services");
42
42
  const create_rule_1 = require("../utils/create-rule");
43
43
  const DEFAULT_ALLOWED_FIRST_ARGUMENT_NAMES = ['app', '_app', '_'];
44
+ function unwrapParentheses(node) {
45
+ let current = node;
46
+ while (current.type === 'TSAsExpression' ||
47
+ current.type === 'TSTypeAssertion' ||
48
+ current.type === 'TSSatisfiesExpression') {
49
+ current = current.expression;
50
+ }
51
+ return current;
52
+ }
53
+ function extractFunctionInfo(node, fn) {
54
+ const params = fn.params.filter((param) => param.type === 'Identifier');
55
+ const paramNames = params.map(param => param.name);
56
+ const paramTypes = params.map(param => param.type === 'Identifier' ? (0, plugin_utils_1.extractParameterType)(param) : null);
57
+ const paramNodes = params.map(param => param.type === 'Identifier' ? param : null);
58
+ return {
59
+ node,
60
+ paramNames,
61
+ paramTypes,
62
+ paramNodes
63
+ };
64
+ }
44
65
  /**
45
66
  * Finds the activate function in the plugin object
46
67
  */
47
- function findActivateFunction(node) {
68
+ function findActivateFunction(node, sourceCode) {
48
69
  const activateProp = node.properties.find((prop) => prop.type === 'Property' &&
49
70
  ((prop.key.type === 'Identifier' && prop.key.name === 'activate') ||
50
71
  (prop.key.type === 'Literal' && prop.key.value === 'activate')));
@@ -52,19 +73,38 @@ function findActivateFunction(node) {
52
73
  return null;
53
74
  }
54
75
  const activateValue = activateProp.value;
55
- // Handle both arrow functions and regular functions
76
+ // Handle both arrow functions and regular functions inline
56
77
  if (activateValue.type === 'ArrowFunctionExpression' ||
57
78
  activateValue.type === 'FunctionExpression') {
58
- const params = activateValue.params.filter((param) => param.type === 'Identifier');
59
- const paramNames = params.map(param => param.name);
60
- const paramTypes = params.map(param => param.type === 'Identifier' ? (0, plugin_utils_1.extractParameterType)(param) : null);
61
- const paramNodes = params.map(param => param.type === 'Identifier' ? param : null);
62
- return {
63
- node: activateProp,
64
- paramNames,
65
- paramTypes,
66
- paramNodes
67
- };
79
+ return extractFunctionInfo(activateProp, activateValue);
80
+ }
81
+ // Handle referenced functions: `activate` or `activate: activatePlugin`
82
+ if (activateValue.type === 'Identifier' && sourceCode) {
83
+ const scope = sourceCode.getScope(activateValue);
84
+ let currentScope = scope;
85
+ let variable = null;
86
+ while (currentScope) {
87
+ const found = currentScope.set.get(activateValue.name);
88
+ if (found) {
89
+ variable = found;
90
+ break;
91
+ }
92
+ currentScope = currentScope.upper;
93
+ }
94
+ if (variable && variable.defs.length > 0) {
95
+ const def = variable.defs[0];
96
+ if (def.type === 'FunctionName' &&
97
+ def.node.type === 'FunctionDeclaration') {
98
+ return extractFunctionInfo(activateProp, def.node);
99
+ }
100
+ if (def.type === 'Variable' && def.node.init) {
101
+ const init = unwrapParentheses(def.node.init);
102
+ if (init.type === 'ArrowFunctionExpression' ||
103
+ init.type === 'FunctionExpression') {
104
+ return extractFunctionInfo(activateProp, init);
105
+ }
106
+ }
107
+ }
68
108
  }
69
109
  return null;
70
110
  }
@@ -152,17 +192,7 @@ const jupyterPluginActivationArgs = (0, create_rule_1.createRule)({
152
192
  ],
153
193
  create(context, [options]) {
154
194
  const allowedFirstArgumentNames = options.allowedFirstArgumentNames || DEFAULT_ALLOWED_FIRST_ARGUMENT_NAMES;
155
- // Try to obtain the TypeScript type checker for type-aware comparisons.
156
- let services = null;
157
- let checker = null;
158
- try {
159
- services = utils_1.ESLintUtils.getParserServices(context, true);
160
- checker = services.program ? services.program.getTypeChecker() : null;
161
- }
162
- catch {
163
- // Parser services unavailable (e.g., non-TS file or misconfigured parser)
164
- services = null;
165
- }
195
+ const { services, checker, getTSNode } = (0, type_services_1.getTypeServices)(context);
166
196
  /**
167
197
  * Given the AST node for a token in requires/optional, uses the TypeScript checker to extract T from
168
198
  * `Token<T>` and returns the TypeScript type object for T.
@@ -290,156 +320,157 @@ const jupyterPluginActivationArgs = (0, create_rule_1.createRule)({
290
320
  return [false, false];
291
321
  }
292
322
  return {
293
- VariableDeclarator(node) {
294
- const pluginKind = (0, plugin_utils_1.getJupyterPluginKind)(node, checker, n => services?.esTreeNodeToTSNodeMap.get(n));
295
- if (!pluginKind) {
323
+ ObjectExpression(pluginObj) {
324
+ const hasId = (0, plugin_utils_1.getObjectProperties)(pluginObj).has('id');
325
+ if (!hasId) {
296
326
  return;
297
327
  }
298
- if (node.init && node.init.type === 'ObjectExpression') {
299
- const pluginObj = node.init;
300
- const { requires, optional } = extractRequiresOptional(pluginObj);
301
- const activateInfo = findActivateFunction(pluginObj);
302
- if (!activateInfo) {
303
- return;
304
- }
305
- const { paramNames, paramTypes, paramNodes } = activateInfo;
306
- const expectedCount = 1 + requires.length + optional.length;
307
- const expectedTokensWithoutApp = [...requires, ...optional];
308
- if (expectedCount === 1 && paramNames.length === 0) {
309
- // Special case, not invalid
328
+ const pluginKind = (0, plugin_utils_1.getPluginObjectKind)(pluginObj, checker, getTSNode);
329
+ if (pluginKind !== 'frontend' && pluginKind !== 'service-manager') {
330
+ return;
331
+ }
332
+ const { requires, optional } = extractRequiresOptional(pluginObj);
333
+ const activateInfo = findActivateFunction(pluginObj, context.sourceCode);
334
+ if (!activateInfo) {
335
+ return;
336
+ }
337
+ const { paramNames, paramTypes, paramNodes } = activateInfo;
338
+ const expectedCount = 1 + requires.length + optional.length;
339
+ const expectedTokensWithoutApp = [...requires, ...optional];
340
+ if (expectedCount === 1 && paramNames.length === 0) {
341
+ // Special case, not invalid
342
+ return;
343
+ }
344
+ if (pluginKind === 'frontend') {
345
+ // Validation 1a: Check if first argument is one of the allowed names
346
+ if (paramNames.length > 0 &&
347
+ !allowedFirstArgumentNames.includes(paramNames[0])) {
348
+ context.report({
349
+ node: activateInfo.node,
350
+ messageId: 'appNotFirst',
351
+ data: {
352
+ arg: paramNames[0],
353
+ allowedNames: allowedFirstArgumentNames
354
+ .map(name => `"${name}"`)
355
+ .join(', ')
356
+ }
357
+ });
310
358
  return;
311
359
  }
312
- if (pluginKind === 'frontend') {
313
- // Validation 1a: Check if first argument is one of the allowed names
314
- if (paramNames.length > 0 &&
315
- !allowedFirstArgumentNames.includes(paramNames[0])) {
360
+ // Validation 1b: Check if first argument type is compatible with JupyterFrontEnd
361
+ if (paramNames.length > 0 && paramTypes.length > 0) {
362
+ const firstParamType = paramTypes[0];
363
+ if (!isCompatibleWithJupyterFrontEnd(firstParamType)) {
316
364
  context.report({
317
365
  node: activateInfo.node,
318
- messageId: 'appNotFirst',
366
+ messageId: 'invalidAppType',
319
367
  data: {
320
368
  arg: paramNames[0],
321
- allowedNames: allowedFirstArgumentNames
322
- .map(name => `"${name}"`)
323
- .join(', ')
324
- }
325
- });
326
- return;
327
- }
328
- // Validation 1b: Check if first argument type is compatible with JupyterFrontEnd
329
- if (paramNames.length > 0 && paramTypes.length > 0) {
330
- const firstParamType = paramTypes[0];
331
- if (!isCompatibleWithJupyterFrontEnd(firstParamType)) {
332
- context.report({
333
- node: activateInfo.node,
334
- messageId: 'invalidAppType',
335
- data: {
336
- arg: paramNames[0],
337
- type: firstParamType || 'unknown'
338
- }
339
- });
340
- return;
341
- }
342
- }
343
- }
344
- else if (pluginKind === 'service-manager') {
345
- // Validation 1: First argument must be literal null
346
- if (paramNames.length === 0 || paramTypes[0] !== null) {
347
- context.report({
348
- node: activateInfo.node,
349
- messageId: 'serviceManagerFirstArgNotNull',
350
- data: {
351
- arg: paramTypes[0]
369
+ type: firstParamType || 'unknown'
352
370
  }
353
371
  });
354
372
  return;
355
373
  }
356
374
  }
357
- // Validation 2: Check if argument count matches
358
- if (paramNames.length !== expectedCount) {
375
+ }
376
+ else if (pluginKind === 'service-manager') {
377
+ // Validation 1: First argument must be literal null
378
+ if (paramNames.length === 0 || paramTypes[0] !== null) {
359
379
  context.report({
360
380
  node: activateInfo.node,
361
- messageId: 'wrongArgumentCount',
381
+ messageId: 'serviceManagerFirstArgNotNull',
362
382
  data: {
363
- expected: String(expectedCount),
364
- tokenCount: String(requires.length + optional.length),
365
- actual: String(paramNames.length)
383
+ arg: paramTypes[0]
366
384
  }
367
385
  });
386
+ return;
387
+ }
388
+ }
389
+ // Validation 2: Check if argument count matches
390
+ if (paramNames.length !== expectedCount) {
391
+ context.report({
392
+ node: activateInfo.node,
393
+ messageId: 'wrongArgumentCount',
394
+ data: {
395
+ expected: String(expectedCount),
396
+ tokenCount: String(requires.length + optional.length),
397
+ actual: String(paramNames.length)
398
+ }
399
+ });
400
+ }
401
+ // Validation 3: Validate remaining parameters against expected token order
402
+ const actualParamTypes = paramTypes.slice(1); // First arg already validated above
403
+ const actualParamNodes = paramNodes.slice(1);
404
+ // Validate that parameter types match expected token types in order
405
+ for (let i = 0; i < actualParamTypes.length; i++) {
406
+ const paramType = actualParamTypes[i];
407
+ const paramNode = actualParamNodes[i];
408
+ const expectedToken = expectedTokensWithoutApp[i];
409
+ if (expectedToken === undefined) {
410
+ // Extra argument
411
+ context.report({
412
+ node: activateInfo.node,
413
+ messageId: 'extraArgument',
414
+ data: { arg: paramNames[i + 1] }
415
+ });
368
416
  }
369
- // Validation 3: Validate remaining parameters against expected token order
370
- const actualParamTypes = paramTypes.slice(1); // First arg already validated above
371
- const actualParamNodes = paramNodes.slice(1);
372
- // Validate that parameter types match expected token types in order
373
- for (let i = 0; i < actualParamTypes.length; i++) {
374
- const paramType = actualParamTypes[i];
375
- const paramNode = actualParamNodes[i];
376
- const expectedToken = expectedTokensWithoutApp[i];
377
- if (expectedToken === undefined) {
378
- // Extra argument
417
+ else {
418
+ const [matches, tokenUnresolved] = tokenMatchesParam(expectedToken, paramType, paramNode);
419
+ if (tokenUnresolved) {
379
420
  context.report({
380
421
  node: activateInfo.node,
381
- messageId: 'extraArgument',
382
- data: { arg: paramNames[i + 1] }
422
+ messageId: 'unresolvableTokenType',
423
+ data: { token: expectedToken.name }
383
424
  });
384
425
  }
385
- else {
386
- const [matches, tokenUnresolved] = tokenMatchesParam(expectedToken, paramType, paramNode);
387
- if (tokenUnresolved) {
426
+ else if (!matches) {
427
+ // Distinguish token-order conflict vs. invalid type annotation.
428
+ const matchesAnyOtherToken = expectedTokensWithoutApp.some((otherToken, j) => {
429
+ if (j === i)
430
+ return false;
431
+ const [otherMatches, tokenUnresolved] = tokenMatchesParam(otherToken, paramType, paramNode);
432
+ return otherMatches && !tokenUnresolved;
433
+ });
434
+ if (matchesAnyOtherToken) {
388
435
  context.report({
389
436
  node: activateInfo.node,
390
- messageId: 'unresolvableTokenType',
391
- data: { token: expectedToken.name }
437
+ messageId: 'mismatchedOrder',
438
+ data: { arg: paramNames[i + 1] }
392
439
  });
393
440
  }
394
- else if (!matches) {
395
- // Distinguish token-order conflict vs. invalid type annotation.
396
- const matchesAnyOtherToken = expectedTokensWithoutApp.some((otherToken, j) => {
397
- if (j === i)
398
- return false;
399
- const [otherMatches, tokenUnresolved] = tokenMatchesParam(otherToken, paramType, paramNode);
400
- return otherMatches && !tokenUnresolved;
441
+ else {
442
+ context.report({
443
+ node: activateInfo.node,
444
+ messageId: 'incorrectType',
445
+ data: {
446
+ arg: paramNames[i + 1],
447
+ type: paramType,
448
+ expected: expectedToken.name
449
+ }
401
450
  });
402
- if (matchesAnyOtherToken) {
403
- context.report({
404
- node: activateInfo.node,
405
- messageId: 'mismatchedOrder',
406
- data: { arg: paramNames[i + 1] }
407
- });
408
- }
409
- else {
410
- context.report({
411
- node: activateInfo.node,
412
- messageId: 'incorrectType',
413
- data: {
414
- arg: paramNames[i + 1],
415
- type: paramType,
416
- expected: expectedToken.name
417
- }
418
- });
419
- }
420
451
  }
421
- else if (i >= requires.length && paramNode) {
422
- // Token matched and is optional — param must be nullable.
423
- if (!isParamNullable(paramNode)) {
424
- context.report({
425
- node: activateInfo.node,
426
- messageId: 'optionalNotNullable',
427
- data: { arg: paramNames[i + 1], type: expectedToken.name }
428
- });
429
- }
452
+ }
453
+ else if (i >= requires.length && paramNode) {
454
+ // Token matched and is optional — param must be nullable.
455
+ if (!isParamNullable(paramNode)) {
456
+ context.report({
457
+ node: activateInfo.node,
458
+ messageId: 'optionalNotNullable',
459
+ data: { arg: paramNames[i + 1], type: expectedToken.name }
460
+ });
430
461
  }
431
462
  }
432
463
  }
433
- // Validation 4: Check for missing arguments (only if counts don't match)
434
- if (paramNames.length < expectedCount) {
435
- for (let i = Math.max(paramNames.length - 1, 0); i < expectedTokensWithoutApp.length; i++) {
436
- const missingToken = expectedTokensWithoutApp[i];
437
- context.report({
438
- node: activateInfo.node,
439
- messageId: 'missingArgument',
440
- data: { token: missingToken.name }
441
- });
442
- }
464
+ }
465
+ // Validation 4: Check for missing arguments (only if counts don't match)
466
+ if (paramNames.length < expectedCount) {
467
+ for (let i = Math.max(paramNames.length - 1, 0); i < expectedTokensWithoutApp.length; i++) {
468
+ const missingToken = expectedTokensWithoutApp[i];
469
+ context.report({
470
+ node: activateInfo.node,
471
+ messageId: 'missingArgument',
472
+ data: { token: missingToken.name }
473
+ });
443
474
  }
444
475
  }
445
476
  }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  const create_rule_1 = require("../utils/create-rule");
7
7
  const plugin_utils_1 = require("../utils/plugin-utils");
8
+ const type_services_1 = require("../utils/type-services");
8
9
  /**
9
10
  * Returns whether the object expression has a description property and whether
10
11
  * it is non-empty.
@@ -53,23 +54,25 @@ const jupyterPluginDescription = (0, create_rule_1.createRule)({
53
54
  },
54
55
  defaultOptions: [],
55
56
  create(context) {
57
+ const { checker, getTSNode } = (0, type_services_1.getTypeServices)(context);
56
58
  return {
57
- VariableDeclarator(varDecl) {
58
- // Check if this has a JupyterFrontEndPlugin type annotation
59
- if (!(0, plugin_utils_1.getJupyterPluginKind)(varDecl)) {
59
+ ObjectExpression(node) {
60
+ const hasId = (0, plugin_utils_1.getObjectProperties)(node).has('id');
61
+ if (!hasId) {
60
62
  return;
61
63
  }
62
- // Check if init is an object expression
63
- if (!varDecl.init || varDecl.init.type !== 'ObjectExpression') {
64
+ const pluginKind = (0, plugin_utils_1.getPluginObjectKind)(node, checker, getTSNode);
65
+ if (pluginKind !== 'frontend' &&
66
+ pluginKind !== 'service-manager' &&
67
+ pluginKind !== 'ambiguous') {
64
68
  return;
65
69
  }
66
- const pluginId = (0, plugin_utils_1.getPluginId)(varDecl.init);
70
+ const pluginId = (0, plugin_utils_1.getPluginId)(node, context.sourceCode.getScope(node), checker, getTSNode);
67
71
  const pluginIdSuffix = pluginId ? ` "${pluginId}"` : '';
68
- // Check if description property exists and is non-empty
69
- const descriptionStatus = checkDescriptionProperty(varDecl.init);
72
+ const descriptionStatus = checkDescriptionProperty(node);
70
73
  if (descriptionStatus !== 'present') {
71
74
  context.report({
72
- node: varDecl.init,
75
+ node,
73
76
  messageId: descriptionStatus === 'empty'
74
77
  ? 'emptyDescription'
75
78
  : 'missingDescription',
@@ -0,0 +1,6 @@
1
+ declare const pluginIdConvention: import("@typescript-eslint/utils/ts-eslint").RuleModule<"mismatchedPrefix" | "idEqualsPackageName", [{
2
+ reportIdEqualToPackageName: boolean;
3
+ }], unknown, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
4
+ name: string;
5
+ };
6
+ export = pluginIdConvention;
@@ -0,0 +1,199 @@
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 create_rule_1 = require("../utils/create-rule");
42
+ const plugin_utils_1 = require("../utils/plugin-utils");
43
+ const type_services_1 = require("../utils/type-services");
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
+ const { checker, getTSNode } = (0, type_services_1.getTypeServices)(context);
154
+ /**
155
+ * Reports plugin IDs that do not use the owning extension package prefix.
156
+ */
157
+ function reportIfNeeded(node) {
158
+ // The shape and annotation checks are syntactic, so they run before the
159
+ // ID is resolved: resolving may ask the type checker, and most object
160
+ // literals with an `id` are commands, menu items or DOM nodes.
161
+ const hasId = (0, plugin_utils_1.getObjectProperties)(node).has('id');
162
+ if (!hasId) {
163
+ return;
164
+ }
165
+ const pluginKind = (0, plugin_utils_1.getPluginObjectKind)(node, checker, getTSNode, {
166
+ allowUntyped: true,
167
+ matchMime: true
168
+ });
169
+ if (!pluginKind) {
170
+ return;
171
+ }
172
+ const pluginId = (0, plugin_utils_1.getPluginId)(node, context.sourceCode.getScope(node), checker, getTSNode);
173
+ if (pluginId === null) {
174
+ return;
175
+ }
176
+ const packageName = getExtensionPackageName(context.filename);
177
+ if (!packageName || pluginId.startsWith(`${packageName}:`)) {
178
+ return;
179
+ }
180
+ // An ID that is exactly the package name follows no convention, but
181
+ // `disabledExtensions`, `deferredExtensions` and `lockedExtensions`
182
+ // match it in full, so it is reported only when asked for.
183
+ const isPackageName = pluginId === packageName;
184
+ if (isPackageName && !options.reportIdEqualToPackageName) {
185
+ return;
186
+ }
187
+ const idProperty = (0, plugin_utils_1.getObjectProperties)(node).get('id');
188
+ context.report({
189
+ node: idProperty?.value ?? node,
190
+ messageId: isPackageName ? 'idEqualsPackageName' : 'mismatchedPrefix',
191
+ data: { pluginId, packageName }
192
+ });
193
+ }
194
+ return {
195
+ ObjectExpression: reportIfNeeded
196
+ };
197
+ }
198
+ });
199
+ module.exports = pluginIdConvention;
@@ -1,6 +1,6 @@
1
- import { ESLintUtils } from '@typescript-eslint/utils';
1
+ import { TSESLint } from '@typescript-eslint/utils';
2
2
  import { LazyImportOptions } from '../utils/lazy-imports';
3
- declare const jupyterPreferLazyImports: ESLintUtils.RuleModule<string, [LazyImportOptions], unknown, ESLintUtils.RuleListener> & {
3
+ declare const jupyterPreferLazyImports: TSESLint.RuleModule<string, [LazyImportOptions], unknown, TSESLint.RuleListener> & {
4
4
  name: string;
5
5
  };
6
6
  export = jupyterPreferLazyImports;