debug-heap-profile.js•2.29 kB
const v8 = require('v8');
const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
// Create directory for heap snapshots
const snapshotDir = path.join(__dirname, 'heap-snapshots');
if (!fs.existsSync(snapshotDir)) {
fs.mkdirSync(snapshotDir, { recursive: true });
}
let snapshotCount = 0;
function takeHeapSnapshot(label) {
const filename = path.join(snapshotDir, `heap-${snapshotCount++}-${label}.heapsnapshot`);
const snapshot = v8.writeHeapSnapshot(filename);
const mem = process.memoryUsage();
console.log(`[HEAP] Snapshot ${label} saved to ${filename}`);
console.log(`[HEAP] Memory usage: ${Math.round(mem.heapUsed / 1024 / 1024)}MB / ${Math.round(mem.heapTotal / 1024 / 1024)}MB`);
return filename;
}
// Take initial snapshot
takeHeapSnapshot('initial');
// Run the test with heap profiling
console.log('[HEAP] Starting test process with heap profiling...');
const testProcess = spawn('pnpm', ['vitest', 'tests/unit/languageServer.test.ts', '--', '--run', '--reporter=verbose'], {
env: {
...process.env,
NODE_OPTIONS: '--expose-gc --max-old-space-size=16384',
HEAP_PROFILE: '1'
},
stdio: 'inherit'
});
// Take snapshots periodically
const interval = setInterval(() => {
if (global.gc) {
global.gc();
}
takeHeapSnapshot(`during-${Date.now()}`);
}, 5000);
testProcess.on('close', (code) => {
clearInterval(interval);
takeHeapSnapshot('final');
console.log(`[HEAP] Test process exited with code ${code}`);
// Analyze snapshots
analyzeSnapshots();
});
function analyzeSnapshots() {
console.log('\n[HEAP] Analyzing heap snapshots...');
const files = fs.readdirSync(snapshotDir)
.filter(f => f.endsWith('.heapsnapshot'))
.sort();
if (files.length < 2) {
console.log('[HEAP] Not enough snapshots to compare');
return;
}
console.log(`[HEAP] Found ${files.length} snapshots`);
console.log('[HEAP] To analyze in Chrome DevTools:');
console.log(' 1. Open chrome://inspect');
console.log(' 2. Go to Memory tab');
console.log(' 3. Load the heap snapshots from:');
files.forEach(f => {
console.log(` ${path.join(snapshotDir, f)}`);
});
}