### Verify Installation Source: https://github.com/facebook/memlab/blob/main/website/docs/installation.md Command to run to verify that the installation succeeded. Shows example output. ```bash $ memlab help memlab: memory leak detector for front-end JS COMMON COMMANDS memlab run --scenario Find memory leaks in web apps Options: --work-dir --headful --full --skip-screenshot --skip-gc --skip-scroll --skip-extra-ops --local-puppeteer --scenario --chromium-binary --protocol-timeout --device --user-agent --disable-xvfb --disable-web-security --rewrite-js --log-script --worker --leak-filter --trace-object-size-above --ignore-leak-cluster-size-below --trace-all-objects --save-trace-as-unclassified-cluster --ml-clustering --ml-linkage-max-dist --ml-clustering-max-df --clean-up-snapshot memlab list List all test scenarios memlab trace --node-id= Report retainer trace of a specific node, use with --nodeId Options: --snapshot --snapshot-dir --engine --node-id --heap-parser-dict-fast-store-size memlab find-leaks Find memory leaks in heap snapshots Options: --baseline --target --final --snapshot-dir --engine --leak-filter --trace-object-size-above --ignore-leak-cluster-size-below --trace-all-objects --save-trace-as-unclassified-cluster --ml-clustering --ml-linkage-max-dist --ml-clustering-max-df --clean-up-snapshot --work-dir --heap-parser-dict-fast-store-size memlab analyze [PLUGIN_OPTIONS] Run heap analysis on heap snapshots. Options: --analysis-plugin --heap-parser-dict-fast-store-size --work-dir memlab help [SUB-COMMANDS] List all MemLab CLI commands or print helper text for a specific command memlab diff-leaks Find new memory leaks by diffing control and test heap snapshots Options: --control-snapshot --control-work-dir --treatment-snapshot --treatment-work-dir --engine --leak-filter --trace-object-size-above --ignore-leak-cluster-size-below --trace-all-objects --save-trace-as-unclassified-cluster --ml-clustering --ml-linkage-max-dist --ml-clustering-max-df --max-cluster-sample-size --trace-contains --heap-parser-dict-fast-store-size --work-dir memlab heap --snapshot Interactive command to explore a single heap snapshot Options: --snapshot --engine --heap-parser-dict-fast-store-size memlab view-heap --snapshot Interactive command to view a single heap snapshot Options: --snapshot --engine --node-id --ml-clustering --work-dir --heap-parser-dict-fast-store-size MISC COMMANDS memlab version Show the versions of all memlab packages installed memlab reset Reset and initialize all directories Options: --work-dir memlab measure --scenario Run test scenario in measure mode Options: --headful --run-num --app --interaction --full --skip-snapshot --skip-screenshot --skip-gc --skip-scroll --skip-extra-ops --run-mode --local-puppeteer --scenario --chromium-binary --protocol-timeout --device --user-agent --disable-xvfb --disable-web-security --rewrite-js --log-script --work-dir memlab warmup --scenario Warm up the target app Options: --headful --app --interaction --run-mode --local-puppeteer --scenario --chromium-binary --protocol-timeout --device --user-agent --disable-xvfb --disable-web-security --skip-warmup --rewrite-js --log-script --work-dir memlab get-default-work-dir Query the default working directory memlab snapshot --scenario Interact with web app and take heap snapshots Options: --headful --app --interaction --full --skip-snapshot --skip-screenshot --skip-gc --skip-scroll --skip-extra-ops --run-mode --local-puppeteer --scenario --chromium-binary --protocol-timeout --device --user-agent --disable-xvfb --disable-web-security --rewrite-js --log-script --worker --work-dir memlab warmup-and-snapshot --scenario Warm up server and take heap snapshots Options: --work-dir --headful --app --interaction --run-mode --local-puppeteer --scenario --chromium-binary --protocol-timeout --device --user-agent --disable-xvfb --disable-web-security --skip-warmup --rewrite-js --log-script --full --skip-snapshot --skip-screenshot --skip-gc --skip-scroll --skip-extra-ops --worker ``` -------------------------------- ### Example Scenario File Source: https://github.com/facebook/memlab/blob/main/website/docs/getting-started.md A JavaScript file defining how memlab interacts with a web page, including navigation and actions. ```javascript // initial page load's url function url() { return "https://www.youtube.com"; } // action where you suspect the memory leak might be happening async function action(page) { await page.click('[id="video-title-link"]'); } // how to go back to the state before action async function back(page) { await page.click('[id="logo-icon"]'); } module.exports = { action, back, url }; ``` -------------------------------- ### Running MemLab Command Source: https://github.com/facebook/memlab/blob/main/website/docs/getting-started.md The command to run memlab with a specified scenario file. ```bash $ memlab run --scenario ~/memlab/scenario.js ``` -------------------------------- ### memlab snapshot examples Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Examples for taking heap snapshots. ```bash memlab snapshot --scenario /tmp/test-scenario.js memlab snapshot --scenario /tmp/test-scenario.js --work-dir /tmp/test-1/ ``` -------------------------------- ### memlab warmup-and-snapshot examples Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Example for warming up the server and taking heap snapshots. ```bash memlab warmup-and-snapshot --scenario /tmp/test-scenario.js ``` -------------------------------- ### Install MemLab Source: https://github.com/facebook/memlab/blob/main/website/docs/installation.md Install MemLab using pip. ```bash pip install facebook-memlab ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/facebook/memlab/blob/main/packages/e2e/static/example/README.md Use npm or yarn to install the necessary project dependencies before running the development server. ```bash npm install ``` ```bash yarn install ``` -------------------------------- ### Install dependencies Source: https://github.com/facebook/memlab/blob/main/website/README.md Install all required project dependencies using Yarn. ```bash $ yarn ``` -------------------------------- ### MemLens E2E Test Setup Source: https://github.com/facebook/memlab/blob/main/packages/lens/README.md Commands to install Playwright dependencies and run end-to-end tests for MemLens. ```bash # Install Playwright dependencies (first time): npx playwright install npx playwright install-deps # Run tests: npm run test:e2e ``` -------------------------------- ### Install MemLab globally Source: https://github.com/facebook/memlab/blob/main/website/docs/installation.md Installs the MemLab command-line interface globally using npm. ```bash npm install -g memlab ``` -------------------------------- ### Install the CLI Source: https://github.com/facebook/memlab/blob/main/README.md Installs the MemLab command-line interface globally. ```bash npm install -g memlab ``` -------------------------------- ### Quick Start: Local Build Injection Source: https://github.com/facebook/memlab/blob/main/packages/lens/README.md Paste the contents of the MemLens run bundle (local build) into the browser's web console to start the overlay. ```APIDOC ## Inject MemLens from Local Build ### Description Copy the content of `packages/lens/dist/memlens.run.bundle.min.js` (or `.js`) and paste it directly into your browser's developer console. This will start the MemLens overlay. ### Method JavaScript snippet execution ### Endpoint N/A (Local file content) ### Request Example ```js // Paste the content of memlens.run.bundle.min.js here // Example: (function() { ... })(); ``` ### Response N/A (In-browser execution) ``` -------------------------------- ### run-meta.json example Source: https://github.com/facebook/memlab/blob/main/website/docs/guides/05-integrate-with-E2E-frameworks.md An example of the `run-meta.json` file, which logs metadata about MemLab's operation. ```json { "app": "default-app-for-scenario", "type": "scenario", "interaction": "test-google-maps.js", "browserInfo": { "_browserVersion": "HeadlessChrome/101.0.4950.0", "_puppeteerConfig": { "headless": true, "devtools": true, "userDataDir": "/tmp/memlab/data/profile", "args": [ "--no-sandbox", "--disable-notifications", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", "--js-flags=\"--no-move-object-start\"", "--enable-precise-memory-info", "browser-test", "--display=:100" ], "defaultViewport": { "width": 1680, "height": 1080, "deviceScaleFactor": 1 } }, "_consoleMessages": [ "console output line 1", "console output line 2" ] }, "extraInfo": { "command": "run --scenario /home/jacksongl/scripts/test-google-maps.js" } } ``` -------------------------------- ### memlab run examples Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Examples of using the memlab run command with different options. ```bash memlab run --scenario /tmp/test-scenario.js ``` ```bash memlab run --scenario /tmp/test-scenario.js --work-dir /tmp/test-1/ ``` -------------------------------- ### memlab help command usage Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Usage example for the memlab help command to get information about other commands. ```bash memlab help [SUB-COMMANDS] ``` -------------------------------- ### Start local development server Source: https://github.com/facebook/memlab/blob/main/website/README.md Launch the local development server to preview changes with live reloading. ```bash $ yarn start ``` -------------------------------- ### Quick Start: CDN Injection Source: https://github.com/facebook/memlab/blob/main/packages/lens/README.md Inject and start MemLens with the interactive overlay by pasting this snippet into your browser's console. ```APIDOC ## Inject MemLens via CDN ### Description This snippet injects the MemLens script from a CDN into the current page, automatically starting the interactive overlay for memory leak visualization. ### Method JavaScript snippet execution ### Endpoint N/A (CDN URL) ### Request Example ```js (() => { const s = document.createElement('script'); s.src = 'https://unpkg.com/@memlab/lens/dist/memlens.run.bundle.min.js'; s.crossOrigin = 'anonymous'; document.head.appendChild(s); })(); ``` ### Response N/A (In-browser execution) ``` -------------------------------- ### Global install Source: https://github.com/facebook/memlab/blob/main/packages/mcp-server/README.md Install the mcp-server globally and configure the MCP server. ```bash npm install -g @memlab/mcp-server ``` ```json { "mcpServers": { "memlab": { "type": "stdio", "command": "memlab-mcp", "env": { "NODE_OPTIONS": "--max-old-space-size=8192" } } } } ``` -------------------------------- ### memlab warmup example Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Example of how to use the memlab warmup command to prepare a target application for testing. ```bash memlab warmup --scenario /tmp/test-scenario.js ``` -------------------------------- ### memlab trace examples Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Examples of using the `memlab trace` command with different node IDs. ```bash memlab trace --node-id=@3123123 memlab trace --node-id=128127 ``` -------------------------------- ### BeforeInitialPageLoad callback example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md Example demonstrating the `beforeInitialPageLoad` callback, which is executed once before the initial page load. ```typescript const scenario = { url: () => 'https://www.npmjs.com/', beforeInitialPageLoad: async (page) => { // before the initial page load }, action: async (page) => { await page.click('a[href="/link"]'); }, back: async (page) => { await page.click('a[href="/back"]'); }, } module.exports = scenario; ``` -------------------------------- ### memlab trace command example Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Example of how to use the `memlab trace` command to report the retainer trace of a specific node. ```bash memlab trace --node-id= ``` -------------------------------- ### memlab measure examples Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Examples of how to use the memlab measure command to analyze web application performance and memory usage. ```bash memlab measure --scenario /tmp/test-scenario.js memlab measure --scenario /tmp/test-scenario.js --work-dir /tmp/test-1/ ``` -------------------------------- ### Run in Node.js Source: https://github.com/facebook/memlab/blob/main/website/docs/guides/04-continuous-test.md Example of invoking memlab APIs from a Node.js test job. ```typescript const {run} = require('@memlab/api'); const scenario = require('/path/to/test/scenario/file.js'); const fs = require('fs-extra'); (async function () { const workDir = '/path/to/save/memlab/run/results/'; // make sure the working directory exists fs.mkdirsSync(workDir); const result = await run({scenario, workDir}); })(); ``` -------------------------------- ### Example Retainer Trace Output Source: https://github.com/facebook/memlab/blob/main/README.md Example output from memlab showing detected memory leaks and their retainer traces. ```text MemLab found 46 leak(s) --Similar leaks in this run: 4-- --Retained size of leaked objects: 8.3MB-- [Window] (native) @35847 [8.3MB] --20 (element)---> [InternalNode] (native) @130981728 [8.3MB] --8 (element)---> [InternalNode] (native) @130980288 [8.3MB] --1 (element)---> [EventListener] (native) @131009888 [8.3MB] --1 (element)---> [V8EventListener] (native) @224808192 [8.3MB] --1 (element)---> [eventHandler] (closure) @168079 [8.3MB] --context (internal)---> [] (object) @181905 [8.3MB] --bigArray (variable)---> [Array] (object) @182925 [8.3MB] --elements (internal)---> [(object elements)] (array) @182929 [8.3MB] ... ``` -------------------------------- ### Basic action and back callback example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md A simple example illustrating the `action` and `back` callbacks within a scenario definition. ```typescript const scenario = { url: () => 'https://www.npmjs.com/', action: async (page) => { await page.click('a[href="/link"]'); }, back: async (page) => { await page.click('a[href="/back"]'); }, } module.exports = scenario; ``` -------------------------------- ### Example takeJSHeapSnapshot API Source: https://github.com/facebook/memlab/blob/main/website/docs/guides/05-integrate-with-E2E-frameworks.md This is an example of how the takeJSHeapSnapshot API might look in your E2E testing framework. ```javascript await takeJSHeapSnapshot(page, tag); ``` -------------------------------- ### memlab find-leaks examples Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Examples of using the memlab find-leaks command with different input specifications. ```bash memlab find-leaks --baseline /tmp/baseline.heapsnapshot --target /tmp/target.heapsnapshot --final /tmp/final.heapsnapshot ``` ```bash memlab find-leaks --snapshot-dir /dir/containing/heapsnapshot/files/ ``` -------------------------------- ### memlab version Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Show the versions of all memlab packages installed. ```bash memlab version ``` -------------------------------- ### IScenario Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md An example of how to define an IScenario object, including the setup function for initial page preparation. ```typescript const scenario = { url: () => 'https://www.npmjs.com/', setup: async (page) => { // log in or prepare data for the interaction }, action: async (page) => { await page.click('a[href="/link"]'); }, back: async (page) => { await page.click('a[href="/back"]'); }, } module.exports = scenario; ``` -------------------------------- ### Example usage of getCommandName Source: https://github.com/facebook/memlab/blob/main/website/docs/api/heap-analysis/src/classes/ObjectUnboundGrowthAnalysis.md Illustrates how to get the command name for a heap analysis. ```typescript const analysis = new YourAnalysis(); const name = analysis.getCommandName(); ``` -------------------------------- ### Run Development Server Source: https://github.com/facebook/memlab/blob/main/packages/e2e/static/example/README.md Start the Next.js development server using npm or yarn to view the project locally. ```bash npm run dev ``` ```bash yarn dev ``` -------------------------------- ### Get browser interaction steps Source: https://github.com/facebook/memlab/blob/main/website/docs/api/api/src/classes/SnapshotResultReader.md Retrieve the sequence of browser interaction steps associated with the snapshot reader. ```javascript const {SnapshotResultReader} = require('@memlab/api'); // baseline, target, and final are file paths of heap snapshot files const reader = SnapshotResultReader.fromSnapshots(baseline, target, final); const paths = reader.getInteractionSteps(); ``` -------------------------------- ### MemLens Manual Test Setup Source: https://github.com/facebook/memlab/blob/main/packages/lens/README.md Instructions for manually testing MemLens by opening a local HTML file or pasting the bundle into the browser's DevTools console. ```bash open `src/tests/manual/todo-list/todo-with-run.bundle.html` in a browser, or copy/paste `dist/memlens.run.bundle.js` to the DevTools console on any React page. ``` -------------------------------- ### Getting a Node by ID Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IHeapSnapshot.md Example of retrieving a specific heap node using its unique ID. ```typescript import type {IHeapSnapshot} from '@memlab/core'; import {dumpNodeHeapSnapshot} from '@memlab/core'; import {getFullHeapFromFile} from '@memlab/heap-analysis'; (async function () { const heapFile = dumpNodeHeapSnapshot(); const heap: IHeapSnapshot = await getFullHeapFromFile(heapFile); const node = heap.getNodeById(351); node?.id; // should be 351 })(); ``` -------------------------------- ### getNodesByIdSet Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IHeapSnapshot.md Shows how to get a set of heap nodes using a set of their IDs, returning only found nodes. ```typescript import type {IHeapSnapshot} from '@memlab/core'; import {dumpNodeHeapSnapshot} from '@memlab/core'; import {getFullHeapFromFile} from '@memlab/heap-analysis'; (async function () { const heapFile = dumpNodeHeapSnapshot(); const heap: IHeapSnapshot = await getFullHeapFromFile(heapFile); // suppose 1000 is not a valid id in the heap const set = heap.getNodesByIdSet(new Set([1, 2, 1000, 3])); set // should be Set([node1, node2, node3]) })(); ``` -------------------------------- ### MemLab npm Package Usage Source: https://github.com/facebook/memlab/blob/main/README.md Example of using the memlab npm package to start an E2E run in the browser and detect memory leaks programmatically. ```javascript const memlab = require('memlab'); const scenario = { // initial page load url url: () => 'https://www.google.com/maps/@37.386427,-122.0428214,11z', // action where we want to detect memory leaks action: async page => await page.click('text/Hotels'), // action where we want to go back to the step before back: async page => await page.click('[aria-label="Close"]'), }; memlab.run({scenario}); ``` -------------------------------- ### Run in CLI Source: https://github.com/facebook/memlab/blob/main/website/docs/guides/04-continuous-test.md Example of running memlab test scenarios via the command line interface. ```bash memlab run --scenario /path/to/test/scenario/file.js \ --work-dir /path/to/save/memlab/run/results/ ``` -------------------------------- ### beforeLeakFilter Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md Example of how to define the beforeLeakFilter callback. ```typescript module.exports = { url: () => ... , action: async (page) => ... , back: async (page) => ... , beforeLeakFilter: (snapshot, leakedNodeIds) => { // initialize some data stores }, }; ``` -------------------------------- ### From source Source: https://github.com/facebook/memlab/blob/main/packages/mcp-server/README.md Build the mcp-server from source and configure the MCP server. ```bash git clone https://github.com/facebook/memlab.git cd memlab npm install npm run build ``` ```json { "mcpServers": { "memlab": { "type": "stdio", "command": "node", "args": ["--max-old-space-size=8192", "/path/to/memlab/packages/mcp-server/dist/index.js"] } } } ``` -------------------------------- ### npx (no install) Source: https://github.com/facebook/memlab/blob/main/packages/mcp-server/README.md Use npx to run the mcp-server without installation and configure the MCP server. ```json { "mcpServers": { "memlab": { "type": "stdio", "command": "npx", "args": ["@memlab/mcp-server"], "env": { "NODE_OPTIONS": "--max-old-space-size=8192" } } } } ``` -------------------------------- ### Include Core Callbacks for Scenarios Source: https://github.com/facebook/memlab/blob/main/AI.md Most scenarios require `url`, `action`, and `back` callbacks. `url` defines the starting page, `action` performs the user interaction, and `back` reverts the state. ```javascript module.exports = { url: () => 'https://example.com', action: async (page) => { await page.click('#button'); }, back: async (page) => { await page.click('#close'); }, }; ``` -------------------------------- ### forEachReferrer Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IHeapNode.md Example of using forEachReferrer to iterate over incoming references to a node. ```typescript node.forEachReferrer((edge: IHeapEdge) => { // process edge ... // if no need to iterate over remaining edges after // the current edge in the node.referrers list return {stop: true}; }); ``` -------------------------------- ### memlab list Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md List all test scenarios. ```bash memlab list ``` -------------------------------- ### forEachReference Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IHeapNode.md Example of using forEachReference to iterate over outgoing references from a node. ```typescript node.forEachReference((edge: IHeapEdge) => { // process edge ... // if no need to iterate over remaining edges after // the current edge in the node.references list return {stop: true}; }); ``` -------------------------------- ### cookies Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md Example of how to define the cookies callback to provide authentication cookies. ```typescript const scenario = { url: () => 'https://www.facebook.com/', cookies: () => [ {name:'cm_j', value: 'none', domain: '.facebook.com'}, {name:'datr', value: 'yJvIY...', domain: '.facebook.com'}, {name:'c_user', value: '8917...', domain: '.facebook.com'}, {name:'xs', value: '95:9WQ...', domain: '.facebook.com'}, // ... ], }; module.exports = scenario; ``` -------------------------------- ### Warmup and Snapshot Command Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Example of using the `memlab warmup-and-snapshot` command to set a working directory and run a scenario. ```bash memlab warmup-and-snapshot --scenario /tmp/test-scenario.js --work-dir /tmp/test-1/ ``` -------------------------------- ### Leak Filter Example Source: https://github.com/facebook/memlab/blob/main/website/docs/guides/02-detect-oversized-object.mdx Example of a leak filter function that can be extracted into its own file. ```jsx const { memlab } = require('memlab'); module.exports = { // Filter out objects larger than 1MB leakFilter: ({ obj }) => { return obj.length > 1024 * 1024; }, }; ``` -------------------------------- ### Build static site Source: https://github.com/facebook/memlab/blob/main/website/README.md Generate static content for production in the build directory. ```bash $ yarn build ``` -------------------------------- ### Example Leak Filter Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/type-aliases/LeakFilterCallback.md An example of a LeakFilterCallback that filters nodes larger than 1MB. ```javascript // any node in the heap snapshot that is greater than 1MB function leakFilter(node, _snapshot, _leakedNodeIds) { return node.retainedSize > 1000000; }; ``` -------------------------------- ### Development Build and Run Source: https://github.com/facebook/memlab/blob/main/README.md Commands to install dependencies, build the project, and run in development mode with automatic compilation. ```bash npm install npm run build ``` ```bash npm run dev ``` -------------------------------- ### repeat Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md Example of a repeat callback that specifies two extra action-back cycles. ```typescript module.exports = { url: () => ... , action: async (page) => ... , back: async (page) => ... , // browser interaction: two additional [ action -> back ] // init-load -> action -> back -> action -> back -> action -> back repeat: () => 2, }; ``` -------------------------------- ### Warmup and Take Snapshots with MemLab API Source: https://github.com/facebook/memlab/blob/main/website/docs/api/api/src/functions/warmupAndTakeSnapshots.md Use this snippet to programmatically warm up a web server, run E2E interactions, and take heap snapshots. Configure browser interaction runs using the options parameter. ```javascript const {warmupAndTakeSnapshots} = require('@memlab/api'); (async function () { const scenario = { url: () => 'https://www.facebook.com', }; const result = await warmupAndTakeSnapshots({scenario}); })(); ``` -------------------------------- ### warmupAndTakeSnapshots Source: https://github.com/facebook/memlab/blob/main/website/docs/api/api/src/functions/warmupAndTakeSnapshots.md Warms up the web server, runs E2E interactions, and takes heap snapshots. ```APIDOC ## warmupAndTakeSnapshots ### Description Warms up the web server, runs E2E interaction, and takes heap snapshots. This is equivalent to running `memlab warmup-and-snapshot` in the CLI. ### Parameters #### options (RunOptions) - Optional - Configuration object for the browser interaction run. ### Returns - **Promise** - A promise that resolves to the browser interaction results. ### Request Example ```javascript const {warmupAndTakeSnapshots} = require('@memlab/api'); (async function () { const scenario = { url: () => 'https://www.facebook.com', }; const result = await warmupAndTakeSnapshots({scenario}); })(); ``` ``` -------------------------------- ### findAnyReferrerNode Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IHeapNode.md Example of using findAnyReferrerNode to find a referring node based on a predicate. ```typescript const referrer = node.findAnyReferrerNode((node: IHeapNode) => { // find the referring node with name "Parent" return node.name === 'Parent'; }); ``` -------------------------------- ### Sample snap-seq.json file Source: https://github.com/facebook/memlab/blob/main/website/docs/guides/05-integrate-with-E2E-frameworks.md A sample snap-seq.json file, which is an array of objects representing browser interaction steps. MemLab requires at least three steps labeled baseline, target, and final, in that order, to detect memory leaks. ```json [{"name": "page-load","snapshot": true,"type": "baseline","idx": 1,"JSHeapUsedSize": 33872820},{"name": "action-on-page","snapshot": true,"type": "target","idx": 2,"JSHeapUsedSize": 44172336},{"name": "revert","snapshot": true,"type": "final","idx": 3,"JSHeapUsedSize": 43304156}] ``` -------------------------------- ### isPageLoaded Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md Example of how to define the isPageLoaded callback for custom page load checks. ```typescript module.exports = { url: () => ... , action: async (page) => ... , back: async (page) => ... , isPageLoaded: async (page) => { await page.waitForNavigation({ // consider navigation to be finished when there are // no more than 2 network connections for at least 500 ms. waitUntil: 'networkidle2', // Maximum navigation time in milliseconds timeout: 5000, }); return true; }, }; ``` -------------------------------- ### Example Usage of ReferenceFilterCallback Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/type-aliases/ReferenceFilterCallback.md An example of how to define a ReferenceFilterCallback to exclude React Fiber references. ```javascript // exclude react fiber references function retainerReferenceFilter(edge, _snapshot, _isReferenceUsedByDefault) { if (edge.name_or_index.toString().startsWith('__reactFiber$')) { return false; } // exclude other references here // ... return true; }; ``` -------------------------------- ### memlab warmup-and-snapshot Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Warm up server and take heap snapshots. This is equivalent to running `memlab warmup` and `memlab snapshot`. ```bash # specify a test scenario file, memlab will warm up the server and take heap snapshots memlab warmup-and-snapshot --scenario ``` -------------------------------- ### memlab snapshot Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Interact with web app and take heap snapshots. ```bash memlab snapshot --scenario ``` -------------------------------- ### getOptions() Source: https://github.com/facebook/memlab/blob/main/website/docs/api/heap-analysis/src/classes/BaseAnalysis.md Retrieves the command line options for the analysis. ```APIDOC ## getOptions() ### Description Override this method to define custom command line options for the analysis. ### Returns - **BaseOption[]** - An array of command line options. ``` -------------------------------- ### URL Callback Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md An example demonstrating the usage of the url callback within an IScenario object. ```typescript const scenario = { url: () => 'https://www.npmjs.com/', }; module.exports = scenario; ``` -------------------------------- ### memlab reset Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Reset and initialize all directories. ```bash memlab reset ``` -------------------------------- ### retainerReferenceFilter Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md Example of a retainerReferenceFilter callback that excludes React Fiber references from the retainer trace. ```javascript // save as leak-filter.js module.exports = { retainerReferenceFilter(edge, _snapshot, _leakedNodeIds) { // exclude react fiber references if (edge.name_or_index.toString().startsWith('__reactFiber$')) { return false; } return true; } }; ``` -------------------------------- ### IHeapNodes Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IHeapNodes.md Example demonstrating how to use the IHeapNodes interface to access and iterate over heap nodes. ```typescript import type {IHeapSnapshot, IHeapNodes} from '@memlab/core'; import {dumpNodeHeapSnapshot} from '@memlab/core'; import {getFullHeapFromFile} from '@memlab/heap-analysis'; (async function () { const heapFile = dumpNodeHeapSnapshot(); const heap: IHeapSnapshot = await getFullHeapFromFile(heapFile); const nodes: IHeapNodes = heap.nodes; nodes.length; nodes.get(0); nodes.forEach((node, i) => { if (stopIteration) { return false; } }); })(); ``` -------------------------------- ### Build search index Source: https://github.com/facebook/memlab/blob/main/website/README.md Run the Algolia docsearch scraper using a Docker container with environment variables. ```bash docker run -it --env-file=.env -e "CONFIG=$(cat /path-to/search-index-config.json | jq -r tostring)" algolia/docsearch-scraper ``` -------------------------------- ### Configure Page Load Leak Scenarios Source: https://github.com/facebook/memlab/blob/main/AI.md Avoid using page.goto() in back() unless specifically testing initial page load leaks, as it creates a new baseline and disrupts standard leak detection. ```javascript // ⚠️ ADVANCED USE CASE ONLY: Testing initial page load leaks // This is an exception to the "no page.goto()" rule, but should be used sparingly // Only use this if you specifically want to test leaks from the initial page load itself module.exports = { url: () => 'https://example.com', // No action() - memlab will detect leaks from initial page load back: async (page) => { // ⚠️ Exception: Using page.goto() here creates a new baseline // This is intentional for page-load leak testing, but breaks normal leak detection await page.goto('about:blank'); // Navigate away to final state }, }; // ✅ BETTER: For most cases, use in-page interactions even for page load testing module.exports = { url: () => 'https://example.com', action: async (page) => { // Test interaction that should clean up page load resources }, back: async (page) => { await page.click('#reset'); // Use in-page interaction instead }, }; ``` -------------------------------- ### Basic back callback example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md A simple example illustrating the `back` callback within a scenario definition. ```typescript const scenario = { url: () => 'https://www.npmjs.com/', action: async (page) => { await page.click('a[href="/link"]'); }, back: async (page) => { await page.click('a[href="/back"]'); }, } ``` -------------------------------- ### leakFilter Example Source: https://github.com/facebook/memlab/blob/main/website/docs/api/core/src/interfaces/IScenario.md Example of a leakFilter callback that identifies nodes with a retained size greater than 1MB as memory leaks. ```typescript module.exports = { url: () => ... , action: async (page) => ... , back: async (page) => ... , leakFilter(node, snapshot, leakedNodeIds) { // any unreleased node (JS heap object) with 1MB+ // retained size is considered a memory leak return node.retainedSize > 1000000; }, }; ``` -------------------------------- ### Configure MemLab MCP Server Source: https://github.com/facebook/memlab/blob/main/AI.md Add this configuration to your MCP client, such as Claude Desktop, to enable heap analysis tools. ```json { "mcpServers": { "memlab": { "command": "npx", "args": ["@memlab/mcp-server"] } } } ``` -------------------------------- ### Warm up and take snapshots Source: https://github.com/facebook/memlab/blob/main/AI.md Warms up the server before capturing heap snapshots. ```typescript import {warmupAndTakeSnapshots} from '@memlab/api'; const result = await warmupAndTakeSnapshots({scenario}); ``` -------------------------------- ### memlab find-leaks command example Source: https://github.com/facebook/memlab/blob/main/website/docs/cli/CLI-commands.md Example of how to use the `memlab find-leaks` command to specify an output working directory. ```bash memlab find-leaks --work-dir /memlab/working/dir/generated/by/memlab/ ``` -------------------------------- ### Running Tests Source: https://github.com/facebook/memlab/blob/main/README.md Command to execute the project's tests. ```bash npm run test ``` -------------------------------- ### Example usage of analyzeSnapshotsInDirectory Source: https://github.com/facebook/memlab/blob/main/website/docs/api/heap-analysis/src/classes/ObjectUnboundGrowthAnalysis.md Demonstrates how to run heap analysis for a series of heap snapshot files and retrieve analysis results. ```typescript const analysis = new ShapeUnboundGrowthAnalysis(); // analysis console output is saved in result.analysisOutputFile const result = await analysis.analyzeSnapshotsInDirectory(snapshotDirectory); // query analysis-specific and structured results const shapes = analysis.getShapesWithUnboundGrowth(); ```