diff options
Diffstat (limited to 'castle-search/src/search.ts')
| -rw-r--r-- | castle-search/src/search.ts | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/castle-search/src/search.ts b/castle-search/src/search.ts index b5effb8..1ddd523 100644 --- a/castle-search/src/search.ts +++ b/castle-search/src/search.ts @@ -393,3 +393,42 @@ export const resolveLink = async (url: string, signal: AbortSignal): Promise<Res }; const isGoogleHost = (url: string): boolean => /^https?:\/\/([a-z0-9-]+\.)*google\.(?:com?\.)?[a-z]{2,3}\//.test(url); + +/** + * Runs `fn` on a fresh background tab of the shared browser, under the same + * concurrency cap and connection as a search, and closes the tab on every path. + * For page work that is not an engine search, such as x-search.ts. + */ +export const withPage = async <T>( + signal: AbortSignal, + fn: (page: PageSession, endpoint: string) => Promise<T>, + options: { isolated?: boolean } = {}, +): Promise<T> => { + const release = await acquire(signal); + try { + const conn = await ensureConnection(signal); + const endpoint = describeCdpTarget(conn.target); + // isolated: a browser context of its own, with none of the profile's + // cookies, thrown away afterwards with everything in it. + let context: string | undefined; + if (options.isolated) { + const created = await conn.send("Target.createBrowserContext", { disposeOnDetach: true }); + if (typeof created["browserContextId"] !== "string") { + throw new BrowserUnavailableError("Target.createBrowserContext did not return a browserContextId"); + } + context = created["browserContextId"]; + } + try { + const page = await PageSession.open(conn, signal, context); + try { + return await fn(page, endpoint); + } finally { + await page.close(); + } + } finally { + if (context) await conn.send("Target.disposeBrowserContext", { browserContextId: context }).catch(() => {}); + } + } finally { + release(); + } +}; |
