diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95c621e..f929a35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,13 @@ jobs: - name: Install dependencies run: npm ci + # Browser tests (tests/browser) run the in-page scroll/expand/session/navigation code + # against local fixtures in headless Chromium. Only the headless shell is needed. + # `npm exec --no` uses the locally installed Playwright and never fetches from the registry. + # Do not copy this step into release.yml's publish job (it holds id-token: write). + - name: Install Chromium (headless shell) for browser tests + run: npm exec --no -- playwright install --with-deps --only-shell chromium + - name: Type check run: npm run typecheck diff --git a/.gitignore b/.gitignore index c778c87..3b5ccec 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ dist/ /output/ *.log coverage/ +.DS_Store # Local scratch. Never committed. .local/ diff --git a/AGENTS.md b/AGENTS.md index 5128c34..61483fc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,13 +15,14 @@ npm run dev -- scrape '' [options] # Run CLI directly (single-quote URLs!) npm run dev -- auth # Authenticate with Google (opens browser) npm run dev -- auth status # Check if signed in npm run build # Build to dist/ via tsup (ESM, shebang) -npm test # Run all tests (vitest) +npm test # Run all tests (vitest) – needs Chromium (browser tests) +npm run test:browser # Only the headless-browser tests (tests/browser) npm run test:watch # Watch mode npx vitest run tests/parser.test.ts # Run a single test file npm run typecheck # Type check without emitting npm run check:pack # Assert the tarball contract (dist present, no src/tests) npm run test:package # Pack + install into a temp consumer, assert --version -npx playwright install chromium # Required once before first scrape +npx playwright install chromium # Required once before first scrape and before `npm test` # Release (see "Release and publishing" below) node scripts/release.mjs patch|minor|major # Prepare: stamp package.json + lock (the workflow opens the bump PR) @@ -97,15 +98,15 @@ CLI (src/index.ts) ─── commander routes to 4 commands: │ validate (schema check), auth (Google sign-in) │ ├── src/commands/scrape.ts ── wraps scrapeLocation + retry + output -├── src/commands/batch.ts ── reads URL file, rate limiting, resume state, per-location timeout +├── src/commands/batch.ts ── reads URL file, rate limiting, resume state; runBatchLocations() (injected scrape) runs each place under runWithTimeout() ├── src/commands/validate.ts ── Zod schema validation of JSON files └── src/commands/auth.ts ── login (headed), status (headless), logout (delete profile) src/scraper/scrape-location.ts ── shared orchestrator, accepts ParsedUrl (used by both commands); delegates final payload construction to exported pure helper `assembleScrapeResult()` which reconciles `business.totalReviews` with `reviews.length` │ -├── browser.ts ── persistent Chromium context (~/.revcli/chrome-profile/), anti-detection, SIGINT cleanup -├── auth.ts ── isSignedIn(), hasLimitedView(), waitForUserAuth(), waitForSignIn(), waitForBrowserClose() – Google auth detection; decideSignedIn()/GOOGLE_AUTH_COOKIES make the cookie check authoritative -├── navigator.ts ── orchestrates state eviction → consent → locale → limited-view check → tab → sort; verifies loaded placeId against parsed.placeId +├── browser.ts ── persistent Chromium context (~/.revcli/chrome-profile/), anti-detection, browserLaunchOptions(), tracking + closeAllBrowsers(), closeOnAbort()/withBrowserSession(), installBrowserShutdown() +├── auth.ts ── getSessionState()/decideSessionState() (single source of truth for the Google session), hasLimitedView(), authRequiredError()/authRequiredMessage(), waitForUserAuth(), waitForSignIn(), waitForBrowserClose() +├── navigator.ts ── orchestrates state eviction → short-link redirect wait → consent → locale → tab (limited-view check before and after the review cards load) → sort; verifies loaded placeId against parsed.placeId ├── consent.ts ── Google consent handling, hl=en enforcement, g_ep/entry stripping ├── business-extractor.ts ── business name/rating/totalReviews/address extraction; page.evaluate() returns raw DOM strings only, parsing happens Node-side via parseReviewCount + parseRatingText; PII-scrubbed debug logging of candidate strings ├── scroller.ts ── mouse wheel scrolling, deduplication by review ID, exponential backoff stale-scroll detection, loading spinner awareness @@ -117,11 +118,15 @@ src/scraper/scrape-location.ts ── shared orchestrator, accepts ParsedUrl (u src/core/ ├── schema.ts ── Zod schemas + SortOrder/OutputFormat union types + SORT_ORDERS/OUTPUT_FORMATS constants ├── retry.ts ── withRetry() – exponential backoff, isUnrecoverable() detection (instanceof UnrecoverableError + substring fallback) -├── errors.ts ── UnrecoverableError typed class with `kind` discriminator – prefer over magic-substring Error for anything we throw -└── rate-limiter.ts ── minimum delay between operations +├── errors.ts ── UnrecoverableError typed class with a `kind: UnrecoverableKind` union, hasUnrecoverableKind() – prefer over magic-substring Error for anything we throw +├── fatal.ts ── reportFatalError() – the top-level handler index.ts installs; describeFatalError() decides what it prints (message without Playwright call log; stack at debug only); re-exports safeErrorMessage() +├── rate-limiter.ts ── minimum delay between operations +├── timeout.ts ── runWithTimeout() – a time limit that aborts the task, waits for it to settle, then rejects LOCATION_TIMEOUT (BROWSER_NOT_CLOSED past the grace) +└── shutdown.ts ── installShutdownHandlers() (SIGHUP/SIGINT/SIGTERM → abort shutdownSignal, close browsers, exit 129/130/143) src/output/ ├── write.ts ── writeOutput() – centralized format dispatch +├── atomic.ts ── writeFileAtomic() – random temp name (`wx`) + rename, used by both writers ├── json.ts ── pretty JSON to file or stdout └── csv.ts ── CSV with formula injection protection (includes author_url column) @@ -138,10 +143,10 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la ### Patterns to know - **Persistent browser profile**: `launchBrowser()` uses `chromium.launchPersistentContext()` with `~/.revcli/chrome-profile/`. Google auth cookies survive between CLI runs. The `PROFILE_DIR` constant is exported from `browser.ts`. `ensureProfileDir()` in `browser.ts` creates the directory with owner-only `0700` permissions – it is a **credential store** holding your Google session cookies, so it must never be shared, backed up, or committed. The profile's spoofed user-agent and `navigator.webdriver` masking are ToS-sensitive (see the anti-automation note in README's Legal notice); removing them would break unauthenticated scraping. -- **Authentication flow**: Google Maps shows a "limited view" (no Reviews tab) to unauthenticated EEA users. `revcli auth` opens a browser for manual sign-in and never short-circuits on an existing session – the window stays open (until the user closes it) so the profile can be switched to a different account. The scrape command also detects limited view inline and can prompt for auth in headed mode. -- **Cookie-authoritative sign-in detection**: `auth.ts` defines `GOOGLE_AUTH_COOKIES` (the definitive set of Google session cookies: SID/HSID/SSID/APISID/SAPISID/`__Secure-*PSID`). `decideSignedIn(cookieCheckSucceeded, hasAuthCookies, signInButtonVisible)` treats a successful cookie check as authoritative – when `cookieCheckSucceeded` is true, `hasAuthCookies` decides, and the DOM "Sign in" button is only a fallback when the cookie check failed. `hasGoogleAuthSession()` checks the cookie set directly; `waitForSignIn()` polls and throws a typed `UnrecoverableError` with kind `"AUTH_POLL"` on timeout, returning `SignInOutcome` (`"signed-in"` | `"browser-closed"`) otherwise – `waitForUserAuth()` treats a closed window as fatal for the scrape, while `revcli auth` reports it as a normal end. `waitForBrowserClose()` resolves once the window is gone, polling `pages()` as well as the `close` event because closing the last window on macOS leaves the process (and context) alive. +- **Authentication flow**: Google Maps shows a "limited view" to signed-out EEA users and to profiles whose saved session has expired: the Reviews tab is still there but only ~5 reviews load, a "You're seeing a limited view of Google Maps" banner appears, and Sort opens a "Sign-in to get the best of Google Maps" dialog. **The scrape decides from these limited-view signals (banner + Sort sign-in dialog), not from session state**, because non-EEA signed-out users get the full view – do not "simplify" this to a session check. `openReviewsTab()` checks the banner twice (after the tabs, and again after the review cards, since it can render late and `relevant` has no Sort click); `setSortOrder()` waits for the first *visible* of the sort menu or `SELECTORS.signInDialog`. Both throw `authRequiredError()` (`UnrecoverableError` kind `"AUTH_REQUIRED"`, never retried). `scrapeLocation()` delegates to the exported, fake-tested `navigateWithAuthFallback()`: headless rethrows at once; headed runs `waitForUserAuth()` and navigates again, **using the second navigation's business info**. A terminal `AUTH_REQUIRED` is reworded by a 5 s session probe: `authRequiredMessage()` gives the "run `revcli auth`" text for `expired`/`signed-out`/unknown and a "appears to be signed in" text for `signed-in`/`unconfirmed`, so `auth status` and the scrape cannot contradict each other silently. Session state is only used to word that error and to detect sign-in completion. `revcli auth` opens a browser for manual sign-in and never short-circuits on a real session – for `signed-in`/`unconfirmed` the window stays open until the user closes it (#24, account switching); for `expired` it says so and waits for a fresh sign-in, closing on detection. +- **Session state (single source of truth)**: `getSessionState(page, { timeoutMs, stableMs })` in `auth.ts` returns `SessionState` (`"signed-in" | "expired" | "signed-out" | "unconfirmed"`) and is used by `auth`, `auth status` and `waitForSignIn()`; there is no second "is signed in" check. It reads the `.google.com` cookies (`GOOGLE_AUTH_COOKIES`: SID/HSID/SSID/APISID/SAPISID/`__Secure-*PSID`/`__Secure-*PAPISID`) – no auth cookies is a fast `signed-out` – then waits (default 15 s) for an account marker: `SELECTORS.accountButton` (`a[href^="https://accounts.google.com/SignOutOptions"]`) vs `SELECTORS.signInLink` (`…/ServiceLogin`). Markers are matched by **href, never aria-label**: hrefs are language-independent, while labels are localized and the account label holds the user's name and email. Cookies prove a session *exists*, not that Google *accepts* it – a dead session keeps its cookies and shows "Sign in", which `decideSessionState()` (pure, exported) maps to `expired`. With auth cookies a "Sign in" link must stay the only marker for `stableMs` because Google can render it briefly on a valid session – `SESSION_SIGN_IN_STABLE_MS` (3 s, the default, for `auth` and `auth status`, which report once) and `POLL_SIGN_IN_STABLE_MS` (1.5 s, in `POLL_PROBE`, for the sign-in poll loop and the scrape's error wording, which simply ask again); the account link always wins; no stable marker in time → `unconfirmed` (trusted with a warning by `auth`/`auth status`; `waitForSignIn()` keeps polling). The marker read swallows every Playwright error and never logs error text, element HTML or labels (Playwright call logs print markup). `waitForSignIn()` takes an injectable `probe` (defaults to `getSessionState` with `POLL_PROBE`: 5 s marker wait, 1.5 s stability; `tests/browser/session.test.ts` also runs it with the real probe), returns `"signed-in"` only when the probe says so, throws `UnrecoverableError` kind `"AUTH_POLL"` on timeout, and returns `SignInOutcome` (`"signed-in"` | `"browser-closed"`) – `waitForUserAuth()` treats a closed window as fatal for the scrape, while `revcli auth` reports it as a normal end. `waitForBrowserClose()` resolves once the window is gone, polling `pages()` as well as the `close` event because closing the last window on macOS leaves the process (and context) alive. - **Default headed mode**: The browser shows by default so users can observe scraping. Use `--headless` to hide it. This is the opposite of most scrapers – it's intentional because auth requires a visible browser. -- **URL normalization**: `appendHlParam()` in `consent.ts` always forces `hl=en` and strips `g_ep`/`entry` tracking params that trigger Google's limited view. This runs before every navigation. +- **URL normalization**: `appendHlParam()` in `consent.ts` always forces `hl=en` and strips `g_ep`/`entry` tracking params that trigger Google's limited view. This runs before every navigation. After the page has landed (redirects, consent), `ensureEnglishLocale()` navigates again when the *parsed* query has `hl` other than exactly `en` (pure helper `englishLocaleTarget()`). Only for short-link input (`stripLimitedViewParams: parsed.isShortUrl`) it also navigates to strip `entry`/`g_ep`, because that is the one case where they could not be stripped before the load; on other links Google's own page script may add them back, and re-checking would cost a second page load on every scrape. - **Centralized selectors**: All Google Maps CSS class selectors live in `src/scraper/selectors.ts`. Google obfuscates these names and changes them periodically. When scraping breaks, check selectors first. See [docs/selector-maintenance.md](docs/selector-maintenance.md) for the full update procedure. - **Mouse wheel scrolling**: Google Maps' virtualized review list only lazy-loads from real scroll events. `page.mouse.wheel()` triggers it; `scrollTop` alone does not. - **Zod as source of truth**: Types are derived from Zod schemas via `z.infer<>`. The `parseReview()` function validates every review at the boundary before it enters the output. @@ -149,7 +154,8 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - **Batch resume**: `.revcli-state.json` in the output directory tracks completed URLs (Zod-validated, atomic writes). `--resume` flag skips them on re-run. - **Type-safe options**: `SortOrder` and `OutputFormat` union types in `schema.ts` provide compile-time safety. Constants `SORT_ORDERS` and `OUTPUT_FORMATS` are the single source of truth. - **Rating=0 sentinel (per-review only)**: When the stars selector is stale, individual reviews get `rating: 0` instead of being silently discarded; parser and extractor both warn. This applies to review-level ratings only. The business-level `business.rating` returned by `parseRatingText()` in business-extractor.ts uses `null` on parse failure – zero is treated as a valid user rating, not a sentinel. -- **Batch safety**: Filename deduplication prevents overwrites. Per-location timeout (`--location-timeout`, default 5 min) prevents indefinite hangs. Invalid URLs logged with warnings. +- **Batch safety**: Filename deduplication prevents overwrites. Invalid URLs logged with warnings. Per-location timeout (`--location-timeout`, default 5 min) goes through `runWithTimeout()` in `src/core/timeout.ts`, never `Promise.race`: the timer aborts a signal that `withRetry` (no further attempt, back-off cut short) and `scrapeLocation(parsed, options, signal)` honour – `withBrowserSession()` closes the browser on abort, so every pending Playwright call rejects – and the batch waits for the stopped scrape to settle before the next place, because Chromium allows one browser per profile directory (issue #33). A result that arrives after the timeout is discarded (`LOCATION_TIMEOUT`); a scrape that does not settle within `SETTLE_GRACE_MS` (15 s) yields `BROWSER_NOT_CLOSED`, which stops the batch (remaining places reported "not started", exit 1). The batch loop is `runBatchLocations()` with a **required** injected `scrape` so tests can never fall back to the real profile; `batchCommand` is the only caller passing `scrapeLocation`. Interactive sign-in in headed mode counts against the timeout. Output files are written atomically (`writeFileAtomic`). +- **Signal handling**: revcli launches with Playwright's `handleSIGINT/handleSIGTERM/handleSIGHUP: false` (`browserLaunchOptions()`), because Playwright's own SIGTERM/SIGHUP handlers close browsers *without exiting* and suppress Node's default exit – that is why `kill ` used to leave revcli running. `src/index.ts` calls `installBrowserShutdown()` once: the first signal aborts `shutdownSignal` (an `UnrecoverableError` kind `"SHUTDOWN"`; batch, `withRetry` and `launchBrowser` stop on it), closes every tracked browser and exits 128 + signal number (129/130/143), forced after `FORCE_EXIT_MS` (5 s); a later signal exits at once. `launchBrowser()` tracks the context right after launch and closes it if the rest of the launch fails. Do not install handlers as an import side effect – test workers import `browser.ts`. - **Sort order verification**: After selecting a sort order via the dropdown, `setSortOrder()` verifies the ARIA live region (`div[aria-live="polite"][aria-atomic="true"]`) contains the expected keyword (e.g., "newest"). Google Maps announces sort changes via this accessibility element. If verification fails, the scraper exits with an unrecoverable error. The `hl=en` locale enforcement guarantees English announcement text. - **Volatile state eviction between scrapes**: Before every navigation, `clearVolatileBrowserState()` in `browser.ts` uses CDP `Storage.clearDataForOrigin` to clear `service_workers,cache_storage,local_storage,indexeddb` for `https://www.google.com`. Cookies are intentionally preserved so Google auth stays intact. This prevents Google Maps' SPA shell from replaying a previously-loaded place via cached state during sequential scrapes. - **Navigation target verification**: After navigating, `navigateToReviews()` compares the loaded page's placeId (extracted from `page.url()`) against `parsed.placeId` using `placeIdsMatch()`. On mismatch, it throws an `UnrecoverableError` with kind `"NAV_VERIFY"` – `isUnrecoverable()` detects this structurally via `instanceof`, so `withRetry` will not mask a cross-contamination bug. Verification only runs when `canVerifyPlaceIdFormat(parsed.placeId)` is true (i.e., the `0x...:0x...` format). Short URLs, CID URLs, and ChIJ Place ID strings skip verification because their format does not align with `extractPlaceIdFromUrl()` output; the resolved placeId is logged at debug level for post-hoc audit. @@ -160,7 +166,14 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - **totalReviews reconciliation**: `assembleScrapeResult()` in `src/scraper/scrape-location.ts` is an exported pure helper called from `scrapeLocation()` to enforce the invariant `business.totalReviews === reviews.length` at the single seam where `businessInfo` (header-derived) and `reviews` (scraped) first coexist. The original Google-header value is preserved as `business.headerTotalReviews`. See issue #5. When `--max-reviews N` caps collection, `totalReviews === N` (not the header) and `headerTotalReviews` holds Google's larger number. - **Header parsing extracted for testability**: `src/scraper/parser.ts` exports `parseReviewCount(text)` and `src/scraper/business-extractor.ts` exports `parseRatingText(text)`. Both are pure functions called from the Node side after `page.evaluate()` returns raw DOM strings. This matches the repo's "extract pure logic out of Playwright-coupled code" convention (see `parseInputFile`, `extractPlaceIdFromUrl`, `calculateStaleDelay`). `parseReviewCount` assumes the `hl=en` locale – comma thousand separator, period is a decimal and not a thousands separator. Suffix forms (`1.6K reviews`) return null; reconciliation backfills via `reviews.length`. - **Business header debug logging**: `business-extractor.ts` emits PII-scrubbed debug-level logs of raw DOM candidate strings (tab text, aria-label badge, scoped `[role="main"]` body snippet) so selector staleness can be diagnosed from `--verbose` output without leaking reviewer names or review content. The scrub preserves digits, separators, K/M/B suffixes, and the letters of "reviews"; all other characters become `·`. -- **Playwright locator scoping for comma-lists**: Never flat-concatenate selector constants like `` `${SELECTORS.reviewCard} ${SELECTORS.expandButton}` `` – CSS parses the comma as a selector-list union, leaving the second alternative unscoped and matching page-wide. Use chained locators: `page.locator(SELECTORS.reviewCard).locator(SELECTORS.expandButton)`. Chaining scopes both alternatives to the parent's subtree. `expandAllReviews()` in `extractor.ts` is the reference implementation. `tests/extractor-selectors.test.ts` pins the regression shape. +- **Playwright locator scoping for comma-lists**: Never flat-concatenate selector constants like `` `${SELECTORS.reviewCard} ${SELECTORS.expandButton}` `` – CSS parses the comma as a selector-list union, leaving the second alternative unscoped and matching page-wide. Use chained locators (`page.locator(SELECTORS.reviewCard).locator(SELECTORS.expandButton)`) or, in-page, `card.querySelectorAll(SELECTORS.expandButton)` – both scope every alternative to the parent's subtree. `expandAllReviews()` in `extractor.ts` now scopes in-page this way. `tests/extractor-selectors.test.ts` pins the regression shape. +- **Visible-filtered waits and counts**: every "first of several markers" wait uses `a.or(b).filter({ visible: true }).first().waitFor({ state: "visible", timeout })`, and every presence check uses `loc.filter({ visible: true }).count() > 0` – never `isVisible()` on a multi-match locator, and never an unfiltered `.first()`, because a hidden earlier match (a template, a duplicate link) stalls the wait or answers wrongly. Used by `setSortOrder()` and the session-marker read. +- **In-page closures**: code passed to `page.evaluate`, `waitForFunction` or `locator.evaluate` runs in the browser. It may reference only its parameters and browser globals (pass Node constants as arguments – `SCROLL_STEP` read from Node scope crashed every scrape on the second scroll, issue #31), and must not declare named inner functions or `const f = () => …`: tsx/esbuild keepNames wraps those in `__name(...)`, which does not exist in the page. Anonymous inline callbacks (`.map((x) => …)`) are fine. Init scripts are passed as strings (`addInitScript({ content })`) so no transform can touch them. The vitest transform does **not** enable keepNames, so the browser tests catch Node-reference bugs but **not** `__name` bugs – that guard is a live `npm run dev` run that scrolls (e.g. `-m 30`). +- **Expand step**: Google removes a review's "More" button once clicked, so `expandAllReviews(page, skipIds)` uses mark-and-confirm, never positional `nth(i)`: one in-page scan (`scanExpandButtons`) stamps each *pending* button (rendered, not `aria-expanded="true"`) in cards not in `skipIds` with a Node-generated `data-revcli-expand` token (alphabet `[a-z0-9-]`, old stamps cleared first); each token is clicked and confirmed by `waitForFunction` (gone, disconnected, hidden, or `aria-expanded="true"` – this also covers owner-response buttons whichever way they react); up to 2 passes. Collected cards carry `data-revcli-collected=""` (`COLLECTED_MARK_ATTR`, set by `markCollected()` after each collect) and are skipped by both `scanExpandButtons` and `extractReviews()` while the mark equals the card's current review id – so a cycle reads only new cards and its cost stays flat as the list grows (issue #33: re-reading every card made 4,000+ review places crawl), and a card element Google reuses for another review is read again. The scroller therefore passes no `skipIds`; a stuck button costs at most 2 clicks per cycle until its card is collected. `ScrollOptions.onCycle` reports `CycleTiming` (duration, new, total, `readCount`) per cycle; `--verbose` logs the same line. `ExpandResult` is for debug logs only: the truncation warning (`formatTruncationWarning()`) comes from the per-card `expandPending` flag that `extractReviews()` reads at extraction time, counted by `collectOnce()` for newly collected reviews and logged once at the end of `scrollAndCollectReviews()`. Every collect path (including the spinner retry) goes through `expandAndCollect()`. Still-truncated reviews are collected anyway (deferring risks losing the whole card from the virtualized list). See docs/selector-maintenance.md §5. +- **Short links redirect in page script**: `maps.app.goo.gl` links no longer redirect with an HTTP 3xx, so `page.goto(..., domcontentloaded)` can resolve while the page is still on the short-link host. `waitForShortLinkRedirect()` in `navigator.ts` waits for the destination before `handleConsent()`/`ensureEnglishLocale()` run. Without it `hl=en` is added to the short link and lost in the redirect, and a signed-out or non-English profile gets a localized page that no English selector or banner text matches (the host constant `SHORT_LINK_HOST` and the pure helper `isShortLinkUrl()` live in `src/utils/url.ts`, which also derives the short-URL input regex from the same constant; pinned by `tests/browser/navigation.test.ts`, which also asserts the final URL has `hl=en` and no `entry`/`g_ep`). +- **Non-place detection**: a link that lands on a search results page fails once with `UnrecoverableError` kind `"NOT_A_PLACE"` and `NOT_A_PLACE_MESSAGE` (which does not echo the URL – batch prints it). Detection is by path (`isSearchResultsUrl()`: `/maps/search…`), never by text (Google may serve that page in another language), and only after the `h1` wait (or the tab wait) times out, because CID and some redirect links pass through `/maps/search/` on their way to `/maps/place/`. Any other timeout is rethrown unchanged so real network flakiness is still retried. +- **Fatal error reporting**: `index.ts` runs `program.parseAsync().catch(reportFatalError)`; `reportFatalError()` in `fatal.ts` prints `describeFatalError(err).message` once via `logger.error`, sets exit code 1, adds "Run again with --verbose for details." only for unexpected errors (not `isUnrecoverable` ones or `ENOENT`), and logs the stack at debug level only. Playwright's "Call log:" section is cut from the message and the stack (it can print the account link's label). `withRetry()` logs its "unrecoverable error" line at debug, so the message appears exactly once; command handlers do not catch `UnrecoverableError` themselves. Any error message from browser code that reaches output or logs goes through `safeErrorMessage()` (call log cut) – batch's per-location failure line, the `withRetry` debug line and the sign-in poll debug line. It is defined in `errors.ts` (no imports, so `retry.ts` can use it without a cycle) and re-exported from `fatal.ts`. +- **Browser tests**: `tests/browser/*.test.ts` run the real in-page code (scroll, expand, session markers, navigation) in a fresh non-persistent headless Chromium (`chromium.launch`) against local HTML from `tests/browser/fixtures/maps-page.ts`. They must **never** import `launchBrowser` or `PROFILE_DIR` (the `~/.revcli` credential store); `tests/browser-import-guard.test.ts` scans every test file for such imports. Timing-sensitive fixture behaviour is event-driven where possible (e.g. `bannerOnReviewsTabClick` shows the banner only after revcli's first check). The harness registers `context.route("**/*", abort)` first and fixture routes after it, so nothing reaches the network even with fake cookies. Fixture behaviour is a plain ` +`; +} diff --git a/tests/browser/fixtures/signal-child.ts b/tests/browser/fixtures/signal-child.ts new file mode 100644 index 0000000..73ced92 --- /dev/null +++ b/tests/browser/fixtures/signal-child.ts @@ -0,0 +1,57 @@ +/** + * Child process for tests/browser/shutdown.test.ts (issue #33). + * + * Starts one browser the way revcli does (same launch options, same signal + * wiring as src/index.ts, same withBrowserSession as a scrape), on a TEMPORARY + * profile passed as argv[2], prints "ready", and then stays busy like a + * running scrape until a signal arrives. + * + * It never touches ~/.revcli: the profile must be inside the OS temp + * directory, and the test also points HOME at a temp directory. + */ +import { realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, sep } from "node:path"; +import { chromium } from "playwright"; +import { + browserLaunchOptions, + installBrowserShutdown, + trackBrowser, + withBrowserSession, +} from "../../../src/scraper/browser.js"; +import { shutdownSignal } from "../../../src/core/shutdown.js"; + +const profile = process.argv[2]; +const tmpRoot = realpathSync(tmpdir()); +if ( + !profile || + profile.includes(".revcli") || + !(realpathSync(dirname(profile)) + sep).startsWith(tmpRoot + sep) +) { + process.stderr.write("signal-child: refusing a profile outside the temp directory\n"); + process.exit(2); +} + +installBrowserShutdown(); + +// Same path as a real scrape: a tracked browser inside withBrowserSession, +// which closes it when the shutdown signal aborts. +await withBrowserSession( + async () => { + const context = await chromium.launchPersistentContext( + profile, + browserLaunchOptions({ headless: true }), + ); + trackBrowser(context); + await context.route("**/*", (route) => route.abort()); + const page = context.pages()[0] ?? (await context.newPage()); + return { context, page }; + }, + shutdownSignal, + async ({ page }) => { + await page.setContent("

