Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
/dist/
/dist/packages
/tmp
packages/**/test-results/
packages/**/playwright-report/
lerna-debug.log
build.log
node_modules
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"./packages/api",
"./packages/cli",
"./packages/memlab",
"./packages/mcp-server"
"./packages/mcp-server",
"./packages/playwright"
]
}
21 changes: 21 additions & 0 deletions packages/playwright/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Meta Platforms, Inc. and affiliates.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 48 additions & 0 deletions packages/playwright/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
## memlab Playwright

This is the memlab Playwright integration. It exposes a drop-in `test`
fixture for `@playwright/test` so existing Playwright specs can attach
memlab's memory-leak detection by destructuring a `memlab` parameter.

```ts
import {test, expect} from '@memlab/playwright';

test('closing a modal does not leak', async ({page, memlab}) => {
await page.goto('http://localhost:3000');
await memlab.baseline();
await page.getByRole('button', {name: 'Open'}).click();
await page.getByRole('button', {name: 'Close'}).click();
// target + final snapshots, leak detection, and the soft-assert run
// automatically at teardown. Omit `memlab` from the parameters and
// the fixture never attaches (no CDP session, no cost).
});
```

For the common "run a flow, assert no leaks" pattern, call
`memlab.expectNoLeaks()` — it captures target/final, runs detection, and
throws a trimmed leak summary (not the full retention dict) if any leak
trace survives. Use it when you want a hard assertion mid-test rather
than the teardown soft-assert:

```ts
test('modal close leaves no retained DOM', async ({page, memlab}) => {
await page.goto('http://localhost:3000');
await memlab.baseline();
await page.getByRole('button', {name: 'Open'}).click();
await page.getByRole('button', {name: 'Close'}).click();
await memlab.expectNoLeaks();
});
```

Use `memlab.findLeaks()` only when you need the raw trace list (e.g. to
assert a specific leak is present in a fixture test).

Chromium only — heap snapshots go over CDP, which Playwright exposes
only for Chromium. On Firefox / WebKit the fixture becomes a no-op:
the test still runs and passes, but no leak detection happens. A
`memlab-skip` annotation records the reason. Restrict leak specs to a
Chromium project if you want them to fail loudly elsewhere.

