/**
 * @license
 * Copyright 2025 ReverseCraft
 * SPDX-License-Identifier: Apache-2.0
 */
import{logger as t}from"./logger.js";export class WaitForHelper{#t=new AbortController;#e;#o;#a;#r;#i;constructor(t,e,o){this.#o=3e3*e,this.#a=100*e,this.#r=100*e,this.#i=3e3*o,this.#e=t}async waitForStableDom(){const t=await this.#e.evaluateHandle(t=>{let e;function o(){clearTimeout(e),e=setTimeout(()=>{a.resolver.resolve(),a.observer.disconnect()},t)}const a={resolver:Promise.withResolvers(),observer:new MutationObserver(o)};return o(),a.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),a},this.#a);return this.#t.signal.addEventListener("abort",async()=>{try{await t.evaluate(t=>{t.observer.disconnect(),t.resolver.resolve()}),await t.dispose()}catch{}}),Promise.race([t.evaluate(async t=>await t.resolver.promise),this.timeout(this.#o).then(()=>{throw new Error("Timeout")})])}async waitForNavigationStarted(){const t=new Promise(t=>{const e=e=>{["historySameDocument","historyDifferentDocument","sameDocument"].includes(e.navigationType)?t(!1):t(!0)};this.#e._client().on("Page.frameStartedNavigating",e),this.#t.signal.addEventListener("abort",()=>{t(!1),this.#e._client().off("Page.frameStartedNavigating",e)})});return await Promise.race([t,this.timeout(this.#r).then(()=>!1)])}timeout(t){return new Promise(e=>{const o=setTimeout(e,t);this.#t.signal.addEventListener("abort",()=>{e(),clearTimeout(o)})})}async waitForEventsAfterAction(e){const o=this.waitForNavigationStarted().then(t=>{if(t)return this.#e.waitForNavigation({timeout:this.#i,signal:this.#t.signal})}).catch(e=>t(e));try{await e()}catch(t){throw this.#t.abort(),t}try{await o,await this.waitForStableDom()}catch(e){t(e)}finally{this.#t.abort()}}}