signal test

"); + process.stdout.write("ready\n"); + // Stay busy like a running scrape until the browser is closed under us. + await page.waitForTimeout(10 * 60_000); + }, +); diff --git a/tests/browser/harness.ts b/tests/browser/harness.ts new file mode 100644 index 0000000..d800c5a --- /dev/null +++ b/tests/browser/harness.ts @@ -0,0 +1,62 @@ +/** + * Browser-test harness: a throwaway headless Chromium that only ever sees + * local fixture HTML. + * + * Rules (see AGENTS.md "Browser tests"): + * - Never import `launchBrowser` or `PROFILE_DIR` from src/scraper/browser.ts + * here or in any browser test. They open the persistent profile in + * ~/.revcli, which is a credential store holding a real Google session. + * - Every context blocks all network traffic first; fixture routes are added + * afterwards (Playwright runs the most recently registered matching route + * first), so nothing can reach Google even with fake cookies in the context. + */ +import { + chromium, + type Browser, + type BrowserContext, + type Page, +} from "playwright"; + +export async function launchTestBrowser(): Promise { + return chromium.launch({ headless: true }); +} + +/** A fresh, non-persistent context with every network request aborted. */ +export async function newFixtureContext(browser: Browser): Promise { + const context = await browser.newContext({ + viewport: { width: 1280, height: 800 }, + locale: "en-US", + }); + await context.route("**/*", (route) => route.abort()); + return context; +} + +/** A page whose content is the given fixture HTML (no URL, no network). */ +export async function newFixturePage( + context: BrowserContext, + html: string, +): Promise { + const page = await context.newPage(); + await page.setContent(html); + return page; +} + +export type RouteMatcher = string | RegExp | ((url: URL) => boolean); + +/** + * Serve fixture HTML for requests matching `url`. Registered after the + * abort-all route, so it takes precedence for its own URLs only. + * + * There is deliberately no redirect variant: Playwright does not route the + * follow-up request of a fulfilled 3xx, so such a navigation hangs. Fixtures + * that need a different final URL use `rewriteUrlTo` (history.replaceState). + */ +export async function routeFixture( + context: BrowserContext, + url: RouteMatcher, + html: string, +): Promise { + await context.route(url, (route) => + route.fulfill({ status: 200, contentType: "text/html", body: html }), + ); +} diff --git a/tests/browser/navigation.test.ts b/tests/browser/navigation.test.ts new file mode 100644 index 0000000..b56677e --- /dev/null +++ b/tests/browser/navigation.test.ts @@ -0,0 +1,208 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { navigateToReviews, NOT_A_PLACE_MESSAGE, setSortOrder } from "../../src/scraper/navigator.js"; +import { parseGoogleMapsInput } from "../../src/utils/url.js"; +import { hasUnrecoverableKind, UnrecoverableError } from "../../src/core/errors.js"; +import { SORT_ORDERS } from "../../src/core/schema.js"; +import { buildMapsPage, type MapsFixtureOptions } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage, routeFixture } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +const PLACE_URL = "https://www.google.com/maps/place/Test/data=!1s0x1:0x2?hl=en"; +const isPlacePath = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps/place/Test/data=!1s0x1:0x2"; +const CID_URL = "https://www.google.com/maps?cid=1234567890"; +const isCidLink = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps" && u.searchParams.has("cid"); +const SEARCH_PATH = "/maps/search/foo/@1,2,3z?hl=en"; + +const PLACE: MapsFixtureOptions = { totalReviews: 10, batchSize: 10, withSortMenu: true }; + +let browser: Browser; +let context: BrowserContext; + +beforeAll(async () => { + browser = await launchTestBrowser(); +}); + +afterAll(async () => { + await browser?.close(); +}); + +beforeEach(async () => { + context = await newFixtureContext(browser); +}); + +afterEach(async () => { + await context?.close(); +}); + +async function rejection(p: Promise): Promise { + return p.then( + () => new Error("expected a rejection"), + (e: unknown) => e, + ); +} + +describe("navigateToReviews on a limited view (issue #31 finding 5)", () => { + it.each([...SORT_ORDERS])("fails with AUTH_REQUIRED for sort %s", async (sort) => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, limitedViewBanner: true })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), sort)); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }); + + it("catches a banner that appears only after the Reviews tab is clicked", async () => { + // The banner is inserted by the tab click, i.e. after the first check: + // only the second check (after the review cards) can see it. + await routeFixture( + context, + isPlacePath, + buildMapsPage({ ...PLACE, limitedViewBanner: true, bannerOnReviewsTabClick: true }), + ); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }); + + it.each(["newest", "highest", "lowest"] as const)( + "fails with AUTH_REQUIRED when Sort opens the sign-in dialog, with no banner (sort %s)", + async (sort) => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), sort)); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }, + ); + + it("does not see the Sort sign-in dialog for sort relevant (no Sort click), so it resolves", async () => { + // Pins current behaviour: with no banner, "relevant" never clicks Sort, so + // the dialog signal cannot fire. The banner is the only signal for it. + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + const page = await context.newPage(); + + const business = await navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant"); + + expect(business.name).toBe("Test Place"); + }); + + it("is not fooled by a review quoting the banner text", async () => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, reviewQuotingBanner: true })); + const page = await context.newPage(); + + const business = await navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant"); + + expect(business.name).toBe("Test Place"); + }); +}); + +describe("navigateToReviews on a short link (issue #31)", () => { + it("waits for the script redirect before forcing hl=en", async () => { + // Google redirects maps.app.goo.gl links in page script. If hl=en is added + // to the short link itself it is lost, and a signed-out or non-English + // profile gets a localized page that no English selector matches. + // hl=en is already there, so only the short-link rule can cause the + // extra navigation that strips entry/g_ep. + const target = "https://www.google.com/maps/place/Test/data=!1s0x1:0x2?hl=en&entry=tts&g_ep=Egoy"; + await routeFixture( + context, + (u) => u.hostname === "maps.app.goo.gl", + ``, + ); + await routeFixture(context, isPlacePath, buildMapsPage(PLACE)); + const page = await context.newPage(); + + await navigateToReviews(page, parseGoogleMapsInput("https://maps.app.goo.gl/abcDEF123"), "relevant"); + + const finalUrl = new URL(page.url()); + expect(finalUrl.hostname).toBe("www.google.com"); + expect(finalUrl.searchParams.get("hl")).toBe("en"); + expect(finalUrl.searchParams.has("entry")).toBe(false); + expect(finalUrl.searchParams.has("g_ep")).toBe(false); + }); +}); + +describe("setSortOrder", () => { + it("fails fast with AUTH_REQUIRED when Sort opens the sign-in dialog", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + + const start = Date.now(); + const err = await rejection(setSortOrder(page, "newest")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect(Date.now() - start).toBeLessThan(3000); + }); + + it("is not stalled by a hidden menu item earlier in the DOM", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ ...PLACE, sortOpensSignInDialog: true, hiddenMenuTemplate: true }), + ); + + const start = Date.now(); + const err = await rejection(setSortOrder(page, "newest")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect(Date.now() - start).toBeLessThan(3000); + }); + + it("carries on when the sort menu is visible alongside a sign-in dialog", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, signInDialogAtLoad: true })); + + await expect(setSortOrder(page, "newest")).resolves.toBeUndefined(); + }); + + it("still applies the sort through the real menu", async () => { + const page = await newFixturePage(context, buildMapsPage(PLACE)); + + await expect(setSortOrder(page, "newest")).resolves.toBeUndefined(); + }); + + it("still applies the sort with a hidden menu item earlier in the DOM", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, hiddenMenuTemplate: true })); + + await expect(setSortOrder(page, "lowest")).resolves.toBeUndefined(); + }); +}); + +// The link loads, then the page rewrites its URL to a search results path – as +// Google Maps does for a link that does not resolve to one place. +describe("navigateToReviews on a non-place link (issue #31 finding 6)", () => { + const searchPage = (h1: string | null) => + buildMapsPage({ totalReviews: 0, batchSize: 1, h1, tabs: [], rewriteUrlTo: SEARCH_PATH }); + + it("fails once with NOT_A_PLACE when the link lands on a search page without h1", async () => { + await routeFixture(context, isCidLink, searchPage(null)); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(err).toBeInstanceOf(UnrecoverableError); + expect((err as UnrecoverableError).kind).toBe("NOT_A_PLACE"); + expect((err as UnrecoverableError).message).toBe(NOT_A_PLACE_MESSAGE); + }); + + it("fails with NOT_A_PLACE when the search page has an h1 but no tabs", async () => { + await routeFixture(context, isCidLink, searchPage("Results")); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(hasUnrecoverableKind(err, "NOT_A_PLACE")).toBe(true); + }); + + it("rethrows a plain timeout when a place panel never loads on a non-search URL", async () => { + await routeFixture(context, isCidLink, buildMapsPage({ totalReviews: 0, batchSize: 1, h1: null })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(err).toBeInstanceOf(Error); + expect(err).not.toBeInstanceOf(UnrecoverableError); + }); +}); diff --git a/tests/browser/scroll.test.ts b/tests/browser/scroll.test.ts new file mode 100644 index 0000000..303fc83 --- /dev/null +++ b/tests/browser/scroll.test.ts @@ -0,0 +1,100 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { scrollAndCollectReviews, type CycleTiming } from "../../src/scraper/scroller.js"; +import { buildMapsPage } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +let browser: Browser; +let context: BrowserContext; + +beforeAll(async () => { + browser = await launchTestBrowser(); +}); + +afterAll(async () => { + await browser?.close(); +}); + +beforeEach(async () => { + context = await newFixtureContext(browser); +}); + +afterEach(async () => { + await context?.close(); +}); + +describe("scrollAndCollectReviews (in-page scroll code, issue #31 finding 1)", () => { + it("collects exactly maxReviews across several scrolls", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 35, batchSize: 10 }), + ); + + const reviews = await scrollAndCollectReviews(page, { maxReviews: 30, delayMs: 1 }); + + expect(reviews).toHaveLength(30); + expect(new Set(reviews.map((r) => r.id)).size).toBe(30); + }); + + it("collects every review and stops when the list stops growing", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 12, batchSize: 5 }), + ); + + const reviews = await scrollAndCollectReviews(page, { delayMs: 1 }); + + expect(reviews.map((r) => r.id).sort()).toEqual( + Array.from({ length: 12 }, (_, i) => `r${i}`).sort(), + ); + }); + + it("keeps a flat collect-cycle time as the list grows to 2,000 reviews (issue #33)", async () => { + const total = 2000; + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: total, batchSize: 50 }), + ); + + const cycles: CycleTiming[] = []; + const reviews = await scrollAndCollectReviews(page, { + delayMs: 1, + onCycle: (c) => cycles.push(c), + }); + + expect(reviews).toHaveLength(total); + // Only cycles that collected something: the trailing stale cycles at the + // end of the list are not "collect cycles" of a growing list. + const productive = cycles.filter((c) => c.newCount > 0); + expect(productive.length).toBeGreaterThanOrEqual(20); + const sum = (cs: CycleTiming[]) => cs.reduce((n, c) => n + c.durationMs, 0); + const first = sum(productive.slice(0, 10)); + const last = sum(productive.slice(-10)); + console.log(`collect cycles: first 10 = ${first}ms, last 10 = ${last}ms`); + // Timing-free check: a cycle reads only the cards not collected yet (about + // one scroll's worth), never the whole list. + const maxRead = Math.max(...cycles.map((c) => c.readCount)); + expect(maxRead).toBeLessThanOrEqual(2 * 50); + expect(last).toBeLessThanOrEqual(2 * Math.max(first, 1)); + // One retry: the ~10 ms timings can be disturbed by a busy machine. The + // readCount check above is timing-free and fails on the old code anyway. + }, { timeout: 180_000, retry: 1 }); + + it("stops at the time limit and keeps the reviews collected so far", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 35, batchSize: 10 }), + ); + + // A deadline already in the past: one collect, then stop. + const reviews = await scrollAndCollectReviews(page, { + delayMs: 1, + deadline: Date.now() - 1, + }); + + expect(reviews.length).toBeGreaterThan(0); + expect(reviews.length).toBeLessThan(35); + }); +}); diff --git a/tests/browser/session.test.ts b/tests/browser/session.test.ts new file mode 100644 index 0000000..9877311 --- /dev/null +++ b/tests/browser/session.test.ts @@ -0,0 +1,210 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { + getSessionState, + POLL_PROBE, + SESSION_SIGN_IN_STABLE_MS, + waitForSignIn, +} from "../../src/scraper/auth.js"; +import { hasUnrecoverableKind } from "../../src/core/errors.js"; +import { logger } from "../../src/utils/logger.js"; +import { buildMapsPage, type MapsFixtureOptions } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage, routeFixture } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +/** Made-up values: the context blocks all network, so these never reach Google. */ +const FAKE_AUTH_COOKIES = ["SID", "HSID", "SSID", "APISID", "SAPISID", "__Secure-1PSID", "__Secure-3PSID"]; +const PII = ["test.user@example.com", "Konto Google"]; + +let browser: Browser; +let context: BrowserContext; + +beforeAll(async () => { + browser = await launchTestBrowser(); +}); + +afterAll(async () => { + await browser?.close(); +}); + +beforeEach(async () => { + context = await newFixtureContext(browser); +}); + +afterEach(async () => { + await context?.close(); +}); + +async function addFakeAuthCookies(): Promise { + await context.addCookies( + FAKE_AUTH_COOKIES.map((name) => ({ + name, + value: `revcli-fake-${name}`, + domain: ".google.com", + path: "/", + secure: true, + })), + ); +} + +function page(opts: Partial) { + return newFixturePage(context, buildMapsPage({ totalReviews: 0, batchSize: 1, ...opts })); +} + +async function timed(fn: () => Promise): Promise<{ value: T; ms: number }> { + const start = Date.now(); + const value = await fn(); + return { value, ms: Date.now() - start }; +} + +describe("getSessionState (issue #31 findings 3–4)", () => { + it("reports a dead session (cookies + steady Sign in link) as expired", async () => { + await addFakeAuthCookies(); + const p = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }] }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("expired"); + expect(ms).toBeGreaterThanOrEqual(SESSION_SIGN_IN_STABLE_MS); + }); + + it("uses a longer stability window for the commands than for the poll loop", async () => { + // "Sign in" for 2 s, then the account link: longer than the poll loop's + // 1.5 s window, shorter than the commands' 3 s window. + await addFakeAuthCookies(); + const timeline = [ + { atMs: 0, marker: "sign-in" as const }, + { atMs: 2000, marker: "account" as const }, + ]; + + const forCommands = await page({ markerTimeline: timeline }); + expect(await getSessionState(forCommands)).toBe("signed-in"); + + const forPolling = await page({ markerTimeline: timeline }); + expect(await getSessionState(forPolling, POLL_PROBE)).toBe("expired"); + }); + + it("reports cookies + account link as signed-in", async () => { + await addFakeAuthCookies(); + const p = await page({ markerTimeline: [{ atMs: 0, marker: "account" }], markerLang: "en" }); + + expect(await getSessionState(p)).toBe("signed-in"); + }); + + it("reads the markers independently of the page language", async () => { + await addFakeAuthCookies(); + const account = await page({ markerTimeline: [{ atMs: 0, marker: "account" }], markerLang: "pl" }); + expect(await getSessionState(account)).toBe("signed-in"); + + const signIn = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }], markerLang: "pl" }); + expect(await getSessionState(signIn)).toBe("expired"); + }); + + it("reports signed-out quickly when there are no auth cookies", async () => { + const p = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }] }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("signed-out"); + expect(ms).toBeLessThan(1000); + }); + + it("waits for a slow account marker, and is unconfirmed when none appears", async () => { + await addFakeAuthCookies(); + const slow = await page({ markerTimeline: [{ atMs: 1500, marker: "account" }] }); + expect(await getSessionState(slow)).toBe("signed-in"); + + const none = await page({}); + expect(await getSessionState(none, { timeoutMs: 500 })).toBe("unconfirmed"); + }); + + it("never reports a transient Sign in link on a valid session as expired", async () => { + await addFakeAuthCookies(); + const p = await page({ + markerTimeline: [ + { atMs: 0, marker: "sign-in" }, + { atMs: 800, marker: "account" }, + ], + }); + + expect(await getSessionState(p)).toBe("signed-in"); + }); + + it("ignores a hidden duplicate Sign in link earlier in the DOM", async () => { + await addFakeAuthCookies(); + const p = await page({ + hiddenDuplicateMarker: "sign-in", + markerTimeline: [{ atMs: 0, marker: "account" }], + }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("signed-in"); + expect(ms).toBeLessThan(2000); + }); + + it("never logs the account label (name, email)", async () => { + const spies = (["debug", "info", "warn", "error"] as const).map((level) => + vi.spyOn(logger, level), + ); + try { + await addFakeAuthCookies(); + for (const markerLang of ["en", "pl"] as const) { + for (const marker of ["account", "sign-in"] as const) { + const p = await page({ markerTimeline: [{ atMs: 0, marker }], markerLang }); + await getSessionState(p, POLL_PROBE); + } + } + const unconfirmed = await page({ hiddenDuplicateMarker: "account" }); + await getSessionState(unconfirmed, { timeoutMs: 300 }); + + const logged = spies.flatMap((s) => s.mock.calls).map((args) => args.map(String).join(" ")); + expect(logged.length).toBeGreaterThan(0); + for (const line of logged) { + for (const secret of PII) expect(line).not.toContain(secret); + } + } finally { + for (const spy of spies) spy.mockRestore(); + } + }); +}); + +// The real session probe inside the sign-in poll loop (no injected `probe`). +// A cookie-only check would report "signed-in" for the dead session below. +describe("waitForSignIn with the real session probe", () => { + const MAPS_HOME = "https://www.google.com/maps?hl=en"; + const isMapsHome = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps"; + + it("keeps waiting on a dead session (cookies + steady Sign in link) and times out", async () => { + await addFakeAuthCookies(); + await routeFixture( + context, + isMapsHome, + buildMapsPage({ totalReviews: 0, batchSize: 1, markerTimeline: [{ atMs: 0, marker: "sign-in" }] }), + ); + const p = await context.newPage(); + await p.goto(MAPS_HOME); + + const err = await waitForSignIn(context, p, { timeoutMs: 8000, pollIntervalMs: 50 }).catch( + (e: unknown) => e, + ); + + expect(hasUnrecoverableKind(err, "AUTH_POLL")).toBe(true); + }); + + it("returns signed-in once Google shows the account link", async () => { + await addFakeAuthCookies(); + await routeFixture( + context, + isMapsHome, + buildMapsPage({ totalReviews: 0, batchSize: 1, markerTimeline: [{ atMs: 0, marker: "account" }] }), + ); + const p = await context.newPage(); + await p.goto(MAPS_HOME); + + await expect(waitForSignIn(context, p, { timeoutMs: 8000, pollIntervalMs: 50 })).resolves.toBe( + "signed-in", + ); + }); +}); diff --git a/tests/browser/shutdown.test.ts b/tests/browser/shutdown.test.ts new file mode 100644 index 0000000..f92b68a --- /dev/null +++ b/tests/browser/shutdown.test.ts @@ -0,0 +1,120 @@ +import { spawn, spawnSync, type ChildProcess } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +/** + * Issue #33: `kill ` (SIGTERM) must close every browser and end revcli + * with a non-zero code within 10 seconds. Runs a real child process with a + * real Chromium on a temporary profile (never ~/.revcli). + */ + +const CHILD = fileURLToPath(new URL("./fixtures/signal-child.ts", import.meta.url)); +const EXIT_WITHIN_MS = 10_000; + +/** + * The child gets a temporary HOME, so tell Playwright where the installed + * browsers are (its default location is derived from the real HOME). + */ +const BROWSERS_PATH = + process.env.PLAYWRIGHT_BROWSERS_PATH ?? + (process.platform === "darwin" + ? join(homedir(), "Library", "Caches", "ms-playwright") + : join(homedir(), ".cache", "ms-playwright")); + +/** + * Whether a Chromium for `profileDir` is running: matched on its + * `--user-data-dir=` flag, so the child node process (which has the bare path + * in its argv) does not count. No shell involved. + */ +function processRunning(profileDir: string): boolean { + const res = spawnSync("pgrep", ["-f", `user-data-dir=${profileDir}`], { encoding: "utf8" }); + if (res.status === 0) return true; + if (res.status === 1) return false; + throw new Error(`pgrep failed (status ${res.status}): ${res.error?.message ?? res.stderr}`); +} + +async function waitUntil(check: () => boolean, timeoutMs: number): Promise { + const end = Date.now() + timeoutMs; + while (Date.now() < end) { + if (check()) return true; + await new Promise((r) => setTimeout(r, 100)); + } + return check(); +} + +let child: ChildProcess | undefined; +let tmp: string | undefined; +let profile: string | undefined; + +afterEach(() => { + if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + if (profile) spawnSync("pkill", ["-9", "-f", profile]); + if (tmp) rmSync(tmp, { recursive: true, force: true }); + child = tmp = profile = undefined; +}); + +/** Start the child and resolve once it printed "ready". */ +async function startChild(): Promise { + tmp = mkdtempSync(join(tmpdir(), "revcli-signal-")); + const home = join(tmp, "home"); + mkdirSync(home); + profile = join(tmp, "profile"); + const proc = spawn(process.execPath, ["--import", "tsx", CHILD, profile], { + env: { ...process.env, HOME: home, PLAYWRIGHT_BROWSERS_PATH: BROWSERS_PATH }, + stdio: ["ignore", "pipe", "pipe"], + shell: false, + }); + child = proc; + let stderr = ""; + proc.stderr?.on("data", (d) => (stderr += String(d))); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`child not ready: ${stderr}`)), 45_000); + proc.stdout?.on("data", (d) => { + if (String(d).includes("ready")) { + clearTimeout(timer); + resolve(); + } + }); + proc.once("exit", (code) => { + clearTimeout(timer); + reject(new Error(`child exited early (${code}): ${stderr}`)); + }); + }); + return proc; +} + +/** Resolve with the exit code (null when killed by a signal) or "timeout". */ +function waitForExit(proc: ChildProcess, timeoutMs: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => resolve("timeout"), timeoutMs); + proc.once("exit", (code) => { + clearTimeout(timer); + resolve(code); + }); + }); +} + +describe.skipIf(process.platform === "win32")("signal shutdown with a real browser (issue #33)", () => { + it.each([ + ["SIGTERM", 143], + ["SIGINT", 130], + ] as const)("%s closes the browser and exits %i within 10 s", async (signal, code) => { + const proc = await startChild(); + expect(processRunning(profile!)).toBe(true); + + const start = Date.now(); + proc.kill(signal); + const exitCode = await waitForExit(proc, EXIT_WITHIN_MS + 2_000); + const elapsed = Date.now() - start; + + expect(exitCode).toBe(code); + expect(elapsed).toBeLessThan(EXIT_WITHIN_MS); + // Chromium's helper processes may need a moment to go after the exit. + expect(await waitUntil(() => !processRunning(profile!), 3_000)).toBe(true); + }); +}); diff --git a/tests/consent.test.ts b/tests/consent.test.ts index e92b189..a3121c0 100644 --- a/tests/consent.test.ts +++ b/tests/consent.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { appendHlParam } from "../src/scraper/consent.js"; +import { appendHlParam, englishLocaleTarget } from "../src/scraper/consent.js"; import { extractPlaceIdFromUrl } from "../src/utils/url.js"; describe("appendHlParam", () => { @@ -68,3 +68,56 @@ describe("appendHlParam", () => { expect(placeId).toBe("0x3e2ee3641f7016d7:0x8e3a8bcf52dad296"); }); }); + +describe("appendHlParam short-link detection", () => { + it("rewrites a normal Maps link that only mentions the short-link host in its query", () => { + const out = appendHlParam("https://www.google.com/maps/place/Test/@0,0,15z?ref=maps.app.goo.gl"); + expect(new URL(out).searchParams.get("hl")).toBe("en"); + }); +}); + +describe("englishLocaleTarget", () => { + const params = (url: string | null) => new URL(url ?? "about:blank").searchParams; + + it("returns null for an English URL without limited-view params", () => { + expect(englishLocaleTarget("https://www.google.com/maps/place/Test/@0,0,15z?hl=en")).toBeNull(); + }); + + it("forces hl=en when hl is missing or another language", () => { + for (const url of [ + "https://www.google.com/maps/place/Test/@0,0,15z", + "https://www.google.com/maps/place/Test/@0,0,15z?hl=pl", + "https://www.google.com/maps/place/Test/@0,0,15z?hl=en-GB", + ]) { + expect(params(englishLocaleTarget(url)).get("hl")).toBe("en"); + } + }); + + it("does not mistake hl=en inside another parameter's value for the locale", () => { + const url = "https://www.google.com/maps/place/Test/@0,0,15z?q=hl%3Den&hl=de"; + expect(params(englishLocaleTarget(url)).get("hl")).toBe("en"); + }); + + it("leaves an English URL alone when Google's script re-added entry/g_ep", () => { + // Without the option, tracking params must not cost a second page load. + expect( + englishLocaleTarget("https://www.google.com/maps/place/Test/@0,0,15z?hl=en&entry=ttu&g_ep=Egoy"), + ).toBeNull(); + }); + + it("strips entry and g_ep after a short-link redirect even when hl is already en", () => { + const target = englishLocaleTarget( + "https://www.google.com/maps/place/Test/@0,0,15z?hl=en&entry=tts&g_ep=Egoy", + { stripLimitedViewParams: true }, + ); + const p = params(target); + expect(p.get("hl")).toBe("en"); + expect(p.has("entry")).toBe(false); + expect(p.has("g_ep")).toBe(false); + }); + + it("returns null for a short link and for unparseable input", () => { + expect(englishLocaleTarget("https://maps.app.goo.gl/abc123")).toBeNull(); + expect(englishLocaleTarget("not a url")).toBeNull(); + }); +}); diff --git a/tests/extractor.test.ts b/tests/extractor.test.ts index 769c23e..c7f75cf 100644 --- a/tests/extractor.test.ts +++ b/tests/extractor.test.ts @@ -5,8 +5,23 @@ import { buildCardSelector, shouldFallbackLang, resolveOriginalLanguage, + formatTruncationWarning, } from "../src/scraper/extractor.js"; +describe("formatTruncationWarning", () => { + it("uses the singular noun for a single collected review", () => { + expect(formatTruncationWarning(1, 1)).toBe( + 'Could not expand the full text of 1 of 1 collected review – their text may be cut off (ends with "…").', + ); + }); + + it("uses the plural noun for several collected reviews", () => { + expect(formatTruncationWarning(3, 300)).toBe( + 'Could not expand the full text of 3 of 300 collected reviews – their text may be cut off (ends with "…").', + ); + }); +}); + describe("isShowingTranslation", () => { it("is true when aria-checked is 'true'", () => { expect(isShowingTranslation("true")).toBe(true); diff --git a/tests/fatal.test.ts b/tests/fatal.test.ts new file mode 100644 index 0000000..c19271c --- /dev/null +++ b/tests/fatal.test.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, it, expect, vi } from "vitest"; +import { describeFatalError, reportFatalError, safeErrorMessage } from "../src/core/fatal.js"; +import { logger } from "../src/utils/logger.js"; +import { UnrecoverableError } from "../src/core/errors.js"; + +describe("describeFatalError", () => { + it("treats a typed UnrecoverableError as expected", () => { + const f = describeFatalError(new UnrecoverableError("AUTH_REQUIRED", "Run `revcli auth`.")); + expect(f).toMatchObject({ message: "Run `revcli auth`.", expected: true }); + }); + + it("treats an invalid-input error as expected", () => { + const f = describeFatalError(new Error('Invalid input: "foo". Provide a Google Maps URL or Place ID.')); + expect(f.expected).toBe(true); + expect(f.message).toBe('Invalid input: "foo". Provide a Google Maps URL or Place ID.'); + }); + + it("treats a missing file (ENOENT) as expected", () => { + const err = Object.assign(new Error("ENOENT: no such file or directory, open 'urls.txt'"), { + code: "ENOENT", + }); + expect(describeFatalError(err).expected).toBe(true); + }); + + it("treats a plain error as unexpected and keeps its stack for debug output", () => { + const f = describeFatalError(new Error("Something went wrong")); + expect(f.expected).toBe(false); + expect(f.message).toBe("Something went wrong"); + expect(f.stack).toContain("Something went wrong"); + }); + + it("stringifies a non-Error throwable", () => { + expect(describeFatalError("plain string")).toEqual({ + message: "plain string", + stack: null, + expected: false, + }); + }); + + it("cuts Playwright's call log, which can contain the account name and email", () => { + const err = new Error( + 'locator.click: Timeout 1000ms exceeded.\nCall log:\n - locator resolved to ', + ); + const f = describeFatalError(err); + expect(f.message).toBe("locator.click: Timeout 1000ms exceeded."); + expect(f.message).not.toContain("Call log"); + expect(f.message).not.toContain("example.com"); + expect(f.stack).not.toContain("example.com"); + }); +}); + +const CALL_LOG_ERROR = () => + new Error( + 'locator.click: Timeout 1000ms exceeded.\nCall log:\n - locator resolved to ', + ); + +describe("safeErrorMessage", () => { + it("cuts Playwright's call log", () => { + expect(safeErrorMessage(CALL_LOG_ERROR())).toBe("locator.click: Timeout 1000ms exceeded."); + }); + + it("keeps a message without a call log unchanged", () => { + expect(safeErrorMessage(new Error("boom\nsecond line"))).toBe("boom\nsecond line"); + }); + + it("stringifies a non-Error throwable", () => { + expect(safeErrorMessage("plain")).toBe("plain"); + expect(safeErrorMessage(42)).toBe("42"); + }); +}); + +describe("reportFatalError", () => { + const originalExitCode = process.exitCode; + + afterEach(() => { + process.exitCode = originalExitCode; + vi.restoreAllMocks(); + }); + + function spies() { + return { + error: vi.spyOn(logger, "error").mockImplementation(() => {}), + info: vi.spyOn(logger, "info").mockImplementation(() => {}), + debug: vi.spyOn(logger, "debug").mockImplementation(() => {}), + }; + } + + it("prints an expected error once, with no --verbose hint, stack at debug only", () => { + const s = spies(); + + reportFatalError(new UnrecoverableError("AUTH_REQUIRED", "Run `revcli auth`.")); + + expect(s.error).toHaveBeenCalledTimes(1); + expect(s.error).toHaveBeenCalledWith("Run `revcli auth`."); + expect(s.info).not.toHaveBeenCalled(); + expect(s.debug).toHaveBeenCalledTimes(1); + expect(String(s.debug.mock.calls[0][0])).toContain("UnrecoverableError"); + expect(process.exitCode).toBe(1); + }); + + it("adds the --verbose hint for an unexpected error and never prints the stack at error level", () => { + const s = spies(); + + reportFatalError(CALL_LOG_ERROR()); + + expect(s.error).toHaveBeenCalledTimes(1); + expect(s.error).toHaveBeenCalledWith("locator.click: Timeout 1000ms exceeded."); + expect(s.info).toHaveBeenCalledWith("Run again with --verbose for details."); + expect(String(s.error.mock.calls[0][0])).not.toContain(" at "); + expect(String(s.debug.mock.calls[0][0])).not.toContain("example.com"); + expect(process.exitCode).toBe(1); + }); + + it("reports a non-Error throwable without a stack", () => { + const s = spies(); + + reportFatalError("plain string"); + + expect(s.error).toHaveBeenCalledWith("plain string"); + expect(s.debug).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/tests/retry.test.ts b/tests/retry.test.ts index c989f6f..d531d72 100644 --- a/tests/retry.test.ts +++ b/tests/retry.test.ts @@ -1,5 +1,7 @@ import { describe, it, expect, vi } from "vitest"; import { withRetry } from "../src/core/retry.js"; +import { UnrecoverableError } from "../src/core/errors.js"; +import { logger } from "../src/utils/logger.js"; describe("withRetry", () => { it("returns result on first success", async () => { @@ -57,10 +59,84 @@ describe("withRetry", () => { expect(fn).toHaveBeenCalledTimes(1); }); + it("does not retry a typed AUTH_REQUIRED error", async () => { + const fn = vi + .fn() + .mockRejectedValue(new UnrecoverableError("AUTH_REQUIRED", "limited view")); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10 }), + ).rejects.toThrow("limited view"); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("does not log an UnrecoverableError at error level (the caller prints it once)", async () => { + const errorSpy = vi.spyOn(logger, "error"); + try { + const fn = vi.fn().mockRejectedValue(new UnrecoverableError("NOT_A_PLACE", "search page")); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10 }), + ).rejects.toThrow("search page"); + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + errorSpy.mockRestore(); + } + }); + it("wraps non-Error throwables", async () => { const fn = vi.fn().mockRejectedValue("string error"); await expect( withRetry(fn, "test", { maxRetries: 0, baseDelayMs: 10 }), ).rejects.toThrow("string error"); }); + + describe("with an abort signal (issue #33)", () => { + it("starts no further attempt once the signal is aborted", async () => { + const controller = new AbortController(); + const fn = vi.fn().mockImplementation(async () => { + controller.abort(new Error("stopped")); + throw new Error("Target page, context or browser has been closed"); + }); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10, signal: controller.signal }), + ).rejects.toThrow("stopped"); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("ends the back-off sleep early when aborted", async () => { + const controller = new AbortController(); + const fn = vi.fn().mockRejectedValue(new Error("flaky")); + setTimeout(() => controller.abort(new Error("stopped")), 50); + const start = Date.now(); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 5_000, signal: controller.signal }), + ).rejects.toThrow("stopped"); + expect(Date.now() - start).toBeLessThan(2_000); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("does not log the retry warning for an aborted attempt", async () => { + const warnSpy = vi.spyOn(logger, "warn"); + try { + const controller = new AbortController(); + const fn = vi.fn().mockImplementation(async () => { + controller.abort(new Error("stopped")); + throw new Error("closed"); + }); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10, signal: controller.signal }), + ).rejects.toThrow("stopped"); + expect(warnSpy).not.toHaveBeenCalled(); + } finally { + warnSpy.mockRestore(); + } + }); + + it("does not start at all when the signal is already aborted", async () => { + const controller = new AbortController(); + controller.abort(new Error("stopped")); + const fn = vi.fn().mockResolvedValue("ok"); + await expect(withRetry(fn, "test", { signal: controller.signal })).rejects.toThrow("stopped"); + expect(fn).not.toHaveBeenCalled(); + }); + }); }); diff --git a/tests/scrape-location.test.ts b/tests/scrape-location.test.ts index db3a1ae..888fb44 100644 --- a/tests/scrape-location.test.ts +++ b/tests/scrape-location.test.ts @@ -1,5 +1,11 @@ -import { describe, it, expect } from "vitest"; -import { assembleScrapeResult } from "../src/scraper/scrape-location.js"; +import { describe, it, expect, vi } from "vitest"; +import { + assembleScrapeResult, + navigateWithAuthFallback, + type AuthFallbackDeps, +} from "../src/scraper/scrape-location.js"; +import { authRequiredError, type SessionState } from "../src/scraper/auth.js"; +import { hasUnrecoverableKind } from "../src/core/errors.js"; import type { Business, Review } from "../src/core/schema.js"; function makeReview(id: string): Review { @@ -155,3 +161,70 @@ describe("assembleScrapeResult", () => { expect(reviews[0].id).toBe(originalFirstId); }); }); + +describe("navigateWithAuthFallback", () => { + const M1_START = "Google Maps is showing a limited view: this browser profile is not signed in"; + const M1B_START = "Google Maps is showing a limited view even though this browser profile appears to be signed in"; + + function deps(overrides: Partial> = {}) { + const navigate = vi.fn<() => Promise<{ name: string }>>(); + const waitForAuth = vi.fn<() => Promise>().mockResolvedValue(undefined); + const sessionProbe = vi.fn<() => Promise>().mockResolvedValue("expired"); + return { headless: true, navigate, waitForAuth, sessionProbe, ...overrides }; + } + + it("fails headless at once with the sign-in wording", async () => { + const d = deps(); + d.navigate.mockRejectedValue(authRequiredError()); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect((err as Error).message.startsWith(M1_START)).toBe(true); + expect(d.waitForAuth).not.toHaveBeenCalled(); + expect(d.navigate).toHaveBeenCalledTimes(1); + }); + + it("headed: waits for sign-in and returns the second navigation's result", async () => { + const d = deps({ headless: false }); + d.navigate + .mockRejectedValueOnce(authRequiredError()) + .mockResolvedValueOnce({ name: "B" }); + + await expect(navigateWithAuthFallback(d)).resolves.toEqual({ name: "B" }); + expect(d.waitForAuth).toHaveBeenCalledTimes(1); + expect(d.sessionProbe).not.toHaveBeenCalled(); + }); + + it("headed: a limited view after sign-in on a signed-in profile gets the M1b wording", async () => { + const d = deps({ headless: false }); + d.navigate.mockRejectedValue(authRequiredError()); + d.sessionProbe.mockResolvedValue("signed-in"); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect((err as Error).message.startsWith(M1B_START)).toBe(true); + expect(d.navigate).toHaveBeenCalledTimes(2); + }); + + it("falls back to the sign-in wording when the session probe fails", async () => { + const d = deps(); + d.navigate.mockRejectedValue(authRequiredError()); + d.sessionProbe.mockRejectedValue(new Error("page closed")); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect((err as Error).message.startsWith(M1_START)).toBe(true); + }); + + it("rethrows any other error unchanged without probing or prompting", async () => { + const d = deps({ headless: false }); + const boom = new Error("boom"); + d.navigate.mockRejectedValue(boom); + + await expect(navigateWithAuthFallback(d)).rejects.toBe(boom); + expect(d.sessionProbe).not.toHaveBeenCalled(); + expect(d.waitForAuth).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/selectors.test.ts b/tests/selectors.test.ts new file mode 100644 index 0000000..d6431e3 --- /dev/null +++ b/tests/selectors.test.ts @@ -0,0 +1,28 @@ +import { describe, it, expect } from "vitest"; +import { SELECTORS, TEXT_MARKERS } from "../src/scraper/selectors.js"; + +describe("SELECTORS", () => { + it("never uses Playwright's :has-text substring match", () => { + for (const value of Object.values(SELECTORS)) { + const all = Array.isArray(value) ? value : [value]; + for (const sel of all) expect(sel).not.toContain("has-text"); + } + }); + + it.each([ + ["accountButton", SELECTORS.accountButton, "SignOutOptions"], + ["signInLink", SELECTORS.signInLink, "ServiceLogin"], + ])("matches %s by its accounts.google.com href only", (_name, sel, path) => { + expect(sel).toBe(`a[href^="https://accounts.google.com/${path}"]`); + expect(sel).not.toContain("aria-label"); + }); +}); + +describe("TEXT_MARKERS", () => { + it("holds a lower-case limited-view phrase longer than 'limited view'", () => { + const marker = TEXT_MARKERS.limitedViewBanner; + expect(marker).toBe(marker.toLowerCase()); + expect(marker.length).toBeGreaterThan("limited view".length); + expect(marker).toContain("limited view"); + }); +}); diff --git a/tests/shutdown.test.ts b/tests/shutdown.test.ts new file mode 100644 index 0000000..bae1366 --- /dev/null +++ b/tests/shutdown.test.ts @@ -0,0 +1,161 @@ +import { EventEmitter } from "node:events"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { installShutdownHandlers, SIGNAL_EXIT_CODES } from "../src/core/shutdown.js"; +import { hasUnrecoverableKind } from "../src/core/errors.js"; + +/** A fake `process` that only emits signals. */ +function fakeSource() { + const emitter = new EventEmitter(); + return { + source: { on: (event: string, fn: () => void) => emitter.on(event, fn) }, + send: (event: "SIGHUP" | "SIGINT" | "SIGTERM") => emitter.emit(event), + }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("installShutdownHandlers (issue #33)", () => { + it("closes the browsers and exits 143 on SIGTERM", async () => { + const { source, send } = fakeSource(); + const cleanup = vi.fn().mockResolvedValue(undefined); + const exit = vi.fn(); + installShutdownHandlers({ source, cleanup, exit }, new AbortController()); + + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + + expect(cleanup).toHaveBeenCalledTimes(1); + expect(exit).toHaveBeenCalledWith(SIGNAL_EXIT_CODES.SIGTERM); + expect(SIGNAL_EXIT_CODES.SIGTERM).toBe(143); + }); + + it("closes the browsers and exits 130 on SIGINT", async () => { + const { source, send } = fakeSource(); + const cleanup = vi.fn().mockResolvedValue(undefined); + const exit = vi.fn(); + installShutdownHandlers({ source, cleanup, exit }, new AbortController()); + + send("SIGINT"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + + expect(cleanup).toHaveBeenCalledTimes(1); + expect(exit).toHaveBeenCalledWith(130); + }); + + it("aborts the shutdown signal before cleanup runs, so running work stops", async () => { + const { source, send } = fakeSource(); + const controller = new AbortController(); + let abortedAtCleanup: boolean | undefined; + const cleanup = vi.fn(async () => { + abortedAtCleanup = controller.signal.aborted; + }); + const exit = vi.fn(); + installShutdownHandlers({ source, cleanup, exit }, controller); + + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + + expect(abortedAtCleanup).toBe(true); + }); + + it("still exits when cleanup fails", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: () => Promise.reject(new Error("boom")), exit }, + new AbortController(), + ); + + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(143)); + }); + + it("forces the exit when cleanup hangs", async () => { + vi.useFakeTimers(); + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: () => new Promise(() => {}), exit, forceExitMs: 5_000 }, + new AbortController(), + ); + + send("SIGTERM"); + await vi.advanceTimersByTimeAsync(4_999); + expect(exit).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(exit).toHaveBeenCalledWith(143); + }); + + it("exits only once when both signals arrive", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit }, + new AbortController(), + ); + + send("SIGTERM"); + send("SIGINT"); + await vi.waitFor(() => expect(exit).toHaveBeenCalled()); + await new Promise((r) => setTimeout(r, 20)); + + expect(exit).toHaveBeenCalledTimes(1); + expect(exit).toHaveBeenCalledWith(143); + }); + + it("exits 129 on SIGHUP (terminal closed)", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit }, + new AbortController(), + ); + send("SIGHUP"); + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(129)); + }); + + it("a second signal exits at once while cleanup still hangs", async () => { + vi.useFakeTimers(); + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: () => new Promise(() => {}), exit, forceExitMs: 5_000 }, + new AbortController(), + ); + + send("SIGTERM"); + await vi.advanceTimersByTimeAsync(100); + expect(exit).not.toHaveBeenCalled(); + send("SIGTERM"); + expect(exit).toHaveBeenCalledWith(143); + await vi.advanceTimersByTimeAsync(10_000); + expect(exit).toHaveBeenCalledTimes(1); + }); + + it("aborts with a typed SHUTDOWN error, so nothing retries it", async () => { + const { source, send } = fakeSource(); + const controller = new AbortController(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit: vi.fn() }, + controller, + ); + send("SIGINT"); + expect(hasUnrecoverableKind(controller.signal.reason, "SHUTDOWN")).toBe(true); + }); + + it("handles only the signals it is given (no SIGHUP under nohup)", async () => { + const { source, send } = fakeSource(); + const exit = vi.fn(); + installShutdownHandlers( + { source, cleanup: vi.fn().mockResolvedValue(undefined), exit, signals: ["SIGINT", "SIGTERM"] }, + new AbortController(), + ); + send("SIGHUP"); + await new Promise((r) => setTimeout(r, 20)); + expect(exit).not.toHaveBeenCalled(); + send("SIGTERM"); + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(143)); + }); +}); diff --git a/tests/timeout.test.ts b/tests/timeout.test.ts new file mode 100644 index 0000000..08f6699 --- /dev/null +++ b/tests/timeout.test.ts @@ -0,0 +1,119 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { runWithTimeout } from "../src/core/timeout.js"; +import { hasUnrecoverableKind } from "../src/core/errors.js"; + +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** A task that runs until aborted, then takes `closeMs` to finish. */ +function untilAborted(events: string[], closeMs: number) { + return (signal: AbortSignal) => + new Promise((_, reject) => { + signal.addEventListener( + "abort", + () => + setTimeout(() => { + events.push("closed"); + reject(new Error("closed")); + }, closeMs), + { once: true }, + ); + }); +} + +describe("runWithTimeout (issue #33)", () => { + it("returns the task's value when it finishes in time", async () => { + await expect(runWithTimeout(async () => "ok", { timeoutMs: 1_000 })).resolves.toBe("ok"); + }); + + it("rethrows the task's own error when it fails in time", async () => { + await expect( + runWithTimeout(async () => Promise.reject(new Error("boom")), { timeoutMs: 1_000 }), + ).rejects.toThrow("boom"); + }); + + it("on timeout aborts the task and waits for it to finish before rejecting", async () => { + const events: string[] = []; + const err = await runWithTimeout(untilAborted(events, 100), { timeoutMs: 50 }).catch( + (e: unknown) => e, + ); + expect(events).toEqual(["closed"]); + expect(hasUnrecoverableKind(err, "LOCATION_TIMEOUT")).toBe(true); + expect((err as Error).message).toBe("Location timeout after 0.05s"); + }); + + it("passes the timeout as the abort reason", async () => { + let reason: unknown; + await runWithTimeout( + (signal) => + new Promise((_, reject) => + signal.addEventListener("abort", () => { + reason = signal.reason; + reject(signal.reason); + }), + ), + { timeoutMs: 20 }, + ).catch(() => {}); + expect(hasUnrecoverableKind(reason, "LOCATION_TIMEOUT")).toBe(true); + }); + + it("rejects with the timeout even when the task resolves after it", async () => { + const err = await runWithTimeout( + async () => { + await wait(100); + return "late"; + }, + { timeoutMs: 20 }, + ).catch((e: unknown) => e); + expect(hasUnrecoverableKind(err, "LOCATION_TIMEOUT")).toBe(true); + }); + + it("reports BROWSER_NOT_CLOSED when the task does not finish within the grace period", async () => { + const start = Date.now(); + const err = await runWithTimeout(() => new Promise(() => {}), { + timeoutMs: 20, + settleGraceMs: 100, + }).catch((e: unknown) => e); + expect(hasUnrecoverableKind(err, "BROWSER_NOT_CLOSED")).toBe(true); + expect(Date.now() - start).toBeLessThan(1_000); + }); + + it("stops the task when the outer signal aborts", async () => { + const outer = new AbortController(); + setTimeout(() => outer.abort(new Error("shutdown")), 20); + const err = await runWithTimeout( + (signal) => + new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason))), + { timeoutMs: 5_000, signal: outer.signal }, + ).catch((e: unknown) => e); + expect((err as Error).message).toBe("shutdown"); + }); + + describe("leaves no timer running (a stray timer kept revcli alive after the last place)", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("after success", async () => { + vi.useFakeTimers(); + await runWithTimeout(async () => "ok", { timeoutMs: 60_000 }); + expect(vi.getTimerCount()).toBe(0); + }); + + it("after the task fails", async () => { + vi.useFakeTimers(); + await runWithTimeout(async () => Promise.reject(new Error("x")), { timeoutMs: 60_000 }).catch(() => {}); + expect(vi.getTimerCount()).toBe(0); + }); + + it("after a timeout", async () => { + vi.useFakeTimers(); + const done = runWithTimeout( + (signal) => new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason))), + { timeoutMs: 1_000 }, + ).catch(() => {}); + await vi.advanceTimersByTimeAsync(1_000); + await done; + expect(vi.getTimerCount()).toBe(0); + }); + }); +}); diff --git a/tests/unrecoverable.test.ts b/tests/unrecoverable.test.ts index e468601..a63b8bd 100644 --- a/tests/unrecoverable.test.ts +++ b/tests/unrecoverable.test.ts @@ -1,6 +1,26 @@ import { describe, it, expect } from "vitest"; import { isUnrecoverable } from "../src/core/retry.js"; -import { UnrecoverableError } from "../src/core/errors.js"; +import { UnrecoverableError, hasUnrecoverableKind } from "../src/core/errors.js"; + +describe("hasUnrecoverableKind", () => { + it("is true for an UnrecoverableError of the given kind", () => { + expect( + hasUnrecoverableKind(new UnrecoverableError("AUTH_REQUIRED", "x"), "AUTH_REQUIRED"), + ).toBe(true); + }); + + it("is false for an UnrecoverableError of another kind", () => { + expect( + hasUnrecoverableKind(new UnrecoverableError("NOT_A_PLACE", "x"), "AUTH_REQUIRED"), + ).toBe(false); + }); + + it("is false for plain errors and non-errors", () => { + expect(hasUnrecoverableKind(new Error("AUTH_REQUIRED"), "AUTH_REQUIRED")).toBe(false); + expect(hasUnrecoverableKind("AUTH_REQUIRED", "AUTH_REQUIRED")).toBe(false); + expect(hasUnrecoverableKind(undefined, "AUTH_REQUIRED")).toBe(false); + }); +}); describe("isUnrecoverable", () => { it("detects 'invalid input'", () => { @@ -52,6 +72,11 @@ describe("isUnrecoverable", () => { expect(isUnrecoverable(new UnrecoverableError("SORT_VERIFY", ""))).toBe(true); }); + it("detects the AUTH_REQUIRED and NOT_A_PLACE kinds", () => { + expect(isUnrecoverable(new UnrecoverableError("AUTH_REQUIRED", "limited view"))).toBe(true); + expect(isUnrecoverable(new UnrecoverableError("NOT_A_PLACE", "search page"))).toBe(true); + }); + it("matches the exact navigation verification error template thrown by navigator.ts", () => { // Pin the exact message shape so retry.ts classifier and navigator.ts // thrower cannot silently drift apart. Mirrors navigator.ts:58-62 template. diff --git a/tests/url.test.ts b/tests/url.test.ts index 4b264fa..daf369c 100644 --- a/tests/url.test.ts +++ b/tests/url.test.ts @@ -5,8 +5,59 @@ import { extractPlaceIdFromUrl, placeIdsMatch, canVerifyPlaceIdFormat, + isSearchResultsUrl, + isShortLinkUrl, + SHORT_LINK_HOST, } from "../src/utils/url.js"; +describe("isShortLinkUrl", () => { + it("is true for a maps.app.goo.gl share link", () => { + expect(SHORT_LINK_HOST).toBe("maps.app.goo.gl"); + expect(isShortLinkUrl("https://maps.app.goo.gl/MTVGWdpd8vVqTouv9")).toBe(true); + expect(isShortLinkUrl("http://maps.app.goo.gl/abc?g_st=ic")).toBe(true); + }); + + it.each([ + "https://www.google.com/maps/place/Test/@0,0,15z", + "https://www.google.com/maps?continue=https://maps.app.goo.gl/abc", + "https://maps.app.goo.gl.example.com/abc", + "https://evilmaps.app.goo.gl/abc", + "not a url", + "", + ])("is false for %s", (url) => { + expect(isShortLinkUrl(url)).toBe(false); + }); + + it("is the same host that parseGoogleMapsInput treats as a short URL", () => { + expect(parseGoogleMapsInput(`https://${SHORT_LINK_HOST}/abc123`).isShortUrl).toBe(true); + expect(() => parseGoogleMapsInput("https://mapsXappXgooXgl/abc123")).toThrow(/Invalid input/); + }); +}); + +describe("isSearchResultsUrl", () => { + it("is true for a /maps/search/ page, tracking params included", () => { + expect( + isSearchResultsUrl( + "https://www.google.com/maps/search/coffee+near+me/@52.23,21.01,14z?entry=ttu&g_ep=EgoyMDI2", + ), + ).toBe(true); + expect(isSearchResultsUrl("https://www.google.pl/maps/search/foo/@1,2,3z?hl=en")).toBe(true); + }); + + it.each([ + "https://www.google.com/maps/place/Optimo+Nakheel/@24.74,46.64,867m/data=!1s0x3e2ee3641f7016d7:0x8e3a8bcf52dad296", + "https://www.google.com/maps?cid=1234567890", + "https://www.google.com/maps?ftid=0x3e2ee3641f7016d7:0x8e3a8bcf52dad296", + "https://www.google.com/maps/place/?q=place_id:ChIJN1t_tDeuEmsRUsoyG83frY4", + "https://www.google.com/maps/place/Caf%C3%A9+S%C5%82odki/@52.2,21.0,17z", + "https://www.google.com/maps/searchable-place/", + "not a url", + "", + ])("is false for %s", (url) => { + expect(isSearchResultsUrl(url)).toBe(false); + }); +}); + describe("parseGoogleMapsInput", () => { it("parses a long Google Maps URL", () => { const url =