@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.
@@ -49,21 +49,6 @@ const requireDisposableOwnership = (0, create_rule_1.createRule)({
49
49
  catch {
50
50
  services = null;
51
51
  }
52
- function isDisposableCreation(node) {
53
- if (checker && services) {
54
- try {
55
- const tsNode = services.esTreeNodeToTSNodeMap.get(node);
56
- const type = checker.getTypeAtLocation(tsNode);
57
- if ((0, disposables_1.isDisposableType)(type, checker)) {
58
- return true;
59
- }
60
- }
61
- catch {
62
- // Fall back to the known Lumino disposable constructors below.
63
- }
64
- }
65
- return (0, disposables_1.isDisposableConstructor)(node);
66
- }
67
52
  const ownership = {
68
53
  sourceCode: context.sourceCode,
69
54
  checker,
@@ -85,7 +70,7 @@ const requireDisposableOwnership = (0, create_rule_1.createRule)({
85
70
  if ((0, disposables_1.isInJupyterPluginActivate)(node, ownership)) {
86
71
  return;
87
72
  }
88
- if (!isDisposableCreation(node)) {
73
+ if (!(0, disposables_1.constructsDisposable)(node, ownership)) {
89
74
  return;
90
75
  }
91
76
  const assignedVariable = (0, disposables_1.getAssignedVariable)(node, context.sourceCode);
@@ -170,14 +170,19 @@ const requireDisposableTransfer = (0, create_rule_1.createRule)({
170
170
  (0, disposables_1.markManagedDisposableUse)(pending, node, ownership);
171
171
  if ((0, disposables_1.isInJupyterPluginActivate)(node, ownership) ||
172
172
  isIgnoredReturn(node) ||
173
- !(0, disposables_1.shouldCheckReturnedDisposable)(node) ||
174
- (0, disposables_1.isDisposableExpressionManaged)(node, ownership)) {
173
+ !(0, disposables_1.shouldCheckReturnedDisposable)(node)) {
175
174
  return;
176
175
  }
176
+ // The name test reads the call itself, while the two tests after it
177
+ // ask the type checker about the callee, so a call this rule would
178
+ // never report is dropped before any of that work happens.
177
179
  if (!checkAllDisposableReturns &&
178
180
  !isLikelyDisposableFactoryCall(node)) {
179
181
  return;
180
182
  }
183
+ if ((0, disposables_1.isDisposableExpressionManaged)(node, ownership)) {
184
+ return;
185
+ }
181
186
  if (!returnsDisposable(node)) {
182
187
  return;
183
188
  }
@@ -0,0 +1,12 @@
1
+ import { TSESTree } from '@typescript-eslint/types';
2
+ export type WalkAction = 'skip-children' | 'stop' | undefined;
3
+ export declare function isNode(value: unknown): value is TSESTree.Node;
4
+ /**
5
+ * Iterative AST walk from `root`, visiting every node. The visitor may return
6
+ * 'skip-children' to avoid descending into a node, or 'stop' to abort the
7
+ * whole walk.
8
+ *
9
+ * Children come from the parser's visitor keys, so `parent` is never followed
10
+ * and a node's `loc` and `range` are never read as children.
11
+ */
12
+ export declare function walkFrom(root: TSESTree.Node, visit: (node: TSESTree.Node) => WalkAction): void;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) Jupyter Development Team.
4
+ * Distributed under the terms of the Modified BSD License.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.isNode = isNode;
8
+ exports.walkFrom = walkFrom;
9
+ const visitor_keys_1 = require("@typescript-eslint/visitor-keys");
10
+ function isNode(value) {
11
+ return (typeof value === 'object' &&
12
+ value !== null &&
13
+ typeof value.type === 'string');
14
+ }
15
+ /**
16
+ * Iterative AST walk from `root`, visiting every node. The visitor may return
17
+ * 'skip-children' to avoid descending into a node, or 'stop' to abort the
18
+ * whole walk.
19
+ *
20
+ * Children come from the parser's visitor keys, so `parent` is never followed
21
+ * and a node's `loc` and `range` are never read as children.
22
+ */
23
+ function walkFrom(root, visit) {
24
+ const stack = [root];
25
+ while (stack.length > 0) {
26
+ const node = stack.pop();
27
+ const action = visit(node);
28
+ if (action === 'stop') {
29
+ return;
30
+ }
31
+ if (action === 'skip-children') {
32
+ continue;
33
+ }
34
+ const keys = visitor_keys_1.visitorKeys[node.type] ?? (0, visitor_keys_1.getKeys)(node);
35
+ for (const key of keys) {
36
+ const child = node[key];
37
+ if (Array.isArray(child)) {
38
+ for (const item of child) {
39
+ if (isNode(item)) {
40
+ stack.push(item);
41
+ }
42
+ }
43
+ }
44
+ else if (isNode(child)) {
45
+ stack.push(child);
46
+ }
47
+ }
48
+ }
49
+ }
@@ -60,5 +60,17 @@ export declare function isClassFieldCollectionMutationCall(node: TSESTree.CallEx
60
60
  export declare function isDisposableExpressionManaged(node: TSESTree.Node, ownership: DisposableOwnershipContext): boolean;
61
61
  export declare function markManagedDisposableUse(pending: PendingDisposableMap, node: TSESTree.Node, ownership: DisposableOwnershipContext): void;
62
62
  export declare function isDisposableType(type: ts.Type, checker: ts.TypeChecker, seen?: Set<ts.Type>): boolean;
63
+ /**
64
+ * Whether a `new` expression creates a disposable, by the type it constructs
65
+ * when type information is available and by the known constructor names
66
+ * otherwise.
67
+ *
68
+ * A class is constructed all over a codebase, and for a class with no type
69
+ * parameters what it constructs is a property of the class rather than of any
70
+ * one call, so the answer is kept per constructor symbol. Resolving that symbol
71
+ * is name resolution and reading the instance type off it is a lookup, while
72
+ * typing the `new` expression resolves a construct signature.
73
+ */
74
+ export declare function constructsDisposable(node: TSESTree.NewExpression, ownership: DisposableOwnershipContext): boolean;
63
75
  export declare function shouldCheckReturnedDisposable(node: TSESTree.CallExpression): boolean;
64
76
  export {};
@@ -52,6 +52,7 @@ exports.isClassFieldCollectionMutationCall = isClassFieldCollectionMutationCall;
52
52
  exports.isDisposableExpressionManaged = isDisposableExpressionManaged;
53
53
  exports.markManagedDisposableUse = markManagedDisposableUse;
54
54
  exports.isDisposableType = isDisposableType;
55
+ exports.constructsDisposable = constructsDisposable;
55
56
  exports.shouldCheckReturnedDisposable = shouldCheckReturnedDisposable;
56
57
  const ts = __importStar(require("typescript"));
57
58
  const plugin_utils_1 = require("./plugin-utils");
@@ -954,6 +955,7 @@ function isArrayExtInsertCall(node) {
954
955
  */
955
956
  const signatureCache = new WeakMap();
956
957
  const disposableTypeCache = new WeakMap();
958
+ const disposableConstructorCache = new WeakMap();
957
959
  function isDisposableTypeCached(type, checker) {
958
960
  const cached = disposableTypeCache.get(type);
959
961
  if (cached !== undefined) {
@@ -1568,6 +1570,29 @@ function markDisposedSignalCallbackDisposals(pending, node, ownership) {
1568
1570
  markManagedVariablesWithoutScopeCheck(pending, target, ownership, node);
1569
1571
  }
1570
1572
  }
1573
+ /**
1574
+ * Whether a call can credit any disposable that is still waiting, which decides
1575
+ * whether it is worth asking the type checker which of its arguments take
1576
+ * ownership.
1577
+ *
1578
+ * Crediting removes an entry from `pending` and does nothing for a variable
1579
+ * that is not in it, so a call naming no waiting disposable changes nothing
1580
+ * whatever the answer is. Both the arguments and the receiver are checked
1581
+ * because the answer also decides whether the receiver checks in
1582
+ * `markManagedDisposableUse` run, and those credit the receiver. Any check
1583
+ * added there has to credit the receiver or an argument for this to hold.
1584
+ */
1585
+ function namesPendingDisposable(pending, node, ownership) {
1586
+ return getIdentifierVariables(ownership.sourceCode, node).some(variable => pending.has(variable));
1587
+ }
1588
+ function mayCreditPendingDisposable(pending, node, ownership) {
1589
+ if (node.type === 'CallExpression' &&
1590
+ node.callee.type === 'MemberExpression' &&
1591
+ namesPendingDisposable(pending, node.callee.object, ownership)) {
1592
+ return true;
1593
+ }
1594
+ return node.arguments.some(argument => namesPendingDisposable(pending, argument, ownership));
1595
+ }
1571
1596
  function markManagedDisposableUse(pending, node, ownership) {
1572
1597
  if (node.type === 'ReturnStatement') {
1573
1598
  if (isInJupyterPluginActivate(node, ownership)) {
@@ -1600,21 +1625,26 @@ function markManagedDisposableUse(pending, node, ownership) {
1600
1625
  markDisposedSignalCallbackDisposals(pending, node, ownership);
1601
1626
  markImmediateForEachOwnership(pending, node, ownership);
1602
1627
  }
1628
+ // Crediting a disposable only ever removes an entry from `pending`, so with
1629
+ // nothing waiting neither check below can change the outcome. Skipping them
1630
+ // avoids resolving the callee signature, which is the most expensive query
1631
+ // this module makes.
1603
1632
  if (pending.size > 0) {
1604
1633
  markManagedKnownOptionVariables(pending, node, ownership);
1605
- }
1606
- for (const argument of node.arguments) {
1607
- if (argument.type !== 'ObjectExpression') {
1608
- continue;
1609
- }
1610
- for (const property of argument.properties) {
1611
- if (property.type === 'Property' &&
1612
- isOptionsObjectValueManaged(property.value, ownership)) {
1613
- markManagedVariables(pending, property.value, ownership);
1634
+ for (const argument of node.arguments) {
1635
+ if (argument.type !== 'ObjectExpression') {
1636
+ continue;
1637
+ }
1638
+ for (const property of argument.properties) {
1639
+ if (property.type === 'Property' &&
1640
+ namesPendingDisposable(pending, property.value, ownership) &&
1641
+ isOptionsObjectValueManaged(property.value, ownership)) {
1642
+ markManagedVariables(pending, property.value, ownership);
1643
+ }
1614
1644
  }
1615
1645
  }
1616
1646
  }
1617
- const ownershipArguments = pending.size > 0
1647
+ const ownershipArguments = pending.size > 0 && mayCreditPendingDisposable(pending, node, ownership)
1618
1648
  ? getOwnershipArguments(node, ownership)
1619
1649
  : [];
1620
1650
  if (ownershipArguments.length > 0) {
@@ -1686,6 +1716,67 @@ function isDisposableType(type, checker, seen = new Set()) {
1686
1716
  hasDisposableHeritage(type) ||
1687
1717
  hasDisposableShape(apparentType, checker));
1688
1718
  }
1719
+ /**
1720
+ * A class with no type parameters constructs the same type everywhere, so its
1721
+ * instance type answers for every `new` of it. A generic one does not: `dispose`
1722
+ * can be declared as the type parameter, which is callable in one instantiation
1723
+ * and not in another, so those are asked about one expression at a time.
1724
+ */
1725
+ function nonGenericClassSymbol(symbol) {
1726
+ if (!symbol || !(symbol.flags & ts.SymbolFlags.Class)) {
1727
+ return undefined;
1728
+ }
1729
+ const declarations = symbol.declarations ?? [];
1730
+ const generic = declarations.some(declaration => (ts.isClassDeclaration(declaration) ||
1731
+ ts.isClassExpression(declaration)) &&
1732
+ (declaration.typeParameters?.length ?? 0) > 0);
1733
+ return generic ? undefined : symbol;
1734
+ }
1735
+ /**
1736
+ * Whether a `new` expression creates a disposable, by the type it constructs
1737
+ * when type information is available and by the known constructor names
1738
+ * otherwise.
1739
+ *
1740
+ * A class is constructed all over a codebase, and for a class with no type
1741
+ * parameters what it constructs is a property of the class rather than of any
1742
+ * one call, so the answer is kept per constructor symbol. Resolving that symbol
1743
+ * is name resolution and reading the instance type off it is a lookup, while
1744
+ * typing the `new` expression resolves a construct signature.
1745
+ */
1746
+ function constructsDisposable(node, ownership) {
1747
+ const { checker, services } = ownership;
1748
+ if (checker && services) {
1749
+ try {
1750
+ const tsNode = services.esTreeNodeToTSNodeMap.get(node);
1751
+ let symbol = checker.getSymbolAtLocation(tsNode.expression);
1752
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
1753
+ // An imported class resolves to a different alias symbol in every
1754
+ // file; the class it points at is shared by all of them.
1755
+ symbol = checker.getAliasedSymbol(symbol);
1756
+ }
1757
+ const classSymbol = nonGenericClassSymbol(symbol);
1758
+ if (classSymbol) {
1759
+ const cached = disposableConstructorCache.get(classSymbol);
1760
+ if (cached !== undefined) {
1761
+ return cached || isDisposableConstructor(node);
1762
+ }
1763
+ }
1764
+ const result = isDisposableTypeCached(classSymbol
1765
+ ? checker.getDeclaredTypeOfSymbol(classSymbol)
1766
+ : checker.getTypeAtLocation(tsNode), checker);
1767
+ if (classSymbol) {
1768
+ disposableConstructorCache.set(classSymbol, result);
1769
+ }
1770
+ if (result) {
1771
+ return true;
1772
+ }
1773
+ }
1774
+ catch {
1775
+ // Fall back to the known Lumino disposable constructors below.
1776
+ }
1777
+ }
1778
+ return isDisposableConstructor(node);
1779
+ }
1689
1780
  function shouldCheckReturnedDisposable(node) {
1690
1781
  const expression = getOuterFallbackExpression(node);
1691
1782
  const parent = expression.parent;
@@ -2,6 +2,7 @@ import { TSESTree } from '@typescript-eslint/types';
2
2
  import { TSESLint } from '@typescript-eslint/utils';
3
3
  export interface LazyImportOptions {
4
4
  allowedPackages: string[];
5
+ deferredPackages: string[];
5
6
  ignoreImports: string[];
6
7
  minimumSize: number;
7
8
  reportInteractionCallbacks: boolean;
@@ -24,6 +25,15 @@ export declare const DEFAULT_MINIMUM_SIZE = 4096;
24
25
  * Entries prefixed with `!` are denied even when another pattern allows them.
25
26
  */
26
27
  export declare const DEFAULT_ALLOWED_PACKAGES: string[];
28
+ /**
29
+ * Packages which JupyterLab itself loads only with `import()`, so a static
30
+ * import anywhere in an extension puts them back on the startup path.
31
+ *
32
+ * A subpath such as `@codemirror/legacy-modes/mode/python` matches through its
33
+ * owning package. Entries prefixed with `!` are exempt even when another
34
+ * pattern matches them.
35
+ */
36
+ export declare const DEFAULT_DEFERRED_PACKAGES: string[];
27
37
  /**
28
38
  * Assets which a bundler turns into a URL or a style side effect rather than
29
39
  * into bundled bytes, so deferring the import saves nothing.
@@ -47,10 +57,23 @@ export declare const ALWAYS_IGNORED_IMPORTS: string[];
47
57
  */
48
58
  export declare function matchesPatterns(specifier: string, patterns: string[]): boolean;
49
59
  /**
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.
60
+ * When a node runs, relative to the application starting. `module` is while
61
+ * the module is evaluated. `activation` is inside the `activate` of a plugin
62
+ * which declares `autoStart: true`, which `Application.start` waits for before
63
+ * it attaches the shell. `deferred` is any later point the rule cannot place,
64
+ * such as a command or a method call.
65
+ */
66
+ export type Reach = 'module' | 'activation' | 'deferred';
67
+ /**
68
+ * Finds when the node runs: while the module is evaluated, during the
69
+ * activation of an autostart plugin, or only later. A node inside a named
70
+ * function is placed by the function's call sites, followed transitively, and
71
+ * the earliest of them wins, so a helper called from both `activate` and a
72
+ * command runs during activation. Each function is explored once per walk,
73
+ * which ends a cycle and bounds the cost by the number of functions in the
74
+ * file, so a chain of helpers is followed however long it is.
52
75
  */
53
- export declare function isEagerlyReached(node: TSESTree.Node, sourceCode: TSESLint.SourceCode, seen?: Set<TSESTree.Node>, depth?: number): boolean;
76
+ export declare function getReach(node: TSESTree.Node, sourceCode: TSESLint.SourceCode, seen?: Set<TSESTree.Node>): Reach;
54
77
  /**
55
78
  * Returns true when the node sits inside a user-interaction handler, so it
56
79
  * cannot run until the user acts, however the module itself is loaded. The
@@ -4,9 +4,9 @@
4
4
  * Distributed under the terms of the Modified BSD License.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.ALWAYS_IGNORED_IMPORTS = exports.DEFAULT_ALLOWED_PACKAGES = exports.DEFAULT_MINIMUM_SIZE = void 0;
7
+ exports.ALWAYS_IGNORED_IMPORTS = exports.DEFAULT_DEFERRED_PACKAGES = exports.DEFAULT_ALLOWED_PACKAGES = exports.DEFAULT_MINIMUM_SIZE = void 0;
8
8
  exports.matchesPatterns = matchesPatterns;
9
- exports.isEagerlyReached = isEagerlyReached;
9
+ exports.getReach = getReach;
10
10
  exports.isInInteractionCallback = isInInteractionCallback;
11
11
  exports.isInPluginTokenList = isInPluginTokenList;
12
12
  exports.buildDeferredImportSnippet = buildDeferredImportSnippet;
@@ -45,6 +45,23 @@ exports.DEFAULT_ALLOWED_PACKAGES = [
45
45
  'react-dom',
46
46
  'yjs'
47
47
  ];
48
+ /**
49
+ * Packages which JupyterLab itself loads only with `import()`, so a static
50
+ * import anywhere in an extension puts them back on the startup path.
51
+ *
52
+ * A subpath such as `@codemirror/legacy-modes/mode/python` matches through its
53
+ * owning package. Entries prefixed with `!` are exempt even when another
54
+ * pattern matches them.
55
+ */
56
+ exports.DEFAULT_DEFERRED_PACKAGES = [
57
+ '@lumino/datagrid',
58
+ '@codemirror/lang-*',
59
+ '@codemirror/legacy-modes',
60
+ '@codemirror/search',
61
+ '@rjsf/validator-ajv8',
62
+ 'mermaid',
63
+ 'react-toastify'
64
+ ];
48
65
  /**
49
66
  * Assets which a bundler turns into a URL or a style side effect rather than
50
67
  * into bundled bytes, so deferring the import saves nothing.
@@ -243,54 +260,122 @@ function getFunctionVariable(fn, sourceCode) {
243
260
  }
244
261
  return null;
245
262
  }
246
- const MAX_CALL_DEPTH = 6;
247
263
  /**
248
- * Returns true when the node runs while the module is evaluated, either
249
- * directly or through a named function which is called at module level.
264
+ * Returns true when the node is the `activate` entry of a plugin object which
265
+ * declares `autoStart: true`. Only the literal `true` counts: a plugin with
266
+ * `autoStart: 'defer'` is activated after the shell is attached. The object is
267
+ * read as written, so a spread or a computed key is not followed, as in every
268
+ * other plugin-shape check in this plugin.
250
269
  */
251
- function isEagerlyReached(node, sourceCode, seen = new Set(), depth = 0) {
270
+ function isAutostartActivateProperty(node) {
271
+ if (!node || node.type !== 'Property' || node.computed) {
272
+ return false;
273
+ }
274
+ const object = node.parent;
275
+ if (object?.type !== 'ObjectExpression') {
276
+ return false;
277
+ }
278
+ const properties = (0, plugin_utils_1.getObjectProperties)(object);
279
+ if (properties.get('activate') !== node) {
280
+ return false;
281
+ }
282
+ const autoStart = properties.get('autoStart');
283
+ return (!!autoStart &&
284
+ autoStart.value.type === 'Literal' &&
285
+ autoStart.value.value === true);
286
+ }
287
+ /**
288
+ * Returns true when a value sits directly in the `activate` entry of an
289
+ * autostart plugin: the function written in place, or the name of one
290
+ * declared elsewhere in the file, as in `activate: activateFoo` or the
291
+ * shorthand `{ activate }`.
292
+ */
293
+ function isAutostartActivateValue(node) {
294
+ const parent = node.parent;
295
+ return (parent?.type === 'Property' &&
296
+ parent.value === node &&
297
+ isAutostartActivateProperty(parent));
298
+ }
299
+ /**
300
+ * Returns the node whose position decides when the function referenced by
301
+ * `identifier` runs, or null when the reference does not call it. `run()` and
302
+ * `new Runner()` reach the body directly, `run.call()` and `run.apply()` do as
303
+ * well, and `list.map(run)` hands it to something which calls it straight
304
+ * away. Passing the function anywhere else does not say when, or whether, it
305
+ * runs.
306
+ */
307
+ function getInvocation(identifier) {
308
+ const parent = identifier.parent;
309
+ if (!parent) {
310
+ return null;
311
+ }
312
+ if ((parent.type === 'CallExpression' || parent.type === 'NewExpression') &&
313
+ parent.callee === identifier) {
314
+ return identifier;
315
+ }
316
+ if (parent.type === 'MemberExpression' &&
317
+ parent.object === identifier &&
318
+ !parent.computed &&
319
+ parent.property.type === 'Identifier' &&
320
+ (parent.property.name === 'call' || parent.property.name === 'apply') &&
321
+ parent.parent?.type === 'CallExpression' &&
322
+ parent.parent.callee === parent) {
323
+ return parent.parent;
324
+ }
325
+ if ((parent.type === 'CallExpression' || parent.type === 'NewExpression') &&
326
+ parent.arguments.includes(identifier) &&
327
+ invokesItsCallback(parent)) {
328
+ return identifier;
329
+ }
330
+ return null;
331
+ }
332
+ /**
333
+ * Finds when the node runs: while the module is evaluated, during the
334
+ * activation of an autostart plugin, or only later. A node inside a named
335
+ * function is placed by the function's call sites, followed transitively, and
336
+ * the earliest of them wins, so a helper called from both `activate` and a
337
+ * command runs during activation. Each function is explored once per walk,
338
+ * which ends a cycle and bounds the cost by the number of functions in the
339
+ * file, so a chain of helpers is followed however long it is.
340
+ */
341
+ function getReach(node, sourceCode, seen = new Set()) {
252
342
  const boundary = findDeferringBoundary(node);
253
343
  if (boundary === null) {
254
- return true;
344
+ return 'module';
255
345
  }
256
- if (boundary === 'field' || depth >= MAX_CALL_DEPTH || seen.has(boundary)) {
257
- return false;
346
+ if (boundary === 'field' || seen.has(boundary)) {
347
+ return 'deferred';
258
348
  }
259
349
  seen.add(boundary);
350
+ if (isAutostartActivateValue(boundary)) {
351
+ return 'activation';
352
+ }
260
353
  const variable = getFunctionVariable(boundary, sourceCode);
261
354
  if (!variable) {
262
- return false;
355
+ return 'deferred';
263
356
  }
264
- return variable.references.some(reference => {
265
- const identifier = reference.identifier;
266
- const parent = identifier.parent;
267
- if (!parent) {
268
- return false;
357
+ let reach = 'deferred';
358
+ for (const { identifier } of variable.references) {
359
+ let result;
360
+ const invocation = getInvocation(identifier);
361
+ if (invocation) {
362
+ result = getReach(invocation, sourceCode, seen);
269
363
  }
270
- // `run()` and `new Runner()` reach the body directly.
271
- if ((parent.type === 'CallExpression' || parent.type === 'NewExpression') &&
272
- parent.callee === identifier) {
273
- return isEagerlyReached(identifier, sourceCode, seen, depth + 1);
364
+ else if (isAutostartActivateValue(identifier)) {
365
+ // The plugin registry calls the function when the application starts.
366
+ result = 'activation';
274
367
  }
275
- // `run.call(...)` and `run.apply(...)` reach it as well.
276
- if (parent.type === 'MemberExpression' &&
277
- parent.object === identifier &&
278
- !parent.computed &&
279
- parent.property.type === 'Identifier' &&
280
- (parent.property.name === 'call' || parent.property.name === 'apply') &&
281
- parent.parent?.type === 'CallExpression' &&
282
- parent.parent.callee === parent) {
283
- return isEagerlyReached(parent.parent, sourceCode, seen, depth + 1);
368
+ else {
369
+ continue;
284
370
  }
285
- // `list.map(run)` passes it to something which calls it straight away.
286
- if ((parent.type === 'CallExpression' || parent.type === 'NewExpression') &&
287
- parent.arguments.includes(identifier) &&
288
- invokesItsCallback(parent)) {
289
- return isEagerlyReached(identifier, sourceCode, seen, depth + 1);
371
+ if (result === 'module') {
372
+ return 'module';
290
373
  }
291
- // Passing the function anywhere else does not say when, or whether, it runs.
292
- return false;
293
- });
374
+ if (result === 'activation') {
375
+ reach = 'activation';
376
+ }
377
+ }
378
+ return reach;
294
379
  }
295
380
  /**
296
381
  * DOM events which only fire on a user action, so a listener for one of them
@@ -8,5 +8,11 @@ export declare function resolveRelativeModule(specifier: string, fromFile: strin
8
8
  /**
9
9
  * Sums the code size of a module and of every relative module it statically
10
10
  * imports. Returns null when the file cannot be read.
11
+ *
12
+ * Callers which only compare the total against a threshold can pass it as
13
+ * `budget`. The walk then stops as soon as the running total reaches it and
14
+ * returns that partial sum, because a module already over the threshold stays
15
+ * over it however much more its imports hold. The files behind the threshold
16
+ * are never read.
11
17
  */
12
- export declare function getTransitiveCodeSize(entry: string): number | null;
18
+ export declare function getTransitiveCodeSize(entry: string, budget?: number): number | null;
@@ -206,8 +206,14 @@ function readFileInfo(filePath) {
206
206
  /**
207
207
  * Sums the code size of a module and of every relative module it statically
208
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.
209
215
  */
210
- function getTransitiveCodeSize(entry) {
216
+ function getTransitiveCodeSize(entry, budget = Number.POSITIVE_INFINITY) {
211
217
  const root = readFileInfo(entry);
212
218
  if (!root) {
213
219
  return null;
@@ -226,6 +232,9 @@ function getTransitiveCodeSize(entry) {
226
232
  return null;
227
233
  }
228
234
  total += info.size;
235
+ if (total >= budget) {
236
+ return total;
237
+ }
229
238
  if (depth >= MAX_DEPTH || seen.size >= MAX_FILES) {
230
239
  continue;
231
240
  }
@@ -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
+ }