closure-context-scan 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +106 -3
- package/bin/cli.js +127 -0
- package/package.json +47 -6
- package/src/analyze.js +143 -0
- package/src/heap.js +173 -0
- package/src/register.js +25 -0
- package/src/source.js +164 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 appystore
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,106 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# closure-context-scan
|
|
2
|
+
|
|
3
|
+
Finds memory that is kept alive **only** because a live closure shares its V8 context with a dead one.
|
|
4
|
+
|
|
5
|
+
## The bug it targets
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
function setup() {
|
|
9
|
+
const big = loadHugeData();
|
|
10
|
+
const small = 42;
|
|
11
|
+
function debug() { return big.length; } // never kept
|
|
12
|
+
handlers.push(() => small); // kept, never touches big
|
|
13
|
+
}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
V8 creates **one context** per scope, shared by every closure in that scope. Because `debug` reads `big`, `big` is stored in that context. The arrow function that is kept alive keeps the context alive, and therefore `big`, even though it never uses it.
|
|
17
|
+
|
|
18
|
+
ESLint and TypeScript cannot see this. In DevTools you only get a `system / Context` entry, with no hint of which code is responsible.
|
|
19
|
+
|
|
20
|
+
## What the tool does
|
|
21
|
+
|
|
22
|
+
1. Takes a heap snapshot (`.heapsnapshot`) of your program.
|
|
23
|
+
2. Computes the dominator tree: how much memory would be freed if a given object went away.
|
|
24
|
+
3. For each closure context, finds the **live** closures that can read it. It reads their source code (embedded in the snapshot) and lists the variables they actually use.
|
|
25
|
+
4. Reports a context variable when all three conditions hold:
|
|
26
|
+
- no live closure uses it;
|
|
27
|
+
- the context is the only path keeping it in memory;
|
|
28
|
+
- its retained size is above the threshold.
|
|
29
|
+
5. Tells you where it is declared and which (now gone) function used it.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm i -D closure-context-scan
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
"scripts": {
|
|
39
|
+
"mem:closures": "closure-context-scan run -- src/index.js",
|
|
40
|
+
"mem:closures:server": "closure-context-scan run --delay 5000 -- server.js",
|
|
41
|
+
"mem:closures:ci": "closure-context-scan run --fail-on 5mb -- scripts/scenario.js"
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Or without installing: `npx closure-context-scan run -- app.js`.
|
|
46
|
+
|
|
47
|
+
Prefer your editor? The **Closure Context Scan** VS Code extension shows the same results in the Problems panel (see [`vscode-extension/`](vscode-extension/)).
|
|
48
|
+
|
|
49
|
+
Requires Node.js 22 or later.
|
|
50
|
+
|
|
51
|
+
| Command / option | Description |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `run -- <script> [args]` | Runs the script and takes the snapshot at exit, or after `--delay` |
|
|
54
|
+
| `analyze <file.heapsnapshot>` | Analyzes an existing snapshot (including one taken in DevTools) |
|
|
55
|
+
| `--delay <ms>` | For servers: take the snapshot after this delay, then stop |
|
|
56
|
+
| `--min-size <size>` | Reporting threshold, `100kb` by default |
|
|
57
|
+
| `--fail-on <size>` | Exit with code 1 if the total wasted memory exceeds this size (CI) |
|
|
58
|
+
| `--ignore <regex>` | Ignore matching files, e.g. `node_modules` |
|
|
59
|
+
| `--json` | JSON output |
|
|
60
|
+
| `--keep <file>` | Keep the snapshot at this path |
|
|
61
|
+
|
|
62
|
+
On an already running process (Linux/macOS): `node --require closure-context-scan/src/register.js app.js`, then `kill -USR2 <pid>`, then `closure-context-scan analyze closure-scan-<pid>.heapsnapshot`. (`SIGUSR2` is not available on Windows; use `run --delay` there.)
|
|
63
|
+
|
|
64
|
+
Tip for servers: send some traffic during the `--delay` window so that request-scoped closures exist when the snapshot is taken.
|
|
65
|
+
|
|
66
|
+
## Sample output
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
1. "report" — 1.5 MB wasted [object Array]
|
|
70
|
+
Declared in makeRoute (app.js:5)
|
|
71
|
+
Kept alive by closure (anonymous) (app.js:8:17), which does not use it.
|
|
72
|
+
Only used by: debug (line 7) — function(s) no longer in memory.
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Conservative by design
|
|
76
|
+
|
|
77
|
+
The tool would rather miss a leak than blame healthy code. It draws no conclusion when:
|
|
78
|
+
- `eval` or `with` is present;
|
|
79
|
+
- the context is retained by something other than a closure (suspended generator or `async` function, a function currently executing, native code);
|
|
80
|
+
- the source cannot be parsed.
|
|
81
|
+
|
|
82
|
+
Variable usage detection is deliberately broad: a name that appears anywhere in the closure counts as used.
|
|
83
|
+
|
|
84
|
+
## Security note
|
|
85
|
+
|
|
86
|
+
A heap snapshot is a full dump of your process memory: it can contain secrets (environment variables, tokens, passwords, user data).
|
|
87
|
+
- Snapshots taken by `run` are written to the OS temp directory and deleted after analysis, unless you pass `--keep`.
|
|
88
|
+
- Do not commit or share `.heapsnapshot` files; add `*.heapsnapshot` to your `.gitignore`.
|
|
89
|
+
- Only run the tool against environments and data you are allowed to inspect.
|
|
90
|
+
|
|
91
|
+
## Limitations
|
|
92
|
+
|
|
93
|
+
- Only analyzes JavaScript as it is executed. With TypeScript or a bundler, reported lines refer to the compiled code (no source map support yet).
|
|
94
|
+
- The `.heapsnapshot` file is loaded fully into memory. A 114 MB heap took about 5 s to analyze; very large heaps need a lot of RAM.
|
|
95
|
+
- Only closures that exist at snapshot time are visible.
|
|
96
|
+
- V8 internals can change between Node versions (tested on Node 22 and 24).
|
|
97
|
+
|
|
98
|
+
## Tests
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
npm test
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
MIT
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { spawnSync } = require('child_process');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const os = require('os');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const { analyze } = require('../src/analyze');
|
|
9
|
+
|
|
10
|
+
const HELP = `closure-context-scan — finds memory retained by dead closures
|
|
11
|
+
|
|
12
|
+
Usage:
|
|
13
|
+
closure-context-scan run [options] -- <script.js> [args...]
|
|
14
|
+
closure-context-scan analyze <file.heapsnapshot> [options]
|
|
15
|
+
|
|
16
|
+
Options:
|
|
17
|
+
--delay <ms> take the snapshot after this delay, then stop (for servers)
|
|
18
|
+
--min-size <size> minimum reported size (default 100kb; e.g. 500kb, 2mb)
|
|
19
|
+
--fail-on <size> exit code 1 if total wasted memory exceeds this size (CI)
|
|
20
|
+
--ignore <regex> ignore matching files (e.g. node_modules)
|
|
21
|
+
--keep <file> keep the snapshot at this path
|
|
22
|
+
--json JSON output
|
|
23
|
+
-h, --help show this help
|
|
24
|
+
`;
|
|
25
|
+
|
|
26
|
+
function parseSize(s) {
|
|
27
|
+
const m = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i.exec(String(s).trim());
|
|
28
|
+
if (!m) throw new Error(`Invalid size: ${s}`);
|
|
29
|
+
const mult = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 }[(m[2] || 'b').toLowerCase()];
|
|
30
|
+
return Math.round(Number(m[1]) * mult);
|
|
31
|
+
}
|
|
32
|
+
function fmt(n) {
|
|
33
|
+
if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;
|
|
34
|
+
if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`;
|
|
35
|
+
return `${n} B`;
|
|
36
|
+
}
|
|
37
|
+
function rel(f) {
|
|
38
|
+
const r = path.relative(process.cwd(), f);
|
|
39
|
+
return r && !r.startsWith('..') ? r : f;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseArgs(argv) {
|
|
43
|
+
const opts = { rest: [] };
|
|
44
|
+
const sep = argv.indexOf('--');
|
|
45
|
+
const head = sep >= 0 ? argv.slice(0, sep) : argv;
|
|
46
|
+
if (sep >= 0) opts.rest = argv.slice(sep + 1);
|
|
47
|
+
const pos = [];
|
|
48
|
+
for (let i = 0; i < head.length; i++) {
|
|
49
|
+
const a = head[i];
|
|
50
|
+
if (a === '--json') opts.json = true;
|
|
51
|
+
else if (a === '--delay') opts.delay = Number(head[++i]);
|
|
52
|
+
else if (a === '--min-size') opts.minSize = parseSize(head[++i]);
|
|
53
|
+
else if (a === '--fail-on') opts.failOn = parseSize(head[++i]);
|
|
54
|
+
else if (a === '--ignore') opts.ignore = new RegExp(head[++i]);
|
|
55
|
+
else if (a === '--keep') opts.keep = head[++i];
|
|
56
|
+
else if (a === '-h' || a === '--help') opts.help = true;
|
|
57
|
+
else pos.push(a);
|
|
58
|
+
}
|
|
59
|
+
opts.cmd = pos[0];
|
|
60
|
+
opts.target = pos[1];
|
|
61
|
+
if (opts.cmd === 'run' && !opts.rest.length && pos[1]) opts.rest = pos.slice(1);
|
|
62
|
+
return opts;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function report(res, opts) {
|
|
66
|
+
const total = res.findings.reduce((s, f) => s + f.retainedSize, 0);
|
|
67
|
+
if (opts.json) {
|
|
68
|
+
process.stdout.write(JSON.stringify({ ...res, totalWasted: total }, null, 2) + '\n');
|
|
69
|
+
return total;
|
|
70
|
+
}
|
|
71
|
+
const out = [];
|
|
72
|
+
out.push(`\nclosure-context-scan — heap analyzed: ${fmt(res.totalHeap)}, contexts scanned: ${res.contextsScanned}\n`);
|
|
73
|
+
if (!res.findings.length) {
|
|
74
|
+
out.push('✔ No variable needlessly retained by a closure context.\n');
|
|
75
|
+
}
|
|
76
|
+
res.findings.forEach((f, i) => {
|
|
77
|
+
out.push(`${i + 1}. "${f.variable}" — ${fmt(f.retainedSize)} wasted${f.instances > 1 ? ` (${f.instances} contexts)` : ''} [${f.valueType}]`);
|
|
78
|
+
out.push(` Declared in ${f.declaredIn ?? '?'} (${rel(f.file)}:${f.declaredLine ?? '?'})`);
|
|
79
|
+
const a = f.aliveClosures[0];
|
|
80
|
+
out.push(` Kept alive by closure ${a.name} (${rel(a.file)}:${a.line}:${a.column})${f.aliveCount > 1 ? ` and ${f.aliveCount - 1} other(s)` : ''}, which does not use it.`);
|
|
81
|
+
if (f.deadUsers.length) {
|
|
82
|
+
out.push(` Only used by: ${f.deadUsers.map((u) => `${u.name} (line ${u.line})`).join(', ')} — function(s) no longer in memory.`);
|
|
83
|
+
}
|
|
84
|
+
out.push(` → The context is shared between sibling closures. Fixes: move "${f.variable}" into a separate function, pass it as a parameter, or set it to null after use.\n`);
|
|
85
|
+
});
|
|
86
|
+
out.push(`Total wasted: ${fmt(total)}\n`);
|
|
87
|
+
process.stdout.write(out.join('\n'));
|
|
88
|
+
return total;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function main() {
|
|
92
|
+
const opts = parseArgs(process.argv.slice(2));
|
|
93
|
+
if (opts.help || !opts.cmd) { process.stdout.write(HELP); return 0; }
|
|
94
|
+
|
|
95
|
+
let file;
|
|
96
|
+
let temp = false;
|
|
97
|
+
if (opts.cmd === 'analyze') {
|
|
98
|
+
file = opts.target;
|
|
99
|
+
if (!file || !fs.existsSync(file)) { console.error('.heapsnapshot file not found.'); return 2; }
|
|
100
|
+
} else if (opts.cmd === 'run') {
|
|
101
|
+
if (!opts.rest.length) { console.error('Specify the script: closure-context-scan run -- app.js'); return 2; }
|
|
102
|
+
file = opts.keep ? path.resolve(opts.keep) : path.join(os.tmpdir(), `ccs-${process.pid}-${Date.now()}.heapsnapshot`);
|
|
103
|
+
temp = !opts.keep;
|
|
104
|
+
const env = { ...process.env, CCS_OUT: file };
|
|
105
|
+
if (opts.delay) env.CCS_DELAY = String(opts.delay);
|
|
106
|
+
// With --json, the target's stdout goes to stderr so that stdout stays valid JSON.
|
|
107
|
+
const stdio = opts.json ? ['inherit', 2, 'inherit'] : 'inherit';
|
|
108
|
+
const r = spawnSync(process.execPath, ['--require', path.join(__dirname, '../src/register.js'), ...opts.rest], { stdio, env });
|
|
109
|
+
if (!fs.existsSync(file)) { console.error(`No snapshot was produced (exit code ${r.status}).`); return 2; }
|
|
110
|
+
} else {
|
|
111
|
+
process.stdout.write(HELP); return 2;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
const res = analyze(file, { minSize: opts.minSize, ignore: opts.ignore });
|
|
116
|
+
const total = report(res, opts);
|
|
117
|
+
if (opts.failOn !== undefined && total > opts.failOn) {
|
|
118
|
+
if (!opts.json) console.error(`✖ --fail-on threshold exceeded (${fmt(total)} > ${fmt(opts.failOn)})`);
|
|
119
|
+
return 1;
|
|
120
|
+
}
|
|
121
|
+
return 0;
|
|
122
|
+
} finally {
|
|
123
|
+
if (temp) fs.rmSync(file, { force: true });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
process.exitCode = main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "closure-context-scan",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "closure-context-scan",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Find memory retained by dead closures through V8 shared contexts",
|
|
5
|
+
"main": "src/analyze.js",
|
|
6
|
+
"directories": {
|
|
7
|
+
"test": "test"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "node --test test/*.test.js",
|
|
11
|
+
"demo": "closure-context-scan run -- fixtures/leak.js"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"memory-leak",
|
|
15
|
+
"closure",
|
|
16
|
+
"v8",
|
|
17
|
+
"heap-snapshot",
|
|
18
|
+
"heapsnapshot",
|
|
19
|
+
"nodejs",
|
|
20
|
+
"profiling",
|
|
21
|
+
"cli",
|
|
22
|
+
"devtools"
|
|
23
|
+
],
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"author": "appystore",
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/IT-Skill31/closure-context-scan.git"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://github.com/IT-Skill31/closure-context-scan#readme",
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/IT-Skill31/closure-context-scan/issues"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"acorn": "^8.19.0"
|
|
36
|
+
},
|
|
37
|
+
"bin": {
|
|
38
|
+
"closure-context-scan": "bin/cli.js"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22"
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"bin",
|
|
45
|
+
"src"
|
|
46
|
+
]
|
|
47
|
+
}
|
package/src/analyze.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Finds variables kept in memory by a V8 closure context
|
|
3
|
+
// even though no live closure uses them.
|
|
4
|
+
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { HeapGraph } = require('./heap');
|
|
7
|
+
const src = require('./source');
|
|
8
|
+
|
|
9
|
+
const SELF_DIR = __dirname;
|
|
10
|
+
const SKIP_VAR = /^(\.|this$|new\.target$|\*)/;
|
|
11
|
+
|
|
12
|
+
function analyze(file, opts = {}) {
|
|
13
|
+
const minSize = opts.minSize ?? 100 * 1024;
|
|
14
|
+
// Lower per-instance threshold: 1000 contexts of 1 KB add up to 1 MB.
|
|
15
|
+
const floor = Math.min(minSize, 1024);
|
|
16
|
+
const g = new HeapGraph(file);
|
|
17
|
+
const retained = g.computeRetainedSizes();
|
|
18
|
+
|
|
19
|
+
const isContext = (n) => g.type(n) === 'object' && g.name(n) === 'system / Context';
|
|
20
|
+
|
|
21
|
+
// What retains each context?
|
|
22
|
+
const retainers = new Map();
|
|
23
|
+
for (let v = 0; v < g.count; v++) {
|
|
24
|
+
for (const e of g.edgesOf(v)) {
|
|
25
|
+
if (e.type === 'weak' || !isContext(e.to)) continue;
|
|
26
|
+
if (!retainers.has(e.to)) retainers.set(e.to, []);
|
|
27
|
+
retainers.get(e.to).push({ from: v, edge: e });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Live closures that can read a context (directly or through the "previous" chain).
|
|
32
|
+
const memo = new Map();
|
|
33
|
+
function usersOf(ctx) {
|
|
34
|
+
if (memo.has(ctx)) return memo.get(ctx);
|
|
35
|
+
const res = { closures: new Set(), opaque: null };
|
|
36
|
+
memo.set(ctx, res);
|
|
37
|
+
for (const { from, edge } of retainers.get(ctx) || []) {
|
|
38
|
+
if (g.type(from) === 'closure' && edge.name === 'context') res.closures.add(from);
|
|
39
|
+
else if (isContext(from) && edge.name === 'previous') {
|
|
40
|
+
const sub = usersOf(from);
|
|
41
|
+
for (const c of sub.closures) res.closures.add(c);
|
|
42
|
+
res.opaque = res.opaque || sub.opaque;
|
|
43
|
+
} else {
|
|
44
|
+
// Suspended generator, running function, native code…: no conclusion.
|
|
45
|
+
res.opaque = res.opaque || `${g.type(from)} ${g.name(from)}`;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return res;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function closureInfo(c) {
|
|
52
|
+
const shared = g.edge(c, 'internal', 'shared');
|
|
53
|
+
const script = shared >= 0 ? g.edge(shared, 'internal', 'script') : -1;
|
|
54
|
+
if (script < 0) return null;
|
|
55
|
+
const srcNode = g.edge(script, 'internal', 'source');
|
|
56
|
+
const nameNode = g.edge(script, 'internal', 'name');
|
|
57
|
+
const loc = g.locations.get(c);
|
|
58
|
+
if (srcNode < 0 || !loc || g.type(srcNode) !== 'string') return null;
|
|
59
|
+
const source = g.name(srcNode);
|
|
60
|
+
const scriptName = nameNode >= 0 ? g.name(nameNode).replace(/^file:\/+/, '/') : '(unknown)';
|
|
61
|
+
const info = src.parse(source);
|
|
62
|
+
if (!info) return null;
|
|
63
|
+
const fn = src.functionAt(info, loc.line, loc.column);
|
|
64
|
+
if (!fn) return null;
|
|
65
|
+
return { closure: c, scriptName, loc, info, fn, name: g.name(c) || src.fnName(info, fn), used: src.usedNames(fn) };
|
|
66
|
+
}
|
|
67
|
+
const closureCache = new Map();
|
|
68
|
+
const getClosure = (c) => {
|
|
69
|
+
if (!closureCache.has(c)) closureCache.set(c, closureInfo(c));
|
|
70
|
+
return closureCache.get(c);
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const findings = [];
|
|
74
|
+
let contextsScanned = 0;
|
|
75
|
+
for (const ctx of retainers.keys()) {
|
|
76
|
+
const vars = [...g.edgesOf(ctx)].filter((e) => e.type === 'context' && !SKIP_VAR.test(e.name));
|
|
77
|
+
if (!vars.length) continue;
|
|
78
|
+
// Pre-filter: nothing large in this context -> skip analysis.
|
|
79
|
+
if (!vars.some((v) => retained[v.to] >= floor)) continue;
|
|
80
|
+
|
|
81
|
+
const users = usersOf(ctx);
|
|
82
|
+
if (users.opaque || users.closures.size === 0) continue;
|
|
83
|
+
const infos = [...users.closures].map(getClosure);
|
|
84
|
+
if (infos.some((i) => !i || i.used.dynamic)) continue; // unparsable source or eval/with
|
|
85
|
+
if (infos.some((i) => i.scriptName.startsWith('node:') || i.scriptName.startsWith(SELF_DIR))) continue;
|
|
86
|
+
if (opts.ignore && infos.every((i) => opts.ignore.test(i.scriptName))) continue;
|
|
87
|
+
contextsScanned++;
|
|
88
|
+
|
|
89
|
+
for (const v of vars) {
|
|
90
|
+
const size = retained[v.to];
|
|
91
|
+
if (size < floor) continue;
|
|
92
|
+
// If the value is reachable through another path, the context is not to blame.
|
|
93
|
+
if (!g.dominates(ctx, v.to)) continue;
|
|
94
|
+
if (infos.some((i) => i.used.names.has(v.name))) continue;
|
|
95
|
+
const ref = infos[0];
|
|
96
|
+
const why = src.explain(ref.info, ref.fn, v.name);
|
|
97
|
+
findings.push({
|
|
98
|
+
node: v.to,
|
|
99
|
+
variable: v.name,
|
|
100
|
+
retainedSize: size,
|
|
101
|
+
valueType: `${g.type(v.to)} ${g.name(v.to)}`.trim(),
|
|
102
|
+
file: ref.scriptName,
|
|
103
|
+
declaredIn: why ? why.declaredIn : null,
|
|
104
|
+
declaredLine: why ? why.declaredLine : null,
|
|
105
|
+
variableLine: why ? why.variableLine : null,
|
|
106
|
+
variableColumn: why ? why.variableColumn : null,
|
|
107
|
+
deadUsers: why ? why.usedBy : [],
|
|
108
|
+
aliveClosures: infos.slice(0, 5).map((i) => ({
|
|
109
|
+
name: i.name || '(anonymous)',
|
|
110
|
+
file: i.scriptName,
|
|
111
|
+
line: i.loc.line + 1,
|
|
112
|
+
column: i.loc.column + 1,
|
|
113
|
+
})),
|
|
114
|
+
aliveCount: infos.length,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// No double counting: a value already retained by another reported value
|
|
120
|
+
// (chained leak) is not counted twice.
|
|
121
|
+
const flagged = new Set(findings.map((f) => f.node));
|
|
122
|
+
for (const f of findings) {
|
|
123
|
+
let v = f.node, guard = 0;
|
|
124
|
+
while (v !== 0 && v !== -1 && guard++ < 1e6) {
|
|
125
|
+
v = g.idom[v];
|
|
126
|
+
if (flagged.has(v)) { f.retainedSize = 0; break; }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// A function called N times creates N contexts: group them.
|
|
130
|
+
const groups = new Map();
|
|
131
|
+
for (const f of findings) {
|
|
132
|
+
const a = f.aliveClosures[0];
|
|
133
|
+
const key = `${f.file}|${f.declaredLine}|${a.line}:${a.column}|${f.variable}`;
|
|
134
|
+
const g0 = groups.get(key);
|
|
135
|
+
if (g0) { g0.retainedSize += f.retainedSize; g0.instances++; }
|
|
136
|
+
else { const { node, ...rest } = f; groups.set(key, { ...rest, instances: 1 }); }
|
|
137
|
+
}
|
|
138
|
+
const grouped = [...groups.values()].filter((f) => f.retainedSize >= minSize).sort((a, b) => b.retainedSize - a.retainedSize);
|
|
139
|
+
const totalHeap = retained[0];
|
|
140
|
+
return { file: path.resolve(file), totalHeap, contextsScanned, findings: grouped };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
module.exports = { analyze };
|
package/src/heap.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Reads a V8 heap snapshot (.heapsnapshot) and computes retained sizes.
|
|
3
|
+
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
|
|
6
|
+
class HeapGraph {
|
|
7
|
+
constructor(file) {
|
|
8
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
9
|
+
const meta = raw.snapshot.meta;
|
|
10
|
+
this.strings = raw.strings;
|
|
11
|
+
this.nodes = raw.nodes;
|
|
12
|
+
this.edges = raw.edges;
|
|
13
|
+
this.nf = meta.node_fields.length;
|
|
14
|
+
this.ef = meta.edge_fields.length;
|
|
15
|
+
this.nodeTypes = meta.node_types[0];
|
|
16
|
+
this.edgeTypes = meta.edge_types[0];
|
|
17
|
+
this.count = this.nodes.length / this.nf;
|
|
18
|
+
|
|
19
|
+
const f = meta.node_fields;
|
|
20
|
+
this.oType = f.indexOf('type');
|
|
21
|
+
this.oName = f.indexOf('name');
|
|
22
|
+
this.oSize = f.indexOf('self_size');
|
|
23
|
+
this.oEdgeCount = f.indexOf('edge_count');
|
|
24
|
+
const e = meta.edge_fields;
|
|
25
|
+
this.oEType = e.indexOf('type');
|
|
26
|
+
this.oEName = e.indexOf('name_or_index');
|
|
27
|
+
this.oETo = e.indexOf('to_node');
|
|
28
|
+
|
|
29
|
+
// Index of the first edge of each node.
|
|
30
|
+
this.firstEdge = new Uint32Array(this.count + 1);
|
|
31
|
+
let acc = 0;
|
|
32
|
+
for (let i = 0; i < this.count; i++) {
|
|
33
|
+
this.firstEdge[i] = acc;
|
|
34
|
+
acc += this.nodes[i * this.nf + this.oEdgeCount];
|
|
35
|
+
}
|
|
36
|
+
this.firstEdge[this.count] = acc;
|
|
37
|
+
|
|
38
|
+
// Function locations (closure -> line/column, 0-based).
|
|
39
|
+
this.locations = new Map();
|
|
40
|
+
const lf = meta.location_fields || [];
|
|
41
|
+
const L = raw.locations || [];
|
|
42
|
+
const step = lf.length || 4;
|
|
43
|
+
for (let k = 0; k < L.length; k += step) {
|
|
44
|
+
this.locations.set(L[k] / this.nf, { line: L[k + 2], column: L[k + 3] });
|
|
45
|
+
}
|
|
46
|
+
this.weak = this.edgeTypes.indexOf('weak');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type(n) { return this.nodeTypes[this.nodes[n * this.nf + this.oType]]; }
|
|
50
|
+
name(n) { return this.strings[this.nodes[n * this.nf + this.oName]]; }
|
|
51
|
+
selfSize(n) { return this.nodes[n * this.nf + this.oSize]; }
|
|
52
|
+
|
|
53
|
+
*edgesOf(n) {
|
|
54
|
+
for (let k = this.firstEdge[n]; k < this.firstEdge[n + 1]; k++) {
|
|
55
|
+
const o = k * this.ef;
|
|
56
|
+
const t = this.edgeTypes[this.edges[o + this.oEType]];
|
|
57
|
+
const raw = this.edges[o + this.oEName];
|
|
58
|
+
yield {
|
|
59
|
+
type: t,
|
|
60
|
+
name: t === 'element' || t === 'hidden' ? raw : this.strings[raw],
|
|
61
|
+
to: this.edges[o + this.oETo] / this.nf,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// True if "dom" lies on every path from the root to "n".
|
|
67
|
+
dominates(dom, n) {
|
|
68
|
+
let v = n, guard = 0;
|
|
69
|
+
while (v !== 0 && v !== -1 && guard++ < 1e6) {
|
|
70
|
+
v = this.idom[v];
|
|
71
|
+
if (v === dom) return true;
|
|
72
|
+
}
|
|
73
|
+
return dom === 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
edge(n, type, name) {
|
|
77
|
+
for (const e of this.edgesOf(n)) if (e.type === type && e.name === name) return e.to;
|
|
78
|
+
return -1;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Dominator tree (Cooper-Harvey-Kennedy), weak edges ignored.
|
|
82
|
+
computeRetainedSizes() {
|
|
83
|
+
const n = this.count;
|
|
84
|
+
const { edges, ef, oEType, oETo, nf, weak } = this;
|
|
85
|
+
const strong = (k) => edges[k * ef + oEType] !== weak;
|
|
86
|
+
const target = (k) => edges[k * ef + oETo] / nf;
|
|
87
|
+
|
|
88
|
+
// Iterative depth-first traversal from the root (node 0) -> post-order.
|
|
89
|
+
const post = new Int32Array(n).fill(-1);
|
|
90
|
+
const order = new Uint32Array(n);
|
|
91
|
+
let visited = 0;
|
|
92
|
+
const seen = new Uint8Array(n);
|
|
93
|
+
const stackNode = new Uint32Array(n);
|
|
94
|
+
const stackEdge = new Uint32Array(n);
|
|
95
|
+
let sp = 0;
|
|
96
|
+
stackNode[0] = 0; stackEdge[0] = this.firstEdge[0]; seen[0] = 1;
|
|
97
|
+
while (sp >= 0) {
|
|
98
|
+
const v = stackNode[sp];
|
|
99
|
+
let k = stackEdge[sp];
|
|
100
|
+
const end = this.firstEdge[v + 1];
|
|
101
|
+
let pushed = false;
|
|
102
|
+
while (k < end) {
|
|
103
|
+
if (strong(k)) {
|
|
104
|
+
const w = target(k);
|
|
105
|
+
if (!seen[w]) {
|
|
106
|
+
seen[w] = 1;
|
|
107
|
+
stackEdge[sp] = k + 1;
|
|
108
|
+
sp++;
|
|
109
|
+
stackNode[sp] = w; stackEdge[sp] = this.firstEdge[w];
|
|
110
|
+
pushed = true;
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
k++;
|
|
115
|
+
}
|
|
116
|
+
if (!pushed) {
|
|
117
|
+
post[v] = visited; order[visited++] = v; sp--;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Predecessors (compact layout).
|
|
122
|
+
const predCount = new Uint32Array(n + 1);
|
|
123
|
+
for (let v = 0; v < n; v++) {
|
|
124
|
+
if (!seen[v]) continue;
|
|
125
|
+
for (let k = this.firstEdge[v]; k < this.firstEdge[v + 1]; k++) if (strong(k)) predCount[target(k) + 1]++;
|
|
126
|
+
}
|
|
127
|
+
for (let i = 1; i <= n; i++) predCount[i] += predCount[i - 1];
|
|
128
|
+
const preds = new Uint32Array(predCount[n]);
|
|
129
|
+
const fill = predCount.slice(0, n);
|
|
130
|
+
for (let v = 0; v < n; v++) {
|
|
131
|
+
if (!seen[v]) continue;
|
|
132
|
+
for (let k = this.firstEdge[v]; k < this.firstEdge[v + 1]; k++) if (strong(k)) preds[fill[target(k)]++] = v;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const UNDEF = -1;
|
|
136
|
+
const idom = new Int32Array(n).fill(UNDEF);
|
|
137
|
+
idom[0] = 0;
|
|
138
|
+
const intersect = (a, b) => {
|
|
139
|
+
while (a !== b) {
|
|
140
|
+
while (post[a] < post[b]) a = idom[a];
|
|
141
|
+
while (post[b] < post[a]) b = idom[b];
|
|
142
|
+
}
|
|
143
|
+
return a;
|
|
144
|
+
};
|
|
145
|
+
let changed = true;
|
|
146
|
+
while (changed) {
|
|
147
|
+
changed = false;
|
|
148
|
+
for (let i = visited - 1; i >= 0; i--) {
|
|
149
|
+
const v = order[i];
|
|
150
|
+
if (v === 0) continue;
|
|
151
|
+
let nd = UNDEF;
|
|
152
|
+
for (let p = predCount[v]; p < predCount[v + 1]; p++) {
|
|
153
|
+
const u = preds[p];
|
|
154
|
+
if (idom[u] === UNDEF) continue;
|
|
155
|
+
nd = nd === UNDEF ? u : intersect(u, nd);
|
|
156
|
+
}
|
|
157
|
+
if (nd !== UNDEF && idom[v] !== nd) { idom[v] = nd; changed = true; }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const retained = new Float64Array(n);
|
|
162
|
+
for (let i = 0; i < visited; i++) retained[order[i]] = this.selfSize(order[i]);
|
|
163
|
+
for (let i = 0; i < visited; i++) {
|
|
164
|
+
const v = order[i];
|
|
165
|
+
if (v !== 0 && idom[v] !== UNDEF) retained[idom[v]] += retained[v];
|
|
166
|
+
}
|
|
167
|
+
this.retained = retained;
|
|
168
|
+
this.idom = idom;
|
|
169
|
+
return retained;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = { HeapGraph };
|
package/src/register.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Preloaded into the target process (node --require): writes the heap snapshot.
|
|
3
|
+
// CCS_OUT path of the .heapsnapshot file
|
|
4
|
+
// CCS_DELAY ms before the snapshot (then the process exits); otherwise at program end
|
|
5
|
+
// SIGUSR2 also triggers an on-demand snapshot (not available on Windows).
|
|
6
|
+
|
|
7
|
+
const v8 = require('v8');
|
|
8
|
+
|
|
9
|
+
const out = process.env.CCS_OUT || `closure-scan-${process.pid}.heapsnapshot`;
|
|
10
|
+
let done = false;
|
|
11
|
+
|
|
12
|
+
function snapshot(reason) {
|
|
13
|
+
if (done) return;
|
|
14
|
+
done = true;
|
|
15
|
+
const file = v8.writeHeapSnapshot(out);
|
|
16
|
+
process.stderr.write(`[closure-context-scan] snapshot written (${reason}): ${file}\n`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const delay = Number(process.env.CCS_DELAY);
|
|
20
|
+
if (delay > 0) {
|
|
21
|
+
setTimeout(() => { snapshot(`after ${delay} ms`); process.exit(0); }, delay).unref();
|
|
22
|
+
}
|
|
23
|
+
process.on('beforeExit', () => snapshot('program end'));
|
|
24
|
+
process.on('exit', () => snapshot('exit'));
|
|
25
|
+
process.on('SIGUSR2', () => { done = false; snapshot('SIGUSR2'); });
|
package/src/source.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Static analysis: which variables a function actually uses,
|
|
3
|
+
// and which (often dead) functions use a given variable.
|
|
4
|
+
|
|
5
|
+
const acorn = require('acorn');
|
|
6
|
+
|
|
7
|
+
const FN = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
|
|
8
|
+
const cache = new Map();
|
|
9
|
+
|
|
10
|
+
function parse(source) {
|
|
11
|
+
if (cache.has(source)) return cache.get(source);
|
|
12
|
+
const opts = { ecmaVersion: 'latest', allowReturnOutsideFunction: true, allowHashBang: true, allowAwaitOutsideFunction: true };
|
|
13
|
+
let ast = null;
|
|
14
|
+
for (const sourceType of ['module', 'script']) {
|
|
15
|
+
try { ast = acorn.parse(source, { ...opts, sourceType }); break; } catch { /* try next */ }
|
|
16
|
+
}
|
|
17
|
+
let info = null;
|
|
18
|
+
if (ast) {
|
|
19
|
+
const parents = new Map();
|
|
20
|
+
const fns = [];
|
|
21
|
+
(function walk(node, parent) {
|
|
22
|
+
parents.set(node, parent);
|
|
23
|
+
if (FN.has(node.type)) fns.push(node);
|
|
24
|
+
for (const key of Object.keys(node)) {
|
|
25
|
+
if (key === 'type' || key === 'start' || key === 'end') continue;
|
|
26
|
+
const v = node[key];
|
|
27
|
+
if (Array.isArray(v)) { for (const c of v) if (c && typeof c.type === 'string') walk(c, node); }
|
|
28
|
+
else if (v && typeof v.type === 'string') walk(v, node);
|
|
29
|
+
}
|
|
30
|
+
})(ast, null);
|
|
31
|
+
const lineStarts = [0];
|
|
32
|
+
for (let i = 0; i < source.length; i++) if (source.charCodeAt(i) === 10) lineStarts.push(i + 1);
|
|
33
|
+
info = { ast, parents, fns, lineStarts, source };
|
|
34
|
+
}
|
|
35
|
+
cache.set(source, info);
|
|
36
|
+
return info;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function lineOf(info, offset) {
|
|
40
|
+
let lo = 0, hi = info.lineStarts.length - 1;
|
|
41
|
+
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (info.lineStarts[mid] <= offset) lo = mid; else hi = mid - 1; }
|
|
42
|
+
return lo + 1;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Innermost function containing the position (0-based line/column).
|
|
46
|
+
function functionAt(info, line, column) {
|
|
47
|
+
const offset = (info.lineStarts[line] ?? 0) + column;
|
|
48
|
+
let best = null;
|
|
49
|
+
for (const fn of info.fns) {
|
|
50
|
+
if (fn.start <= offset && offset < fn.end && (!best || fn.end - fn.start < best.end - best.start)) best = fn;
|
|
51
|
+
}
|
|
52
|
+
return best;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function children(node, cb) {
|
|
56
|
+
for (const key of Object.keys(node)) {
|
|
57
|
+
if (key === 'type' || key === 'start' || key === 'end') continue;
|
|
58
|
+
const v = node[key];
|
|
59
|
+
if (Array.isArray(v)) { for (const c of v) if (c && typeof c.type === 'string') cb(c, key, node); }
|
|
60
|
+
else if (v && typeof v.type === 'string') cb(v, key, node);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Names read inside a function (nested functions included).
|
|
65
|
+
// Deliberate over-approximation: better to miss a leak than to blame wrongly.
|
|
66
|
+
function usedNames(fnNode) {
|
|
67
|
+
const names = new Set();
|
|
68
|
+
let dynamic = false;
|
|
69
|
+
(function walk(node) {
|
|
70
|
+
if (node.type === 'Identifier') names.add(node.name);
|
|
71
|
+
if (node.type === 'WithStatement') dynamic = true;
|
|
72
|
+
if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'eval') dynamic = true;
|
|
73
|
+
children(node, (c, key, parent) => {
|
|
74
|
+
if (!parent.computed && key === 'property' && parent.type === 'MemberExpression') return;
|
|
75
|
+
if (!parent.computed && key === 'key' && !parent.shorthand &&
|
|
76
|
+
(parent.type === 'Property' || parent.type === 'MethodDefinition' || parent.type === 'PropertyDefinition')) return;
|
|
77
|
+
walk(c);
|
|
78
|
+
});
|
|
79
|
+
})(fnNode);
|
|
80
|
+
return { names, dynamic };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Node declaring `name` directly in a function's scope (nested functions excluded), or null.
|
|
84
|
+
function declares(scopeNode, name) {
|
|
85
|
+
if (FN.has(scopeNode.type)) {
|
|
86
|
+
const param = scopeNode.params.find((p) => patternHas(p, name));
|
|
87
|
+
if (param) return param;
|
|
88
|
+
}
|
|
89
|
+
let found = null;
|
|
90
|
+
const body = FN.has(scopeNode.type) ? scopeNode.body : scopeNode;
|
|
91
|
+
(function walk(node) {
|
|
92
|
+
if (found) return;
|
|
93
|
+
if (node.type === 'VariableDeclarator' && patternHas(node.id, name)) { found = node; return; }
|
|
94
|
+
if ((node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') && node.id && node.id.name === name) { found = node; return; }
|
|
95
|
+
if (node.type === 'CatchClause' && node.param && patternHas(node.param, name)) { found = node.param; return; }
|
|
96
|
+
if (FN.has(node.type)) return;
|
|
97
|
+
children(node, walk);
|
|
98
|
+
})(body);
|
|
99
|
+
return found;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function patternHas(p, name) {
|
|
103
|
+
if (!p) return false;
|
|
104
|
+
switch (p.type) {
|
|
105
|
+
case 'Identifier': return p.name === name;
|
|
106
|
+
case 'ObjectPattern': return p.properties.some((pr) => patternHas(pr.type === 'RestElement' ? pr.argument : pr.value, name));
|
|
107
|
+
case 'ArrayPattern': return p.elements.some((el) => patternHas(el, name));
|
|
108
|
+
case 'RestElement': return patternHas(p.argument, name);
|
|
109
|
+
case 'AssignmentPattern': return patternHas(p.left, name);
|
|
110
|
+
default: return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Where the variable is declared, and which functions use it.
|
|
115
|
+
function explain(info, fromFn, name) {
|
|
116
|
+
let scope = info.parents.get(fromFn);
|
|
117
|
+
while (scope && !(FN.has(scope.type) || scope.type === 'Program')) scope = info.parents.get(scope);
|
|
118
|
+
let decl = null;
|
|
119
|
+
while (scope && !(decl = declares(scope, name))) {
|
|
120
|
+
scope = info.parents.get(scope);
|
|
121
|
+
while (scope && !(FN.has(scope.type) || scope.type === 'Program')) scope = info.parents.get(scope);
|
|
122
|
+
}
|
|
123
|
+
if (!scope) return null;
|
|
124
|
+
const users = [];
|
|
125
|
+
for (const fn of info.fns) {
|
|
126
|
+
if (fn === scope || fn.start < scope.start || fn.end > scope.end) continue;
|
|
127
|
+
// Only keep functions that read the variable in their own body.
|
|
128
|
+
if (!directlyUses(fn, name)) continue;
|
|
129
|
+
users.push({ name: fnName(info, fn), line: lineOf(info, fn.start) });
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
declaredIn: scope.type === 'Program' ? '(module)' : fnName(info, scope),
|
|
133
|
+
declaredLine: scope.type === 'Program' ? 1 : lineOf(info, scope.start),
|
|
134
|
+
variableLine: lineOf(info, decl.start),
|
|
135
|
+
variableColumn: decl.start - info.lineStarts[lineOf(info, decl.start) - 1] + 1,
|
|
136
|
+
usedBy: users,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function directlyUses(fn, name) {
|
|
141
|
+
let hit = false;
|
|
142
|
+
(function walk(node) {
|
|
143
|
+
if (hit) return;
|
|
144
|
+
if (node !== fn && FN.has(node.type)) return;
|
|
145
|
+
if (node.type === 'Identifier' && node.name === name) { hit = true; return; }
|
|
146
|
+
children(node, (c, key, parent) => {
|
|
147
|
+
if (!parent.computed && key === 'property' && parent.type === 'MemberExpression') return;
|
|
148
|
+
if (!parent.computed && key === 'key' && !parent.shorthand && parent.type === 'Property') return;
|
|
149
|
+
walk(c);
|
|
150
|
+
});
|
|
151
|
+
})(fn);
|
|
152
|
+
return hit;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function fnName(info, fn) {
|
|
156
|
+
if (fn.id) return fn.id.name;
|
|
157
|
+
const p = info.parents.get(fn);
|
|
158
|
+
if (p && p.type === 'VariableDeclarator' && p.id.type === 'Identifier') return p.id.name;
|
|
159
|
+
if (p && (p.type === 'Property' || p.type === 'MethodDefinition') && p.key.type === 'Identifier') return p.key.name;
|
|
160
|
+
if (p && p.type === 'AssignmentExpression' && p.left.type === 'MemberExpression' && p.left.property.type === 'Identifier') return p.left.property.name;
|
|
161
|
+
return '(anonymous)';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
module.exports = { parse, functionAt, usedNames, explain, fnName, lineOf };
|