## Online Resources
* [Official Website and Demo](https://facebook.github.io/memlab)
* [Documentation](https://facebook.github.io/memlab/docs/intro)
128 changes: 128 additions & 0 deletions packages/playwright/__tests__/fixture.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import {test, expect} from '@memlab/playwright';
import type {LeakFilterFn} from '@memlab/playwright';
import type {Page} from '@playwright/test';

const BASE = 'http://127.0.0.1:5174';
const retainedSizeFilter: LeakFilterFn = node => node.retainedSize > 100_000;

async function openFixture(page: Page, mode: string): Promise<void> {
await page.goto(`${BASE}/?mode=${mode}`);
await page.waitForSelector('#open');
}

async function triggerLeakCycle(page: Page): Promise<void> {
await page.click('#open');
await page.waitForSelector('#slot');
await page.click('#close');
await page.waitForSelector('#slot', {state: 'detached'});
}

test.describe('configure({leakFilter})', () => {
test('routes user filter through to memlab detection', async ({
page,
memlab,
}) => {
memlab.configure({leakFilter: retainedSizeFilter});
await openFixture(page, 'store-leaky');
await memlab.baseline();
await triggerLeakCycle(page);
const leaks = await memlab.findLeaks();
expect(leaks?.length ?? 0).toBeGreaterThan(0);
});

test('invokes the user callback during detection', async ({
page,
memlab,
}) => {
let calls = 0;
memlab.configure({
leakFilter: () => {
calls += 1;
return true;
},
});
await openFixture(page, 'store-leaky');
await memlab.baseline();
await triggerLeakCycle(page);
await memlab.findLeaks();
expect(calls).toBeGreaterThan(0);
});
});

test.describe('configure() merge semantics', () => {
test('later configure({gc}) preserves an earlier leakFilter', async ({
page,
memlab,
}) => {
let invoked = false;
memlab.configure({
leakFilter: () => {
invoked = true;
return false;
},
});
memlab.configure({gc: {repeat: 1}});
await openFixture(page, 'store-leaky');
await memlab.baseline();
await triggerLeakCycle(page);
await memlab.findLeaks();
expect(invoked).toBe(true);
});
});

test.describe('configure({gc})', () => {
test('accepts a tuned cycle without breaking detection', async ({
page,
memlab,
}) => {
memlab.configure({
leakFilter: retainedSizeFilter,
gc: {repeat: 1, waitBetweenMs: 50, waitAfterMs: 100},
});
await openFixture(page, 'store-leaky');
await memlab.baseline();
await triggerLeakCycle(page);
const leaks = await memlab.findLeaks();
expect(leaks?.length ?? 0).toBeGreaterThan(0);
});
});

test.describe('findLeaks()', () => {
test('returns null when baseline was not captured', async ({
page,
memlab,
}) => {
await openFixture(page, 'store-leaky');
await triggerLeakCycle(page);
const leaks = await memlab.findLeaks();
expect(leaks).toBeNull();
});
});

test.describe('expectNoLeaks()', () => {
test('passes when the flow is clean', async ({page, memlab}) => {
await openFixture(page, 'detached-dom-clean');
await memlab.baseline();
await triggerLeakCycle(page);
await memlab.expectNoLeaks();
});

test('throws with leak summary when leaks are detected', async ({
page,
memlab,
}) => {
await openFixture(page, 'detached-dom-leaky');
await memlab.baseline();
await triggerLeakCycle(page);
const err = await memlab.expectNoLeaks().catch(e => e);
expect(err).toBeInstanceOf(Error);
expect((err as Error).message).toMatch(/memlab detected \d+ leak trace/);
});

test('throws when baseline is missing', async ({page, memlab}) => {
await openFixture(page, 'store-leaky');
const err = await memlab.expectNoLeaks().catch(e => e);
expect(err).toBeInstanceOf(Error);
expect((err as Error).message).toMatch(/baseline\(\)/);
});
});
14 changes: 14 additions & 0 deletions packages/playwright/__tests__/fixtures/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>memlab playwright fixture</title>
</head>
<body>
<div>mode: <span id="mode"></span></div>
<button id="open">open</button>
<button id="close">close</button>
<div id="container"></div>
<script type="module" src="/index.js"></script>
</body>
</html>
80 changes: 80 additions & 0 deletions packages/playwright/__tests__/fixtures/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const container = document.getElementById('container');
const mode =
new URLSearchParams(window.location.search).get('mode') ?? 'none';
document.getElementById('mode').textContent = mode;

function makePayload() {
const arr = new Array(50000);
for (let i = 0; i < arr.length; i++) {
arr[i] = {tag: 'memlab-payload', i, nested: {alive: true}};
}
return arr;
}

const externalStore = {
subs: new Set(),
subscribe(fn) {
this.subs.add(fn);
return () => this.subs.delete(fn);
},
};

const detachedDomStash = [];

function mountSlot(label) {
const slot = document.createElement('div');
slot.id = 'slot';
slot.textContent = label;
container.appendChild(slot);
return slot;
}

const MODES = {
'detached-dom-leaky': () => {
const slot = mountSlot('detached-dom-leaky');
detachedDomStash.push(slot);
return () => container.removeChild(slot);
},
'detached-dom-clean': () => {
const slot = mountSlot('detached-dom-clean');
detachedDomStash.push(slot);
return () => {
container.removeChild(slot);
const i = detachedDomStash.indexOf(slot);
if (i >= 0) detachedDomStash.splice(i, 1);
};
},
'store-leaky': () => {
const payload = makePayload();
const slot = mountSlot('store-leaky');
externalStore.subscribe(() => {
if (payload.length < 0) console.log('x');
});
return () => container.removeChild(slot);
},
'interval-clean': () => {
const payload = makePayload();
const slot = mountSlot('interval-clean');
const id = setInterval(() => {
if (payload.length < 0) console.log('x');
}, 1_000_000);
return () => {
container.removeChild(slot);
clearInterval(id);
};
},
};

let cleanup = null;

document.getElementById('open').addEventListener('click', () => {
if (cleanup) return;
const factory = MODES[mode];
if (factory) cleanup = factory();
});

document.getElementById('close').addEventListener('click', () => {
if (!cleanup) return;
cleanup();
cleanup = null;
});
27 changes: 27 additions & 0 deletions packages/playwright/__tests__/fixtures/server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {createServer} from 'node:http';
import {readFile} from 'node:fs/promises';
import {extname, join} from 'node:path';
import {fileURLToPath} from 'node:url';

const root = fileURLToPath(new URL('.', import.meta.url));
const port = Number(process.env.PORT ?? 5174);
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
};

createServer(async (req, res) => {
const pathname = new URL(req.url, 'http://127.0.0.1').pathname;
const file = join(root, pathname === '/' ? '/index.html' : pathname);
try {
const body = await readFile(file);
res.writeHead(200, {
'content-type': mime[extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
});
res.end(body);
} catch {
res.writeHead(404, {'content-type': 'text/plain'});
res.end('not found');
}
}).listen(port, '127.0.0.1');
19 changes: 19 additions & 0 deletions packages/playwright/__tests__/leaky.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!doctype html>
<html>
<body>
<button id="leak">leak</button>
<button id="cleanup">cleanup</button>
<script>
window.__leaks = [];
document.getElementById('leak').addEventListener('click', () => {
// Allocate retained arrays so memlab has something to find.
for (let i = 0; i < 1000; i++) {
window.__leaks.push(new Array(100).fill({tag: 'memlab-leak-' + i}));
}
});
document.getElementById('cleanup').addEventListener('click', () => {
// Intentionally do NOT clear window.__leaks: simulates a real leak.
});
</script>
</body>
</html>
27 changes: 27 additions & 0 deletions packages/playwright/__tests__/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {defineConfig, devices} from '@playwright/test';
import path from 'path';

const fixtureDir = path.join(__dirname, 'fixtures');

export default defineConfig({
testDir: __dirname,
testMatch: /.*\.spec\.ts$/,
fullyParallel: false,
reporter: [['list'], ['html', {open: 'never'}]],
use: {
trace: 'off',
},
webServer: {
command: 'node server.mjs',
cwd: fixtureDir,
url: 'http://127.0.0.1:5174',
reuseExistingServer: !process.env.CI,
timeout: 60_000,
},
projects: [
{
name: 'chromium',
use: {...devices['Desktop Chrome']},
},
],
});
Loading