import { Page, CDPSession, Locator } from '@playwright/test';

/** A single reading of the renderer's retained-object counters. */
type Metrics = {
    /** `JSHeapUsedSize` — bytes of live JS heap after collection. */
    heap: number;
    /** `Nodes` — DOM nodes the renderer still holds, attached or not. */
    nodes: number;
    /** `JSEventListeners` — registered listeners across all documents. */
    listeners: number;
    /** `Documents` — live documents, including detached ones. */
    documents: number;
};
/**
 * Open a CDP session for metrics collection.
 *
 * Chromium only: the counters come from the Chrome DevTools Protocol, which
 * Firefox and WebKit do not implement. Leaks are rarely engine-specific, so a
 * Chromium-only guard still catches the overwhelming majority of them.
 */
declare function attachCDP(page: Page): Promise<CDPSession>;
/**
 * Force collection, then read the counters.
 *
 * Collection runs twice on purpose: a single pass intermittently leaves
 * detached subtrees in the node count, which shows up as a flaky reading
 * roughly one time in six.
 */
declare function getPageMetrics(client: CDPSession): Promise<Metrics>;

type SoakSample = {
    iteration: number;
    metrics: Metrics;
};
type SoakResult = {
    /** Reading taken after warmup, before the measured loop. */
    baseline: Metrics;
    /** Reading taken after the last iteration. */
    after: Metrics;
    /** Readings taken during the loop, ending with `after`. */
    samples: SoakSample[];
    iterations: number;
    warmup: number;
};
type SoakOptions = {
    client: CDPSession;
    /** The user flow to repeat. Receives the zero-based iteration index. */
    flow: (iteration: number) => Promise<void>;
    /** Measured iterations. Default 200. */
    iterations?: number;
    /**
     * Flow runs before the baseline reading. Lazy module loading, first-render
     * caches and connection setup all allocate once; letting them happen before
     * the baseline keeps them out of the measurement. Default 5.
     */
    warmup?: number;
    /**
     * Take an intermediate reading every N iterations. Default is an eighth of
     * the run.
     *
     * Readings are cheap next to the two forced collections each one already
     * costs, and resolution is what the counter checks run on: the more stretches
     * between readings there are, the more clearly a leak spread across all of
     * them separates from a step concentrated in one.
     */
    sampleEvery?: number;
};
/**
 * Warm up, take a baseline, run `flow` `iterations` times taking periodic
 * readings, then take a final reading.
 *
 * Nothing is asserted here — pass the result to {@link expectNoLeak} or read
 * the samples yourself. Keeping measurement and judgement separate matters
 * because sensible thresholds are app-specific.
 */
declare function soak({ client, flow, iterations, warmup, sampleEvery, }: SoakOptions): Promise<SoakResult>;
/** Growth of one metric between two consecutive readings. */
type Stretch = {
    /** Iteration the previous reading was taken at. 0 means the baseline. */
    from: number;
    /** Iteration this reading was taken at. */
    to: number;
    delta: number;
};
/**
 * Growth of one metric between each pair of consecutive readings.
 *
 * This is the series the counter checks judge. A leak repeats, so its growth is
 * spread across the whole series. A cache warming up, a global registered
 * lazily on first interaction, or one of the transient listeners Chromium
 * registers and drops a moment later all pile their growth into a single
 * stretch and leave the rest flat.
 */
declare function metricStretches(r: SoakResult, metric: keyof Metrics): Stretch[];
type Halves = {
    /** Growth from baseline to the midpoint sample. */
    first: number;
    /** Growth from the midpoint sample to the final reading. */
    second: number;
    midIteration: number;
};
/**
 * Split one metric's growth at the midpoint of the run.
 *
 * This is how a leak is told apart from a one-off. A per-iteration leak keeps a
 * roughly constant slope, so it grows its second half about as much as its
 * first. Warm-up allocation, lazily registered globals and browser noise all
 * land on one side of the split and leave the other flat.
 *
 * Returns `undefined` when there are too few samples to split.
 */
declare function metricHalves(r: SoakResult, metric: keyof Metrics): Halves | undefined;
/**
 * Heap growth over the second half of the loop, against the first half.
 *
 * The node, listener and document counters miss retention that is none of
 * those things: a stale subscriber callback closing over a component tree, an
 * unbounded cache of plain objects. That only moves the heap, and absolute heap
 * delta is too noisy to bound directly, so {@link checkLeaks} judges the shape
 * of this split instead of the size of the delta.
 *
 * Returns `undefined` when there are too few samples to split.
 */
