"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.expectLocatorWithRetry = void 0;
const expectLocatorWithRetry = async (page, item, options) => {
    const { shouldBeVisible = true, totalTimeout = 60000, visibilityTimeout = 10000, maxRetries = 3, } = options || {};
    let attempt = 0;
    const startTime = Date.now();
    while (Date.now() - startTime < totalTimeout && attempt < maxRetries) {
        attempt++;
        try {
            if (options?.preAction) {
                try {
                    await options.preAction();
                }
                catch (preErr) {
                    console.warn(`expectLocatorWithRetry: preAction (attempt ${attempt}) threw and will be retried:`, preErr instanceof Error ? preErr.message : preErr);
                }
            }
            await page.waitForLoadState('domcontentloaded');
            await item.waitFor({
                state: shouldBeVisible ? 'visible' : 'hidden',
                timeout: visibilityTimeout,
            });
            return;
        }
        catch (err) {
            console.log(`Attempt ${attempt} failed for ${item}, retrying...`, err instanceof Error ? err.message : err);
            if (options?.postAction) {
                // Swallow transient errors from the recovery action (e.g.
                // `page.reload()` throwing ERR_CONNECTION_REFUSED while the
                // upstream is restarting). The next loop iteration will retry
                // the visibility check itself, which is what we ultimately
                // care about.
                try {
                    await options.postAction();
                }
                catch (postErr) {
                    console.warn(`expectLocatorWithRetry: postAction (attempt ${attempt}) threw and will be retried:`, postErr instanceof Error ? postErr.message : postErr);
                }
            }
            await page.waitForTimeout(500);
        }
    }
    throw new Error(`Failed to assert visibility locator ${item} after ${attempt} attempts.`);
};
exports.expectLocatorWithRetry = expectLocatorWithRetry;
