-
Notifications
You must be signed in to change notification settings - Fork 510
feat: implement Browse AI plugin against official v2 API #1042
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
devjain32
merged 4 commits into
corsairdev:main
from
TanayGurav19:feat/browserai-plugin
Aug 27, 2026
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
33cad53
feat: add BrowserAI plugin scaffold
d05846e
feat: implement Browse AI plugin against official v2 API
Dhirenderchoudhary 54a4223
fix: parse Browse AI responses and stop retrying writes on 429
Dhirenderchoudhary 8098a6f
chore: merge main into feat/browserai-plugin
Dhirenderchoudhary File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| /** | ||
| * Transport: Bearer token, JSON POST, official v2 base. | ||
| * Credentials here are fictional. | ||
| */ | ||
| import { BROWSEAI_API_BASE, makeBrowseaiRequest } from './client'; | ||
|
|
||
| let captured: | ||
| | { | ||
| url: string; | ||
| method: string; | ||
| headers: Record<string, string>; | ||
| body?: string; | ||
| } | ||
| | undefined; | ||
|
|
||
| const realFetch = global.fetch; | ||
| afterEach(() => { | ||
| global.fetch = realFetch; | ||
| }); | ||
|
|
||
| function mockFetch(payload: unknown, status = 200) { | ||
| captured = undefined; | ||
| global.fetch = (async (url: unknown, init?: RequestInit) => { | ||
| const headers: Record<string, string> = {}; | ||
| const raw = init?.headers; | ||
| if (raw instanceof Headers) { | ||
| raw.forEach((value, key) => { | ||
| headers[key.toLowerCase()] = value; | ||
| }); | ||
| } | ||
| captured = { | ||
| url: String(url), | ||
| method: init?.method ?? 'GET', | ||
| headers, | ||
| body: typeof init?.body === 'string' ? init.body : undefined, | ||
| }; | ||
| return { | ||
| ok: status < 400, | ||
| status, | ||
| statusText: status < 400 ? 'OK' : 'Error', | ||
| url: String(url), | ||
| headers: new Headers({ 'Content-Type': 'application/json' }), | ||
| json: async () => payload, | ||
| text: async () => JSON.stringify(payload), | ||
| }; | ||
| }) as unknown as typeof global.fetch; | ||
| } | ||
|
|
||
| describe('makeBrowseaiRequest', () => { | ||
| it('hits the documented v2 base', async () => { | ||
| mockFetch({ tasksQueueStatus: 'OK' }); | ||
| await makeBrowseaiRequest('status', 'tok'); | ||
| expect(captured?.url.startsWith(`${BROWSEAI_API_BASE}/status`)).toBe(true); | ||
| }); | ||
|
|
||
| it('sends the API key as Bearer', async () => { | ||
| mockFetch({}); | ||
| await makeBrowseaiRequest('robots', 'secret-key'); | ||
| expect(captured?.headers.authorization).toBe('Bearer secret-key'); | ||
| }); | ||
|
|
||
| it('POSTs JSON bodies', async () => { | ||
| mockFetch({ statusCode: 200, result: { id: 't1' } }); | ||
| await makeBrowseaiRequest('robots/r1/tasks', 'tok', { | ||
| method: 'POST', | ||
| body: { recordVideo: false }, | ||
| }); | ||
| expect(captured?.method).toBe('POST'); | ||
| expect(captured?.headers['content-type']).toContain('application/json'); | ||
| expect(captured?.body).toBe('{"recordVideo":false}'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import type { | ||
| ApiRequestOptions, | ||
| OpenAPIConfig, | ||
| RateLimitConfig, | ||
| } from 'corsair/http'; | ||
| import { request } from 'corsair/http'; | ||
|
|
||
| /** | ||
| * Official v2 base. Auth is `Authorization: Bearer <api key>`. | ||
| * | ||
| * @see https://docs.browse.ai/api/ | ||
| */ | ||
| export const BROWSEAI_API_BASE = 'https://api.browse.ai/v2'; | ||
|
|
||
| const BROWSEAI_RATE_LIMIT_CONFIG: RateLimitConfig = { | ||
| enabled: true, | ||
| maxRetries: 3, | ||
| initialRetryDelay: 1000, | ||
| backoffMultiplier: 2, | ||
| headerNames: { | ||
| retryAfter: 'retry-after', | ||
| }, | ||
| }; | ||
|
|
||
| export type BrowseaiRequestOptions = { | ||
| method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; | ||
| body?: Record<string, unknown>; | ||
| query?: Record<string, string | number | boolean | undefined>; | ||
| }; | ||
|
|
||
| function buildConfig(apiKey: string): OpenAPIConfig { | ||
| return { | ||
| BASE: BROWSEAI_API_BASE, | ||
| VERSION: '2', | ||
| WITH_CREDENTIALS: false, | ||
| CREDENTIALS: 'omit', | ||
| TOKEN: apiKey, | ||
| HEADERS: { | ||
| Accept: 'application/json', | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| export async function makeBrowseaiRequest<T>( | ||
| endpoint: string, | ||
| apiKey: string, | ||
| options: BrowseaiRequestOptions = {}, | ||
| ): Promise<T> { | ||
| const { method = 'GET', body, query } = options; | ||
| const isWrite = method === 'POST' || method === 'PUT' || method === 'PATCH'; | ||
|
|
||
| const requestOptions: ApiRequestOptions = { | ||
| method, | ||
| url: endpoint, | ||
| body: isWrite ? body : undefined, | ||
| mediaType: isWrite ? 'application/json; charset=utf-8' : undefined, | ||
| query, | ||
| }; | ||
|
|
||
| return await request<T>(buildConfig(apiKey), requestOptions, { | ||
| rateLimitConfig: BROWSEAI_RATE_LIMIT_CONFIG, | ||
| }); | ||
| } | ||
|
|
||
| export { BROWSEAI_RATE_LIMIT_CONFIG }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,198 @@ | ||
| import { logEventFromContext } from 'corsair/core'; | ||
| import { | ||
| bulkRun, | ||
| createMonitor, | ||
| createWebhook, | ||
| deleteMonitor, | ||
| getStatus, | ||
| getTask, | ||
| listRobots, | ||
| listTasks, | ||
| listWebhooks, | ||
| runRobot, | ||
| } from './endpoints'; | ||
| import { browseaiEndpointMeta, browseaiEndpointSchemas } from './index'; | ||
|
|
||
| jest.mock('corsair/core', () => ({ | ||
| logEventFromContext: jest.fn(async () => undefined), | ||
| })); | ||
|
|
||
| const mockLogEvent = logEventFromContext as jest.MockedFunction< | ||
| typeof logEventFromContext | ||
| >; | ||
|
|
||
| type Ctx = Parameters<typeof getStatus>[0]; | ||
|
|
||
| function makeCtx() { | ||
| return { | ||
| key: 'test-token', | ||
| options: { authType: 'api_key' }, | ||
| } as unknown as Ctx; | ||
| } | ||
|
|
||
| let captured: { url: string; method: string; body?: string } | undefined; | ||
|
|
||
| const realFetch = global.fetch; | ||
| afterEach(() => { | ||
| global.fetch = realFetch; | ||
| mockLogEvent.mockClear(); | ||
| }); | ||
|
|
||
| function mockFetch(payload: unknown, status = 200) { | ||
| captured = undefined; | ||
| global.fetch = (async (url: unknown, init?: RequestInit) => { | ||
| captured = { | ||
| url: String(url), | ||
| method: init?.method ?? 'GET', | ||
| body: typeof init?.body === 'string' ? init.body : undefined, | ||
| }; | ||
| return { | ||
| ok: status < 400, | ||
| status, | ||
| statusText: 'OK', | ||
| url: String(url), | ||
| headers: new Headers({ 'Content-Type': 'application/json' }), | ||
| json: async () => payload, | ||
| text: async () => JSON.stringify(payload), | ||
| }; | ||
| }) as unknown as typeof global.fetch; | ||
| } | ||
|
|
||
| function pathAndQuery(): { path: string; query: URLSearchParams } { | ||
| const url = new URL(captured?.url ?? 'http://invalid'); | ||
| return { path: url.pathname, query: url.searchParams }; | ||
| } | ||
|
|
||
| describe('Browse AI endpoints', () => { | ||
| it('system.getStatus calls GET /status', async () => { | ||
| mockFetch({ | ||
| statusCode: 200, | ||
| messageCode: 'success', | ||
| tasksQueueStatus: 'OK', | ||
| }); | ||
| const out = await getStatus(makeCtx(), {}); | ||
| expect(pathAndQuery().path).toBe('/v2/status'); | ||
| expect(out.tasksQueueStatus).toBe('OK'); | ||
| }); | ||
|
|
||
| it('robots.list calls GET /robots', async () => { | ||
| mockFetch({ | ||
| statusCode: 200, | ||
| robots: { totalCount: 1, items: [{ id: 'r1', name: 'Bot' }] }, | ||
| }); | ||
| const out = await listRobots(makeCtx(), {}); | ||
| expect(pathAndQuery().path).toBe('/v2/robots'); | ||
| expect(out.robots?.items?.[0]?.id).toBe('r1'); | ||
| }); | ||
|
|
||
| it('robots.run POSTs /robots/{id}/tasks', async () => { | ||
| mockFetch({ statusCode: 200, result: { id: 't1', robotId: 'r1' } }); | ||
| const out = await runRobot(makeCtx(), { | ||
| robotId: 'r1', | ||
| recordVideo: true, | ||
| inputParameters: { originUrl: 'https://example.com' }, | ||
| }); | ||
| expect(captured?.method).toBe('POST'); | ||
| expect(pathAndQuery().path).toBe('/v2/robots/r1/tasks'); | ||
| expect(captured?.body).toContain('originUrl'); | ||
| expect(out.result?.id).toBe('t1'); | ||
| }); | ||
|
|
||
| it('robots.bulkRun POSTs /robots/{id}/bulk-runs', async () => { | ||
| mockFetch({ | ||
| statusCode: 200, | ||
| result: { bulkRun: { id: 'b1', robotId: 'r1' } }, | ||
| }); | ||
| await bulkRun(makeCtx(), { | ||
| robotId: 'r1', | ||
| title: 'Batch', | ||
| inputParameters: [{ originUrl: 'https://example.com' }], | ||
| }); | ||
| expect(captured?.method).toBe('POST'); | ||
| expect(pathAndQuery().path).toBe('/v2/robots/r1/bulk-runs'); | ||
| expect(captured?.body).toContain('Batch'); | ||
| }); | ||
|
|
||
| it('tasks.list paginates GET /robots/{id}/tasks', async () => { | ||
| mockFetch({ | ||
| statusCode: 200, | ||
| result: { | ||
| robotTasks: { totalCount: 0, pageNumber: 2, hasMore: false, items: [] }, | ||
| }, | ||
| }); | ||
| await listTasks(makeCtx(), { | ||
| robotId: 'r1', | ||
| page: 2, | ||
| pageSize: 10, | ||
| status: 'successful', | ||
| includeRetried: false, | ||
| }); | ||
| const { path, query } = pathAndQuery(); | ||
| expect(path).toBe('/v2/robots/r1/tasks'); | ||
| expect(query.get('page')).toBe('2'); | ||
| expect(query.get('pageSize')).toBe('10'); | ||
| expect(query.get('status')).toBe('successful'); | ||
| expect(query.get('includeRetried')).toBe('false'); | ||
| }); | ||
|
|
||
| it('tasks.get calls GET /robots/{id}/tasks/{taskId}', async () => { | ||
| mockFetch({ statusCode: 200, result: { id: 't1' } }); | ||
| await getTask(makeCtx(), { robotId: 'r1', taskId: 't1' }); | ||
| expect(pathAndQuery().path).toBe('/v2/robots/r1/tasks/t1'); | ||
| }); | ||
|
|
||
| it('monitors.create POSTs documented monitor fields', async () => { | ||
| mockFetch({ statusCode: 200, monitor: { id: 'm1', name: 'Watch' } }); | ||
| await createMonitor(makeCtx(), { | ||
| robotId: 'r1', | ||
| name: 'Watch', | ||
| inputParameters: { originUrl: 'https://example.com' }, | ||
| notifyOnCapturedScreenshotChange: true, | ||
| notifyOnCapturedTextChange: false, | ||
| capturedScreenshotNotificationThreshold: 15, | ||
| schedule: 'FREQ=DAILY;INTERVAL=1', | ||
| }); | ||
| expect(captured?.method).toBe('POST'); | ||
| expect(pathAndQuery().path).toBe('/v2/robots/r1/monitors'); | ||
| expect(captured?.body).toContain('notifyOnCapturedScreenshotChange'); | ||
| expect(captured?.body).toContain('FREQ=DAILY'); | ||
| }); | ||
|
|
||
| it('monitors.delete DELETEs /robots/{id}/monitors/{monitorId}', async () => { | ||
| mockFetch({ statusCode: 200, messageCode: 'success' }); | ||
| await deleteMonitor(makeCtx(), { robotId: 'r1', monitorId: 'm1' }); | ||
| expect(captured?.method).toBe('DELETE'); | ||
| expect(pathAndQuery().path).toBe('/v2/robots/r1/monitors/m1'); | ||
| }); | ||
|
|
||
| it('webhooks.create POSTs hookUrl and eventType', async () => { | ||
| mockFetch({ | ||
| statusCode: 200, | ||
| webhook: { id: 'w1', url: 'https://example.com/hook' }, | ||
| }); | ||
| await createWebhook(makeCtx(), { | ||
| robotId: 'r1', | ||
| hookUrl: 'https://example.com/hook', | ||
| eventType: 'taskFinished', | ||
| }); | ||
| expect(captured?.method).toBe('POST'); | ||
| expect(pathAndQuery().path).toBe('/v2/robots/r1/webhooks'); | ||
| expect(captured?.body).toContain('hookUrl'); | ||
| expect(captured?.body).toContain('taskFinished'); | ||
| }); | ||
|
|
||
| it('webhooks.list calls GET /robots/{id}/webhooks', async () => { | ||
| mockFetch({ | ||
| statusCode: 200, | ||
| webhooks: { totalCount: 0, items: [] }, | ||
| }); | ||
| await listWebhooks(makeCtx(), { robotId: 'r1' }); | ||
| expect(pathAndQuery().path).toBe('/v2/robots/r1/webhooks'); | ||
| }); | ||
|
|
||
| it('covers every registered operation', () => { | ||
| expect(Object.keys(browseaiEndpointMeta).sort()).toEqual( | ||
| Object.keys(browseaiEndpointSchemas).sort(), | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| export { | ||
| bulkRun, | ||
| createMonitor, | ||
| createWebhook, | ||
| deleteMonitor, | ||
| getStatus, | ||
| getTask, | ||
| listRobots, | ||
| listTasks, | ||
| listWebhooks, | ||
| runRobot, | ||
| } from './ops'; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.