declare function heapHalves(r: SoakResult): Halves | undefined;

type LeakThresholds = {
    /**
     * DOM nodes allowed to remain above baseline. A fixed allowance behaves
     * better than a percentage on small DOM trees. Default 100.
     */
    nodes?: number;
    /**
     * Event listeners allowed to remain above baseline. Default 0 — listeners
     * are registered deliberately, so an unmatched one is a bug, not noise.
     *
     * Growth still has to appear on both sides of the run to count, so a one-off
     * registration or a browser blip does not trip this at 0.
     */
    listeners?: number;
    /** Documents allowed to remain above baseline. Default 0. */
    documents?: number;
    /**
     * Nodes per iteration the browser charges for text editing, from
     * `calibrateTypingCost`. Added to the node allowance, with 10% slack.
     * Default 0.
     */
    typingCost?: number;
    /**
     * Fraction of first-half heap growth the second half may reach before the
     * curve counts as linear rather than decaying. Default 0.5 — across five
     * frameworks the worst observed healthy ratio was 0.23.
     */
    heapRatio?: number;
    /**
     * Absolute heap slack, so a flow whose heap is already flat is not judged on
     * the ratio between two noise readings. Default 256KB.
     *
     * Note this floor also means the heap check only really bites once first-half
     * growth exceeds twice it — around 200 iterations on a typical app. Shorter
     * runs are effectively counter-only.
     */
    heapNoise?: number;
};
type LeakFinding = {
    metric: 'nodes' | 'listeners' | 'documents' | 'heap';
    /** Growth from baseline to the final reading. Bytes for `heap`. */
    growth: number;
    /** Growth per iteration. */
    perIteration: number;
    /** Growth either side of the midpoint, when there were samples enough to split. */
    halves?: Halves;
    message: string;
};
/**
 * Check a soak result against the thresholds and return what failed.
 *
 * Pure — no assertion library, no throwing. Use this when you want to decide
 * for yourself, or feed the findings into your runner's reporter.
 */
declare function checkLeaks(result: SoakResult, thresholds?: LeakThresholds): LeakFinding[];
/**
 * Throw if a soak run accumulated DOM nodes, listeners, documents or heap.
 *
 * Throws a plain `Error`, which every test runner reports as a failure. The
 * package deliberately does not import an assertion library at runtime: doing
 * so loads a second copy of `@playwright/test` whenever the package is
 * consumed through a link, which Playwright rejects outright.
 */
declare function expectNoLeak(result: SoakResult, thresholds?: LeakThresholds): void;

/**
 * Render a soak result as a fixed-width block for the test log.
 *
 * The intermediate samples are the point: a single delta cannot tell a leak
 * from a cache warming up, but a series of readings shows which one you have.
 */
declare function formatSoak(name: string, r: SoakResult, extra?: {
    typingCost?: number;
}): string;

type TypingGesture = (locator: Locator) => Promise<void>;
/**
 * Measure how many DOM nodes the browser retains per text-editing gesture,
 * independently of the page under test.
 *
 * Chromium charges roughly one node per editing interaction — its own
 * bookkeeping, nothing to do with your framework or your components. A plain
 * `<input>` created with `document.createElement`, never bound to anything,
 * shows the same slope. At a few hundred iterations that swamps any fixed node
 * budget, which is why typing soak tests get written off as flaky.
 *
 * So measure it against exactly such a control input, and hand the number to
 * {@link expectNoLeak} as `typingCost` so it can be budgeted for rather than
 * charged to your code.
 *
 * Call this *before* the baseline reading: the control's own nodes then sit
 * inside the baseline instead of appearing as growth.
 *
 * @param gesture The same typing gesture the flow performs, so the measured
 * cost matches what the flow will incur.
 * @returns Nodes retained per gesture. Never negative.
 */
declare function calibrateTypingCost(page: Page, client: CDPSession, gesture: TypingGesture, rounds?: number): Promise<number>;

export { type Halves, type LeakFinding, type LeakThresholds, type Metrics, type SoakOptions, type SoakResult, type SoakSample, type Stretch, type TypingGesture, attachCDP, calibrateTypingCost, checkLeaks, expectNoLeak, formatSoak, getPageMetrics, heapHalves, metricHalves, metricStretches, soak };
