Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): log the onboarding dialog the detector does not recognise
Yudhi Armyndharisbe4b6505d18a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 74518473d..128a4c635 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **An onboarding modal the detector does not recognise now shows up in the logs instead of failing silently** — when the "What's new" probe finds nothing to click, the watcher reports the visible dialog's heading and confirm-button labels once per distinct dialog (`action: onboarding_dialog_unrecognized`), so a renamed or localised modal can be covered via `WWEBJS_ONBOARDING_CONTINUE_LABELS` before WhatsApp unlinks the companion. The watcher also logs when it arms and a summary when it stops at its lifetime cap (both debug). Refs #1072.+## [0.15.0] - 2026-08-09### Addeddiff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 00817062c..deb2c8154 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -509,7 +509,11 @@ once, so the session stops instead of being silently unlinked by WhatsApp about> a container stops Chromium launching at all). If your deployment does get a> localised modal, it is **not** auto-dismissed and the session never reaches `action_required` —> instead it links normally, then drops to `disconnected` with reason `LOGOUT` a few minutes later and-> the device disappears from the phone's Linked devices list. Because that path wipes the stored+> the device disappears from the phone's Linked devices list. That miss is no longer silent: when the+> watcher finds a visible dialog it cannot match, it logs a warning (`action:+onboarding_dialog_unrecognized`) carrying the dialog's heading and button labels — the label to add+> via `WWEBJS_ONBOARDING_CONTINUE_LABELS`, and the heading worth reporting — minutes before the unlink+> would happen. Because that path wipes the stored> credentials, the automatic reconnect comes back with a fresh QR on its own, so the session is> usually already sitting at `qr_ready` rather than needing a manual start. Acknowledge the modal once> in a browser signed in as that account, then scan the QR. It does not recur — the modal is showndiff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 02998d374..640769595 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -9,6 +9,7 @@ import {buildProxyLaunchConfig,loadRemoteMedia,probeOnboardingModal,+ collectDialogDiagnostics,resolveAuthTimeoutMs,wwebjsAckToDeliveryStatus,extractWwebjsCall,@@ -6152,6 +6153,147 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {jest.useRealTimers();}});++ // ── Dialog diagnostics (#1072 follow-up) ─────────────────────────────────────+ // When the probe finds nothing to click, the watcher asks the page what dialogs ARE visible,+ // so a modal whose title or button label the detector does not recognise lands in the logs+ // instead of failing silently until WhatsApp unlinks the companion.++ it('warns once per unique unrecognised dialog, carrying its heading and button labels', async () => {+ jest.useFakeTimers();+ try {+ const { adapter, client, evaluate, onActionRequired } = promoteToReady();++ (client as EventEmitter).emit('authenticated');+ await jest.advanceTimersByTimeAsync(2100);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);++ // Spy AFTER promotion: the reconcile path warns once on its own ('ready event was missed'),+ // which would otherwise pollute the counts this test asserts.+ const logger = (adapter as unknown as { logger: { warn: (m: string, meta?: unknown) => void } }).logger;+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);++ evaluate.mockImplementation((fn: unknown) =>+ fn === probeOnboardingModal+ ? Promise.resolve({ modalPresent: false, dismissed: false })+ : Promise.resolve([{ heading: 'A fresh look for WhatsApp Web', buttons: ['Get started'] }]),+ );++ await jest.advanceTimersByTimeAsync(5100); // first tick seeing the dialog+ expect(warnSpy).toHaveBeenCalledTimes(1);+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringMatching(/dialog/i),+ expect.objectContaining({+ action: 'onboarding_dialog_unrecognized',+ dialogs: [{ heading: 'A fresh look for WhatsApp Web', buttons: ['Get started'] }],+ }),+ );++ await jest.advanceTimersByTimeAsync(5100); // the same dialog again — no repeat warn+ expect(warnSpy).toHaveBeenCalledTimes(1);++ // A different dialog (another step of the flow, or another language) is a new signature.+ evaluate.mockImplementation((fn: unknown) =>+ fn === probeOnboardingModal+ ? Promise.resolve({ modalPresent: false, dismissed: false })+ : Promise.resolve([{ heading: 'Novedades de WhatsApp Web', buttons: ['Continuar'] }]),+ );+ await jest.advanceTimersByTimeAsync(5100);+ expect(warnSpy).toHaveBeenCalledTimes(2);++ // The warning is observational: the session itself must never move on it.+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onActionRequired).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });++ it('does not run the diagnostics collector on a tick that dismissed the modal', async () => {+ jest.useFakeTimers();+ try {+ const { adapter, client, evaluate } = promoteToReady();++ (client as EventEmitter).emit('authenticated');+ await jest.advanceTimersByTimeAsync(2100);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);++ evaluate.mockClear(); // drop the reconcile calls; the default `true` implementation stays+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);+ await jest.advanceTimersByTimeAsync(5100);++ expect(evaluate.mock.calls.filter((call: unknown[]) => call[0] === collectDialogDiagnostics)).toHaveLength(0);+ } finally {+ jest.useRealTimers();+ }+ });++ it('does not run the diagnostics collector when the probe itself fails', async () => {+ jest.useFakeTimers();+ try {+ const { adapter, client, evaluate, onActionRequired } = promoteToReady();++ (client as EventEmitter).emit('authenticated');+ await jest.advanceTimersByTimeAsync(2100);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);++ evaluate.mockClear();+ evaluate.mockRejectedValueOnce(new Error('Execution context was destroyed'));+ await jest.advanceTimersByTimeAsync(5100);++ expect(evaluate.mock.calls.filter((call: unknown[]) => call[0] === collectDialogDiagnostics)).toHaveLength(0);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onActionRequired).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });++ it('logs when the watcher arms and when it stops at the lifetime cap', async () => {+ jest.useFakeTimers();+ try {+ const { adapter, client } = promoteToReady();+ const logger = (adapter as unknown as { logger: { debug: (m: string, meta?: unknown) => void } }).logger;+ const debugSpy = jest.spyOn(logger, 'debug').mockImplementation(() => undefined);++ (client as EventEmitter).emit('authenticated');+ await jest.advanceTimersByTimeAsync(2100);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(debugSpy).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ action: 'onboarding_watcher_started' }),+ );++ await jest.advanceTimersByTimeAsync(5 * 60_000 + 5100);+ expect(debugSpy).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ action: 'onboarding_watcher_stopped', clicks: 0, dialogsSeen: 0 }),+ );+ } finally {+ jest.useRealTimers();+ }+ });++ it('logs and does not call back when the fallback fires after READY was already left', () => {+ const adapter = newAdapter();+ const onActionRequired = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = { onActionRequired };+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.DISCONNECTED;+ const logger = (adapter as unknown as { logger: { debug: (m: string, meta?: unknown) => void } }).logger;+ const debugSpy = jest.spyOn(logger, 'debug').mockImplementation(() => undefined);++ (adapter as unknown as { reportActionRequired: (reason: string) => void }).reportActionRequired(+ 'modal stuck after five clicks',+ );++ // The status a concurrent teardown chose stands; the reason survives as a debug line only.+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect(onActionRequired).not.toHaveBeenCalled();+ expect(debugSpy).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ action: 'onboarding_action_required_suppressed' }),+ );+ });});});@@ -6359,6 +6501,161 @@ describe('probeOnboardingModal (in-page onboarding modal detection)', () => {});});+// The diagnostics half of the watcher (#1072 follow-up): when the probe finds nothing to click, the+// adapter asks what dialogs ARE on screen, so a modal the detector does not recognise — a new title,+// another language — shows up in the logs instead of failing silently. `collectDialogDiagnostics` is+// a self-contained function for the same reason as the probe: it is stringified into the page, and+// being plain means the DOM work is unit-testable here directly.+describe('collectDialogDiagnostics (in-page dialog diagnostics)', () => {+ type FakeEl = {+ tagName: string;+ role: string | null;+ ariaModal: boolean;+ ariaLabel: string | null;+ textContent: string;+ parentElement: FakeEl | null;+ offsetParent: unknown;+ getBoundingClientRect: () => { width: number; height: number };+ getAttribute: (name: string) => string | null;+ };++ const el = (+ textContent: string,+ opts: { tag?: string; role?: string; ariaModal?: boolean; ariaLabel?: string; hidden?: boolean } = {},+ ): FakeEl => {+ const ariaLabel = opts.ariaLabel ?? null;+ return {+ tagName: opts.tag ?? 'DIV',+ role: opts.role ?? null,+ ariaModal: opts.ariaModal ?? false,+ ariaLabel,+ textContent,+ parentElement: null,+ offsetParent: opts.hidden ? null : {},+ getBoundingClientRect: () => (opts.hidden ? { width: 0, height: 0 } : { width: 200, height: 40 }),+ getAttribute: (name: string) => (name === 'aria-label' ? ariaLabel : null),+ };+ };++ /** Wire children to a parent and return the parent, so ancestor walks have something to walk. */+ const nest = (parent: FakeEl, ...children: FakeEl[]): FakeEl => {+ for (const child of children) child.parentElement = parent;+ return parent;+ };++ const install = (all: FakeEl[]): void => {+ (globalThis as unknown as { document: unknown }).document = {+ // Mirror the collector's selectors per comma branch: tag branches match tagName, attribute+ // branches match the corresponding fake field.+ querySelectorAll: (selector: string) => {+ const branches = selector.split(',').map(branch => branch.trim());+ return all.filter(e =>+ branches.some(branch =>+ branch === 'button'+ ? e.tagName === 'BUTTON'+ : branch === '[role="button"]'+ ? e.role === 'button'+ : branch === '[role="dialog"]'+ ? e.role === 'dialog'+ : branch === '[aria-modal="true"]'+ ? e.ariaModal+ : branch === '[role="heading"]'+ ? e.role === 'heading'+ : /^h[1-6]$/.test(branch)+ ? e.tagName === branch.toUpperCase()+ : false,+ ),+ );+ },+ };+ };++ afterEach(() => {+ delete (globalThis as unknown as { document?: unknown }).document;+ });++ it('captures the heading and confirm-button labels of a visible dialog', () => {+ const heading = el('A fresh look for WhatsApp Web', { role: 'heading' });+ const button = el('Get started', { tag: 'BUTTON' });+ const dialog = nest(el('', { role: 'dialog' }), heading, button);+ install([dialog, heading, button]);++ expect(collectDialogDiagnostics()).toEqual([+ { heading: 'A fresh look for WhatsApp Web', buttons: ['Get started'] },+ ]);+ });++ // Chat rows and stray buttons are not dialogs: nothing they carry may be reported, or the log+ // would end up capturing ordinary page content.+ it('returns nothing when nothing on the page is a dialog', () => {+ install([el('Alice12:34What’s new?'), el('Continue', { tag: 'BUTTON' })]);++ expect(collectDialogDiagnostics()).toEqual([]);+ });++ it('ignores a dialog that is not visible', () => {+ const heading = el("What's new on WhatsApp Web", { role: 'heading' });+ const dialog = nest(el('', { role: 'dialog', hidden: true }), heading);+ install([dialog, heading]);++ expect(collectDialogDiagnostics()).toEqual([]);+ });++ it('caps the report at three dialogs', () => {+ const dialogs = [1, 2, 3, 4].map(i => el(`dialog ${i}`, { role: 'dialog' }));+ install(dialogs);++ expect(collectDialogDiagnostics()).toHaveLength(3);+ });++ it('excludes buttons and headings that sit outside the dialog', () => {+ const dialog = el('', { role: 'dialog' });+ install([dialog, el('Continue', { tag: 'BUTTON' }), el('Page title', { role: 'heading' })]);++ expect(collectDialogDiagnostics()).toEqual([{ heading: null, buttons: [] }]);+ });++ it("falls back to the dialog's aria-label when it carries no heading element", () => {+ const button = el('Continue', { tag: 'BUTTON' });+ const dialog = nest(el('', { ariaModal: true, ariaLabel: "What's new on WhatsApp Web" }), button);+ install([dialog, button]);++ expect(collectDialogDiagnostics()).toEqual([{ heading: "What's new on WhatsApp Web", buttons: ['Continue'] }]);+ });++ // Captured page text goes straight into the logs: a newline in it would forge extra log lines.+ it('strips control characters so captured text cannot forge log lines', () => {+ const heading = el("What's new\non WhatsApp Web\r\n", { role: 'heading' });+ const dialog = nest(el('', { role: 'dialog' }), heading);+ install([dialog, heading]);++ expect(collectDialogDiagnostics()).toEqual([{ heading: "What's new on WhatsApp Web", buttons: [] }]);+ });++ it('truncates over-long captured text', () => {+ const heading = el('x'.repeat(200), { role: 'heading' });+ const dialog = nest(el('', { role: 'dialog' }), heading);+ install([dialog, heading]);++ const [report] = collectDialogDiagnostics();+ expect(report.heading).toHaveLength(80);+ });++ // Association walks up from the candidate, bounded, so a heading anywhere on the page is not+ // attributed to a dialog it merely shares a distant ancestor with.+ it('associates content only within a bounded ancestor walk', () => {+ const heading = el("What's new on WhatsApp Web", { role: 'heading' });+ let node = heading;+ for (let i = 0; i < 13; i++) {+ node = nest(el('wrapper'), node);+ }+ const dialog = nest(el('', { role: 'dialog' }), node);+ install([dialog, heading]);++ expect(collectDialogDiagnostics()).toEqual([{ heading: null, buttons: [] }]);+ });+});+// WhatsApp Web has no dedicated channel for account standing: a ToS block arrives as a WAState// string on the same generic `disconnected` event as an unlink, a takeover or a version mismatch.// These tests pin which of those twelve states the adapter is willing to call a restriction, becausediff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 56cebdc5a..099acf797 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -71,6 +71,7 @@ import { WwebjsCatalog } from './wwebjs-catalog';import { isSupportedProxyUrl, buildProxyLaunchConfig } from './wwebjs-proxy';import {probeOnboardingModal,+ collectDialogDiagnostics,resolveOnboardingContinueLabels,ONBOARDING_DEFAULT_CONTINUE_LABEL,} from './wwebjs-onboarding';@@ -223,7 +224,7 @@ export { isSupportedProxyUrl, buildProxyLaunchConfig } from './wwebjs-proxy';// The onboarding-modal probe moved to ./wwebjs-onboarding with its label resolution; re-exported// because existing callers (the adapter spec) still import it from here.-export { probeOnboardingModal } from './wwebjs-onboarding';+export { probeOnboardingModal, collectDialogDiagnostics } from './wwebjs-onboarding';export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngine {private client: Client | null = null;@@ -252,6 +253,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// How many times we have clicked the modal's Continue button. Not reset by clearOnboardingWatcher:// it counts for the engine's lifetime, which is what makes "the click is not landing" detectable.private onboardingDismissClicks = 0;+ // Dialog signatures the watcher already warned about (#1072 follow-up). A signature is the+ // serialized diagnostics of what is on screen, so the warn fires once per DISTINCT unrecognised+ // dialog instead of once per 5s tick. Dies with the engine, exactly like the watcher itself.+ private onboardingDialogSignatures = new Set<string>();+ // Probe ticks run, for the lifetime-cap summary line.+ private onboardingProbes = 0;/** How long a received call's handle stays rejectable. Calls ring for roughly a minute, so* two minutes covers the ringing window with margin without pinning dead calls for long. */private static readonly LIVE_CALL_TTL_MS = 2 * 60_000;@@ -1246,6 +1253,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (this.onboardingWatcherStarted) return; // idempotent: ready event + reconcile path share one funnelthis.onboardingWatcherStarted = true;this.onboardingWatcherStartedAt = Date.now();+ this.logger.debug('Onboarding modal watcher armed', {+ sessionId: this.config.sessionId,+ action: 'onboarding_watcher_started',+ });const tick = (): void => {if (!this.client || this.status !== EngineStatus.READY || this.tearingDown || this.disconnectReported) {@@ -1254,6 +1265,16 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}// The modal is one-shot per account: stop after the lifetime cap rather than polling forever.if (Date.now() - this.onboardingWatcherStartedAt >= ONBOARDING_MODAL_MAX_LIFETIME_MS) {+ // Natural end of the episode: one summary, so a log read can tell the watcher ran and what+ // it saw without per-tick noise. Teardown/disconnect stops log nothing — that is shutdown,+ // not signal.+ this.logger.debug('Onboarding modal watcher stopped at its lifetime cap', {+ sessionId: this.config.sessionId,+ probes: this.onboardingProbes,+ clicks: this.onboardingDismissClicks,+ dialogsSeen: this.onboardingDialogSignatures.size,+ action: 'onboarding_watcher_stopped',+ });this.clearOnboardingWatcher();return;}@@ -1283,9 +1304,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin*/private async dismissOnboardingModalIfNeeded(): Promise<void> {if (!this.client) return;+ this.onboardingProbes += 1;const page = (this.client as unknown as {- pupPage?: { evaluate: <T, A>(fn: (arg: A) => T, arg: A) => Promise<T> };+ pupPage?: { evaluate: <T, A>(fn: (arg: A) => T, arg?: A) => Promise<T> };}).pupPage;@@ -1307,6 +1329,32 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}),]);+ // The probe found nothing to click: ask the page what dialogs ARE on screen, so a modal whose+ // title or button label the detector does not recognise is visible in the logs instead of+ // failing silently until WhatsApp unlinks the companion (#1072 follow-up). The `=== false`+ // dispatch is deliberate: a probe that clicked (dismissed) needs no diagnostics, and an+ // absent/garbled result says the page is in no state to answer a second evaluate either.+ if (result && result.dismissed === false) {+ const dialogs = await page?.evaluate(collectDialogDiagnostics);+ if (Array.isArray(dialogs) && dialogs.length > 0) {+ const signature = JSON.stringify(dialogs);+ if (!this.onboardingDialogSignatures.has(signature)) {+ this.onboardingDialogSignatures.add(signature);+ this.logger.warn(+ 'A visible dialog on WhatsApp Web matches neither the onboarding-modal heading nor a ' ++ 'confirm-button label. If this is the onboarding screen in an unrecognised title or ' ++ 'language, WhatsApp will unlink this companion within minutes: add its confirm-label ' ++ 'via WWEBJS_ONBOARDING_CONTINUE_LABELS, and report the heading so detection can cover it.',+ {+ sessionId: this.config.sessionId,+ dialogs,+ action: 'onboarding_dialog_unrecognized',+ },+ );+ }+ }+ }+if (!result?.dismissed) return;// We clicked. A modal that is really dismissed is gone by the next tick, so a click here is@@ -1344,7 +1392,16 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate reportActionRequired(reason: string): void {this.clearOnboardingWatcher();- if (this.status !== EngineStatus.READY) return; // already leaving READY; don't override a teardown/failure+ if (this.status !== EngineStatus.READY) {+ // A teardown/failure latched first: its status stands and the callback stays silent — but the+ // reason must not vanish without a trace, or this path is indistinguishable from "no modal".+ this.logger.debug('Onboarding modal fallback superseded by a status change; not moving to ACTION_REQUIRED', {+ sessionId: this.config.sessionId,+ status: this.status,+ action: 'onboarding_action_required_suppressed',+ });+ return;+ }this.setStatus(EngineStatus.ACTION_REQUIRED);this.callbacks.onActionRequired?.(reason);this.logger.warn(reason, { sessionId: this.config.sessionId, action: 'onboarding_modal_fallback' });diff --git a/src/engine/adapters/wwebjs-onboarding.ts b/src/engine/adapters/wwebjs-onboarding.tsindex d47486550..085e23aff 100644--- a/src/engine/adapters/wwebjs-onboarding.ts+++ b/src/engine/adapters/wwebjs-onboarding.ts@@ -75,3 +75,71 @@ export function probeOnboardingModal(options?: { labels?: string[]; headingOptio}return { modalPresent: false, dismissed: false };}++/**+ * In-page diagnostics for the onboarding watcher (#1072 follow-up): when {@link probeOnboardingModal}+ * finds nothing to click, report what dialogs ARE on screen, so a modal the detector does not+ * recognise — a title WhatsApp changed, another language — shows up in the logs instead of failing+ * silently until the companion is unlinked. Observational only: it clicks nothing and changes+ * nothing, and the adapter logs the result once per distinct answer.+ *+ * Scoped to dialog containers on purpose. The heading text of a `[role="dialog"]` is UI chrome; a+ * chat-list row is not a dialog, so ordinary conversation content never enters the report. The+ * probe's own comment documents why treating page text as a MATCH signal is dangerous — nothing+ * here is a match signal, but the capture is still bounded (three dialogs, five buttons each,+ * truncated strings) so a pathological page cannot flood the logs.+ *+ * Every captured string is sanitized: the text goes straight into a log line, and a newline or+ * control character in page-controlled text would forge extra log entries.+ *+ * Self-contained like the probe: `page.evaluate` stringifies this into the browser, so nothing may+ * be closed over — every constant lives in the body — and being a plain function keeps the DOM work+ * unit-testable.+ */+export function collectDialogDiagnostics(): Array<{ heading: string | null; buttons: string[] }> {+ const MAX_DIALOGS = 3;+ const MAX_BUTTONS_PER_DIALOG = 5;+ const ASSOCIATION_WALK = 12;+ const HEADING_TEXT_MAX = 80;+ const BUTTON_LABEL_MAX = 40;++ const clean = (text: string, max: number): string =>+ text+ // eslint-disable-next-line no-control-regex+ .replace(/[\x00-\x1F\x7F]+/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, max);+ const isVisible = (el: Element): boolean => {+ const rect = (el as HTMLElement).getBoundingClientRect();+ return rect.width > 0 && rect.height > 0 && (el as HTMLElement).offsetParent !== null;+ };+ // Association walks UP from the candidate, bounded, so a heading or button anywhere on the page+ // is never attributed to a dialog it merely shares a distant ancestor with.+ const within = (el: Element, ancestor: Element): boolean => {+ let scope: Element | null = el.parentElement;+ for (let depth = 0; depth < ASSOCIATION_WALK && scope; depth++, scope = scope.parentElement) {+ if (scope === ancestor) return true;+ }+ return false;+ };++ const dialogs = Array.from(document.querySelectorAll('[role="dialog"], [aria-modal="true"]'))+ .filter(isVisible)+ .slice(0, MAX_DIALOGS);+ if (dialogs.length === 0) return [];+ const headings = Array.from(document.querySelectorAll('[role="heading"], h1, h2, h3, h4, h5, h6')).filter(isVisible);+ const buttons = Array.from(document.querySelectorAll('button, [role="button"]')).filter(isVisible);++ return dialogs.map(dialog => {+ const headingEl = headings.find(h => within(h, dialog));+ const rawHeading = headingEl ? headingEl.textContent : dialog.getAttribute('aria-label');+ const heading = rawHeading ? clean(String(rawHeading), HEADING_TEXT_MAX) : '';+ const labels = buttons+ .filter(b => within(b, dialog))+ .map(b => clean(b.textContent || '', BUTTON_LABEL_MAX))+ .filter(label => label.length > 0)+ .slice(0, MAX_BUTTONS_PER_DIALOG);+ return { heading: heading || null, buttons: labels };+ });+}