From 2d5f46da503fe641783013df5b96a97cd4885622 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 16:47:37 +0300 Subject: [PATCH 01/31] feat: add client debug mode --- README.md | 15 +++++++++++++++ src/client.ts | 29 +++++++++++++++++++++++++---- tests/unit/async/client.test.js | 31 +++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index cbeed12..22751b9 100644 --- a/README.md +++ b/README.md @@ -35,11 +35,13 @@ Full API reference (all endpoints, error codes, captcha-type details): **https:/ - [Image to Text](#image-to-text) - [GeeTest (v3 & v4)](#geetest-v3--v4) - [Yandex SmartCaptcha](#yandex-smartcaptcha) + - [Kaleidoscope puzzle](#kaleidoscope-puzzle) - [Coordinates (click captcha)](#coordinates-click-captcha) - [Tencent](#tencent) - [Advanced Usage](#advanced-usage) - [Check balance](#check-balance) - [Custom timeout and polling](#custom-timeout-and-polling) + - [Debug mode](#debug-mode) - [Worker language pool](#worker-language-pool) - [Solving multiple captchas in parallel](#solving-multiple-captchas-in-parallel) - [Error handling](#error-handling) @@ -677,6 +679,19 @@ const captchaSolver = new CaptchaClient({ }); ``` +### Debug mode + +Enable `debug` to print sanitized request and polling lifecycle events. Debug output +includes endpoint names, HTTP status codes, task IDs, and task statuses; it never +includes the API key, task payload, or solution. + +```javascript +const captchaSolver = new CaptchaClient({ + clientKey: 'your_api_key', + debug: true +}); +``` + ### Worker language pool Pass `languagePool` as the second argument to `solve()` (or `createTask()`) to pick a diff --git a/src/client.ts b/src/client.ts index 3039fe1..24d333f 100644 --- a/src/client.ts +++ b/src/client.ts @@ -24,6 +24,12 @@ export interface CaptchaClientOptions { * @defaultValue `5000` */ pollingInterval?: number; + /** + * Print request and polling lifecycle events to `console.debug`. + * API keys, task payloads, and solutions are never included. + * @defaultValue `false` + */ + debug?: boolean; } /** Raw response of `/getTaskResult` (and, structurally, of every other API endpoint). */ @@ -72,14 +78,23 @@ export class CaptchaClient { timeout: number; /** Delay between polls inside {@link solve}, in milliseconds. */ pollingInterval: number; + /** Whether lifecycle debug logging is enabled. */ + debug: boolean; /** * @param options - Client options; only `clientKey` is required. * @throws {ValidationError} If `clientKey` is empty. */ - constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000 }: CaptchaClientOptions = {} as CaptchaClientOptions) { + constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false }: CaptchaClientOptions = {} as CaptchaClientOptions) { if (!clientKey) throw new ValidationError('clientKey is required'); - this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; + this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; this.debug = debug; + } + + /** Write a sanitized lifecycle event when debug mode is enabled. */ + private _debug(message: string, details?: Record): void { + if (!this.debug) return; + if (details) console.debug(`[CaptchaClient] ${message}`, details); + else console.debug(`[CaptchaClient] ${message}`); } /** @@ -97,13 +112,16 @@ export class CaptchaClient { */ protected async _request(endpoint: string, payload: Record): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); + this._debug('request started', { endpoint }); try { const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }, body: JSON.stringify(payload), signal: controller.signal }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); const data = await response.json() as TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); + this._debug('request completed', { endpoint, status: response.status }); return data; } catch (error) { + this._debug('request failed', { endpoint, error: error instanceof Error ? error.name : 'UnknownError' }); if (error instanceof ApiError || error instanceof NetworkError) throw error; if (error && typeof error === 'object' && 'name' in error && error.name === 'AbortError') throw new TimeoutError(`Request timed out after ${this.timeout}ms`); throw new NetworkError(error instanceof Error ? error.message : String(error), error); @@ -131,7 +149,9 @@ export class CaptchaClient { */ async createTask(task: BaseTask, languagePool: string | null = null): Promise { const payload: Record = { clientKey: this.clientKey, task: task.toDict() }; if (languagePool !== null) payload.languagePool = languagePool; - return (await this._request('/createTask', payload)).taskId as number; + const taskId = (await this._request('/createTask', payload)).taskId as number; + this._debug('task created', { taskId }); + return taskId; } /** @@ -195,7 +215,8 @@ export class CaptchaClient { const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); await new Promise(resolve => setTimeout(resolve, Math.min(this.pollingInterval, remaining))); if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - const result = await this.getTaskResult(taskId); if (result.status === 'ready') return (result.solution ?? {}) as SolutionOf; + const result = await this.getTaskResult(taskId); this._debug('task status received', { taskId, status: result.status }); + if (result.status === 'ready') { this._debug('task solved', { taskId }); return (result.solution ?? {}) as SolutionOf; } } } } diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index a612f53..0d7b9b9 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -39,6 +39,37 @@ describe('CaptchaClient (async)', () => { expect(requestOptions.headers['X-SDK']).toBe('javascript-sdk/1.1.0'); }); + test('debug mode logs sanitized request lifecycle events', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) + })); + + await client.getBalance(); + + expect(debug).toHaveBeenCalledWith('[CaptchaClient] request started', { endpoint: '/getBalance' }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] request completed', { endpoint: '/getBalance', status: 200 }); + expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); + debug.mockRestore(); + }); + + test('debug mode is silent by default', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + global.fetch = jest.fn(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) + })); + + await client.getBalance(); + + expect(debug).not.toHaveBeenCalled(); + debug.mockRestore(); + }); + test('aborts an HTTP request after timeout', async () => { client.timeout = 10; global.fetch = jest.fn((url, options) => new Promise((resolve, reject) => { From 58dfee8d905ea4cde06e2914e82c72bb146ec806 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 16:53:53 +0300 Subject: [PATCH 02/31] feat: expand debug lifecycle logging --- README.md | 1 + src/client.ts | 36 ++++++++++++++++++----- tests/unit/async/client.test.js | 52 ++++++++++++++++++++++++++++++++- 3 files changed, 80 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 22751b9..8316bcd 100644 --- a/README.md +++ b/README.md @@ -686,6 +686,7 @@ includes endpoint names, HTTP status codes, task IDs, and task statuses; it neve includes the API key, task payload, or solution. ```javascript +// Create a client with detailed, sanitized lifecycle logging enabled. const captchaSolver = new CaptchaClient({ clientKey: 'your_api_key', debug: true diff --git a/src/client.ts b/src/client.ts index 24d333f..b3e7f6d 100644 --- a/src/client.ts +++ b/src/client.ts @@ -88,9 +88,14 @@ export class CaptchaClient { constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false }: CaptchaClientOptions = {} as CaptchaClientOptions) { if (!clientKey) throw new ValidationError('clientKey is required'); this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; this.debug = debug; + this._debug('client initialized', { baseUrl, timeout, pollingInterval }); } - /** Write a sanitized lifecycle event when debug mode is enabled. */ + /** + * Write a sanitized lifecycle event when debug mode is enabled. + * Callers pass only operational metadata here so credentials, CAPTCHA image + * data, task payloads, and solutions cannot leak into console output. + */ private _debug(message: string, details?: Record): void { if (!this.debug) return; if (details) console.debug(`[CaptchaClient] ${message}`, details); @@ -112,16 +117,17 @@ export class CaptchaClient { */ protected async _request(endpoint: string, payload: Record): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); + const startedAt = Date.now(); this._debug('request started', { endpoint }); try { const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }, body: JSON.stringify(payload), signal: controller.signal }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); const data = await response.json() as TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); - this._debug('request completed', { endpoint, status: response.status }); + this._debug('request completed', { endpoint, status: response.status, durationMs: Date.now() - startedAt }); return data; } catch (error) { - this._debug('request failed', { endpoint, error: error instanceof Error ? error.name : 'UnknownError' }); + this._debug('request failed', { endpoint, error: error instanceof Error ? error.name : 'UnknownError', durationMs: Date.now() - startedAt }); if (error instanceof ApiError || error instanceof NetworkError) throw error; if (error && typeof error === 'object' && 'name' in error && error.name === 'AbortError') throw new TimeoutError(`Request timed out after ${this.timeout}ms`); throw new NetworkError(error instanceof Error ? error.message : String(error), error); @@ -148,9 +154,12 @@ export class CaptchaClient { * ``` */ async createTask(task: BaseTask, languagePool: string | null = null): Promise { - const payload: Record = { clientKey: this.clientKey, task: task.toDict() }; if (languagePool !== null) payload.languagePool = languagePool; + const taskPayload = task.toDict(); + const taskType = typeof taskPayload.type === 'string' ? taskPayload.type : task.constructor.name; + this._debug('task submission started', { taskType, languagePool }); + const payload: Record = { clientKey: this.clientKey, task: taskPayload }; if (languagePool !== null) payload.languagePool = languagePool; const taskId = (await this._request('/createTask', payload)).taskId as number; - this._debug('task created', { taskId }); + this._debug('task created', { taskId, taskType }); return taskId; } @@ -210,13 +219,24 @@ export class CaptchaClient { * ``` */ async solve>(task: T, languagePool: string | null = null): Promise> { + const taskType = task.constructor.name; + this._debug('solve started', { taskType }); const taskId = await this.createTask(task, languagePool); const startedAt = Date.now(); + let pollAttempt = 0; while (true) { const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - await new Promise(resolve => setTimeout(resolve, Math.min(this.pollingInterval, remaining))); + const delayMs = Math.min(this.pollingInterval, remaining); + pollAttempt += 1; + this._debug('waiting before poll', { taskId, pollAttempt, delayMs }); + await new Promise(resolve => setTimeout(resolve, delayMs)); if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - const result = await this.getTaskResult(taskId); this._debug('task status received', { taskId, status: result.status }); - if (result.status === 'ready') { this._debug('task solved', { taskId }); return (result.solution ?? {}) as SolutionOf; } + const result = await this.getTaskResult(taskId); + const elapsedMs = Date.now() - startedAt; + this._debug('task status received', { taskId, pollAttempt, status: result.status, elapsedMs }); + if (result.status === 'ready') { + this._debug('task solved', { taskId, pollAttempts: pollAttempt, elapsedMs }); + return (result.solution ?? {}) as SolutionOf; + } } } } diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 0d7b9b9..6e09dc2 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -51,11 +51,61 @@ describe('CaptchaClient (async)', () => { await client.getBalance(); expect(debug).toHaveBeenCalledWith('[CaptchaClient] request started', { endpoint: '/getBalance' }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] request completed', { endpoint: '/getBalance', status: 200 }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] client initialized', { + baseUrl: 'https://api.captcha-solver.com', + timeout: 120000, + pollingInterval: 5000 + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] request completed', { + endpoint: '/getBalance', + status: 200, + durationMs: expect.any(Number) + }); expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); debug.mockRestore(); }); + test('debug mode logs task type, task ID, and polling progress', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) + })) + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: 'secret_solution' } }) + })); + const task = new Tasks.RecaptchaV2Proxyless({ + websiteURL: 'https://example.com', + websiteKey: 'website_key' + }); + + await client.solve(task); + + expect(debug).toHaveBeenCalledWith('[CaptchaClient] task created', { + taskId: 12345, + taskType: 'RecaptchaV2TaskProxyless' + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] task status received', { + taskId: 12345, + pollAttempt: 1, + status: 'ready', + elapsedMs: expect.any(Number) + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] task solved', { + taskId: 12345, + pollAttempts: 1, + elapsedMs: expect.any(Number) + }); + expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_solution'); + expect(JSON.stringify(debug.mock.calls)).not.toContain('website_key'); + debug.mockRestore(); + }); + test('debug mode is silent by default', async () => { const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); global.fetch = jest.fn(() => Promise.resolve({ From c264312ad5f7eaa8cf382cc9d36b60714a0b557c Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 16:58:08 +0300 Subject: [PATCH 03/31] docs: explain example execution flows --- examples/balance.js | 23 +++++----- examples/coordinates.js | 29 ++++++++++++- examples/coordinates_traffic_lights.js | 29 ++++++++++++- examples/geetest_v3.js | 39 ++++++++++++++--- examples/geetest_v3_proxy.js | 45 +++++++++++++++----- examples/geetest_v4.js | 29 ++++++++++++- examples/geetest_v4_proxy.js | 29 ++++++++++++- examples/image_to_text.js | 29 ++++++++++++- examples/image_to_text_language_pool.js | 29 ++++++++++++- examples/image_to_text_math.js | 29 ++++++++++++- examples/recaptcha_v2.js | 29 ++++++++++++- examples/recaptcha_v2_enterprise.js | 29 ++++++++++++- examples/recaptcha_v2_enterprise_proxy.js | 29 ++++++++++++- examples/recaptcha_v2_proxy.js | 29 ++++++++++++- examples/recaptcha_v3.js | 32 +++++++++++--- examples/tencent.js | 29 ++++++++++++- examples/tencent_proxy.js | 29 ++++++++++++- examples/turnstile.js | 29 ++++++++++++- examples/turnstile_proxy.js | 29 ++++++++++++- examples/yandex_smartcaptcha.js | 29 ++++++++++++- examples/yandex_smartcaptcha_image.js | 29 ++++++++++++- examples/yandex_smartcaptcha_kaleidoscope.js | 22 +++++++++- examples/yandex_smartcaptcha_proxy.js | 29 ++++++++++++- 23 files changed, 613 insertions(+), 70 deletions(-) diff --git a/examples/balance.js b/examples/balance.js index 5afc88e..cded72e 100644 --- a/examples/balance.js +++ b/examples/balance.js @@ -1,24 +1,27 @@ +import 'dotenv/config'; +import { CaptchaClient } from '@captcha-solver-api/javascript-sdk'; + /** - * Example: Get account balance. + * Check the current Captcha Solver account balance without creating a CAPTCHA task. + * Set the CAPTCHA_API_KEY environment variable before running this example. * - * Prerequisites: - * Set the CAPTCHA_API_KEY environment variable. - * Returns the current available balance of your account. + * How it works: + * STEP-01 - Read the API key and configure the SDK client. + * STEP-02 - Request the account balance with CaptchaClient.getBalance(). + * STEP-03 - Print the returned amount or report an error. */ -import 'dotenv/config'; -import { CaptchaClient } from '@captcha-solver-api/javascript-sdk'; - +// STEP-01: Read the API key and configure the SDK client. const apiKey = process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY'; - const captchaSolver = new CaptchaClient({ clientKey: apiKey }); -// Get the current account balance. -// Returns a float with the available amount in your account currency. +// STEP-02: Request the balance; this method does not create a CAPTCHA task. captchaSolver.getBalance() .then((balance) => { + // STEP-03: Print the available amount in the account currency. console.log('Balance:', balance); }) .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. console.error(error); }); diff --git a/examples/coordinates.js b/examples/coordinates.js index fb6c748..f4178d0 100644 --- a/examples/coordinates.js +++ b/examples/coordinates.js @@ -2,12 +2,37 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a coordinate CAPTCHA from a local image without a proxy. + * It creates Tasks.CoordinatesTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.CoordinatesTask({ body: fs.readFileSync(new URL('./assets/coordinates-captcha.png', import.meta.url)).toString('base64'), comment: 'Click on the green apple' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.coordinates)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.coordinates); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/coordinates_traffic_lights.js b/examples/coordinates_traffic_lights.js index 00ee1ab..998d637 100644 --- a/examples/coordinates_traffic_lights.js +++ b/examples/coordinates_traffic_lights.js @@ -2,7 +2,24 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve an instruction-image coordinate CAPTCHA without a proxy. + * It creates Tasks.CoordinatesTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.CoordinatesTask({ body: fs.readFileSync(new URL('./assets/traffic-lights.png', import.meta.url)).toString('base64'), imgInstructions: fs.readFileSync(new URL('./assets/traffic-lights-instructions.png', import.meta.url)).toString('base64'), @@ -10,6 +27,14 @@ const task = new Tasks.CoordinatesTask({ maxClicks: 5 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.coordinates)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.coordinates); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v3.js b/examples/geetest_v3.js index 12223f2..d4125d5 100644 --- a/examples/geetest_v3.js +++ b/examples/geetest_v3.js @@ -1,14 +1,39 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v3 with a challenge fetched from the target site and without a proxy. + * It creates Tasks.GeeTestProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Fetch the current challenge from the target site's GeeTest endpoint. + * STEP-03 - Create and submit the task, then wait for CaptchaClient.solve(). + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); +// STEP-02: Fetch the dynamic challenge immediately before creating the task. fetch('https://target-site.com/path/to/geetest/init') .then((response) => response.json()) - .then(({ challenge }) => client.solve(new Tasks.GeeTestProxyless({ - websiteURL: 'https://example.com/login', - gt: 'YOUR_GT_KEY', - challenge - }))) - .then((solution) => console.log(solution)) - .catch(console.error); + .then(({ challenge }) => { + // STEP-03: Submit a task that uses the fresh challenge returned by the target site. + return client.solve(new Tasks.GeeTestProxyless({ + websiteURL: 'https://example.com/login', + gt: 'YOUR_GT_KEY', + challenge + })); + }) + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v3_proxy.js b/examples/geetest_v3_proxy.js index 21b4bbc..3511ad7 100644 --- a/examples/geetest_v3_proxy.js +++ b/examples/geetest_v3_proxy.js @@ -1,17 +1,42 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v3 with a challenge fetched from the target site and a customer proxy. + * It creates Tasks.GeeTest from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Fetch the current challenge from the target site's GeeTest endpoint. + * STEP-03 - Create and submit the proxied task, then wait for CaptchaClient.solve(). + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); +// STEP-02: Fetch the dynamic challenge immediately before creating the task. fetch('https://target-site.com/path/to/geetest/init') .then((response) => response.json()) - .then(({ challenge }) => client.solve(new Tasks.GeeTest({ - websiteURL: 'https://example.com/login', - gt: 'YOUR_GT_KEY', - challenge, - proxyType: 'http', - proxyAddress: '1.2.3.4', - proxyPort: 8080 - }))) - .then((solution) => console.log(solution)) - .catch(console.error); + .then(({ challenge }) => { + // STEP-03: Submit a proxied task with the fresh challenge returned by the target site. + return client.solve(new Tasks.GeeTest({ + websiteURL: 'https://example.com/login', + gt: 'YOUR_GT_KEY', + challenge, + proxyType: 'http', + proxyAddress: '1.2.3.4', + proxyPort: 8080 + })); + }) + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v4.js b/examples/geetest_v4.js index 8c1084c..3e3123a 100644 --- a/examples/geetest_v4.js +++ b/examples/geetest_v4.js @@ -1,13 +1,38 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v4 without a proxy. + * It creates Tasks.GeeTestProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.GeeTestProxyless({ websiteURL: 'https://example.com/login', version: 4, initParameters: { captcha_id: 'YOUR_CAPTCHA_ID' } }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v4_proxy.js b/examples/geetest_v4_proxy.js index 1ff188e..66c4f31 100644 --- a/examples/geetest_v4_proxy.js +++ b/examples/geetest_v4_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v4 through a customer proxy. + * It creates Tasks.GeeTest from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.GeeTest({ websiteURL: 'https://example.com/login', version: 4, @@ -11,6 +28,14 @@ const task = new Tasks.GeeTest({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/image_to_text.js b/examples/image_to_text.js index ca2bd02..556b33b 100644 --- a/examples/image_to_text.js +++ b/examples/image_to_text.js @@ -2,7 +2,24 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Recognize a constrained text CAPTCHA from a local image. + * It creates Tasks.ImageToText from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.ImageToText({ body: fs.readFileSync(new URL('./assets/text-captcha.png', import.meta.url)).toString('base64'), numeric: 2, @@ -10,6 +27,14 @@ const task = new Tasks.ImageToText({ maxLength: 6 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.text)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/image_to_text_language_pool.js b/examples/image_to_text_language_pool.js index db08a44..10eb972 100644 --- a/examples/image_to_text_language_pool.js +++ b/examples/image_to_text_language_pool.js @@ -2,11 +2,36 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Recognize a text CAPTCHA with the English worker pool. + * It creates Tasks.ImageToText from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.ImageToText({ body: fs.readFileSync(new URL('./assets/text-captcha.png', import.meta.url)).toString('base64') }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task, 'en') - .then((solution) => console.log(solution.text)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/image_to_text_math.js b/examples/image_to_text_math.js index 8c7dcaa..f27bdec 100644 --- a/examples/image_to_text_math.js +++ b/examples/image_to_text_math.js @@ -2,7 +2,24 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a mathematical image-to-text CAPTCHA with image instructions. + * It creates Tasks.ImageToText from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.ImageToText({ body: fs.readFileSync(new URL('./assets/captcha-math.png', import.meta.url)).toString('base64'), math: true, @@ -10,6 +27,14 @@ const task = new Tasks.ImageToText({ imgInstructions: fs.readFileSync(new URL('./assets/captcha-math-instructions.png', import.meta.url)).toString('base64') }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.text)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2.js b/examples/recaptcha_v2.js index 2e7b01f..5566c28 100644 --- a/examples/recaptcha_v2.js +++ b/examples/recaptcha_v2.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 without a proxy. + * It creates Tasks.RecaptchaV2Proxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2_enterprise.js b/examples/recaptcha_v2_enterprise.js index dd7c6e3..7737f14 100644 --- a/examples/recaptcha_v2_enterprise.js +++ b/examples/recaptcha_v2_enterprise.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 Enterprise without a proxy. + * It creates Tasks.RecaptchaV2EnterpriseProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2EnterpriseProxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2_enterprise_proxy.js b/examples/recaptcha_v2_enterprise_proxy.js index 6817580..3add9b2 100644 --- a/examples/recaptcha_v2_enterprise_proxy.js +++ b/examples/recaptcha_v2_enterprise_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 Enterprise through a customer proxy. + * It creates Tasks.RecaptchaV2Enterprise from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2Enterprise({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -10,6 +27,14 @@ const task = new Tasks.RecaptchaV2Enterprise({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2_proxy.js b/examples/recaptcha_v2_proxy.js index 2dc1745..ab7c1c6 100644 --- a/examples/recaptcha_v2_proxy.js +++ b/examples/recaptcha_v2_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 through a customer proxy. + * It creates Tasks.RecaptchaV2 from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -12,6 +29,14 @@ const task = new Tasks.RecaptchaV2({ proxyPassword: 'password' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v3.js b/examples/recaptcha_v3.js index b3ffc63..c237b85 100644 --- a/examples/recaptcha_v3.js +++ b/examples/recaptcha_v3.js @@ -1,15 +1,27 @@ +import 'dotenv/config'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; + /** - * Promise-chain example: Solve reCAPTCHA v3 without a customer proxy. - * Set CAPTCHA_API_KEY and replace the page-specific values before running. + * Solve reCAPTCHA v3 without a proxy. + * It creates Tasks.RecaptchaV3Proxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. */ -import 'dotenv/config'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +// STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV3Proxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -17,6 +29,14 @@ const task = new Tasks.RecaptchaV3Proxyless({ pageAction: 'homepage' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. captchaSolver.solve(task) - .then((result) => console.log('result:', result)) - .catch((error) => console.error(error)); + .then((result) => { + // STEP-04: Print the solution returned for this CAPTCHA type. + console.log('Solution:', result); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/tencent.js b/examples/tencent.js index e827ff4..8ce1b0d 100644 --- a/examples/tencent.js +++ b/examples/tencent.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Tencent CAPTCHA without a proxy. + * It creates Tasks.TencentTaskProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.TencentTaskProxyless({ websiteURL: 'https://example.com/register', appId: 'YOUR_APP_ID' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/tencent_proxy.js b/examples/tencent_proxy.js index b92f239..8f6e721 100644 --- a/examples/tencent_proxy.js +++ b/examples/tencent_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Tencent CAPTCHA through a customer proxy. + * It creates Tasks.TencentTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.TencentTask({ websiteURL: 'https://example.com/register', appId: 'YOUR_APP_ID', @@ -10,6 +27,14 @@ const task = new Tasks.TencentTask({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/turnstile.js b/examples/turnstile.js index ad66730..484b8c6 100644 --- a/examples/turnstile.js +++ b/examples/turnstile.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Cloudflare Turnstile without a proxy. + * It creates Tasks.TurnstileProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.TurnstileProxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/turnstile_proxy.js b/examples/turnstile_proxy.js index 31fb852..f590312 100644 --- a/examples/turnstile_proxy.js +++ b/examples/turnstile_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Cloudflare Turnstile through a customer proxy. + * It creates Tasks.Turnstile from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.Turnstile({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -10,6 +27,14 @@ const task = new Tasks.Turnstile({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha.js b/examples/yandex_smartcaptcha.js index 3397175..84b509e 100644 --- a/examples/yandex_smartcaptcha.js +++ b/examples/yandex_smartcaptcha.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Yandex SmartCaptcha without a proxy. + * It creates Tasks.YandexSmartCaptchaTaskProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaTaskProxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha_image.js b/examples/yandex_smartcaptcha_image.js index 714063a..bc318c8 100644 --- a/examples/yandex_smartcaptcha_image.js +++ b/examples/yandex_smartcaptcha_image.js @@ -2,12 +2,37 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a Yandex SmartCaptcha image challenge from local assets. + * It creates Tasks.YandexSmartCaptchaImageTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaImageTask({ image: fs.readFileSync(new URL('./assets/yandex-smartcaptcha-image.png', import.meta.url)).toString('base64'), imgInstructions: fs.readFileSync(new URL('./assets/yandex-smartcaptcha-instructions.png', import.meta.url)).toString('base64') }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.coordinates)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.coordinates); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 41ef64d..46a32f9 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -2,10 +2,24 @@ import 'dotenv/config'; import fs from 'node:fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a Yandex SmartCaptcha Kaleidoscope puzzle from a local image. + * It creates Tasks.YandexSmartCaptchaKaleidoscopeTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + if (!process.env.CAPTCHA_API_KEY) { throw new Error('Set CAPTCHA_API_KEY in .env or in the current shell before running this example.'); } +// STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY }); @@ -13,13 +27,19 @@ const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) ).toString('base64'); +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaKaleidoscopeTask({ image, task: '[7,15,14,0,11,6,6,0,11,15,6,10,1,14,3,12,9,0,15,1,5,1,8,11,12,11,0,12,1,10,1,4,14,6,10,6,10,8,3,0,5,9,7,8,0,3,8,0,9,12,12,11,3,0,8,10]' }); +// STEP-03: Submit the task; solve() handles task creation and polling. captchaSolver.solve(task) .then((clicks) => { + // STEP-04: Print the number of arrow clicks required by the puzzle. console.log('Captcha solved. Slider arrow clicks:', clicks); }) - .catch(console.error); + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha_proxy.js b/examples/yandex_smartcaptcha_proxy.js index c3250d6..fc12f99 100644 --- a/examples/yandex_smartcaptcha_proxy.js +++ b/examples/yandex_smartcaptcha_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Yandex SmartCaptcha through a customer proxy. + * It creates Tasks.YandexSmartCaptchaTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaTask({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -10,6 +27,14 @@ const task = new Tasks.YandexSmartCaptchaTask({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); From bae5310ce1ad521c802bb57c7279207371ee24d8 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 17:09:30 +0300 Subject: [PATCH 04/31] docs: print Kaleidoscope result as JSON --- examples/yandex_smartcaptcha_kaleidoscope.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 46a32f9..4f5bcbd 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -12,7 +12,7 @@ import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; * STEP-01 - Configure the SDK client. * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. - * STEP-04 - Print the relevant solution value or report an error. + * STEP-04 - Print the solution as formatted JSON or report an error. */ if (!process.env.CAPTCHA_API_KEY) { @@ -21,7 +21,8 @@ if (!process.env.CAPTCHA_API_KEY) { // STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ - clientKey: process.env.CAPTCHA_API_KEY + clientKey: process.env.CAPTCHA_API_KEY, + debug: true }); const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) @@ -36,8 +37,8 @@ const task = new Tasks.YandexSmartCaptchaKaleidoscopeTask({ // STEP-03: Submit the task; solve() handles task creation and polling. captchaSolver.solve(task) .then((clicks) => { - // STEP-04: Print the number of arrow clicks required by the puzzle. - console.log('Captcha solved. Slider arrow clicks:', clicks); + // STEP-04: Print a structured response that can be copied or parsed as JSON. + console.log(JSON.stringify({ clicks }, null, 2)); }) .catch((error) => { // Report SDK or transport failures without hiding the rejected Promise. From 82b6145fb6330613f05c171853546b38d4ac8e3d Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 17:19:03 +0300 Subject: [PATCH 05/31] feat: log sanitized server exchanges --- README.md | 7 +++-- src/client.ts | 45 ++++++++++++++++++++++----- tests/unit/async/client.test.js | 55 ++++++++++++++++++++++++++++++--- 3 files changed, 92 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 8316bcd..d635bd5 100644 --- a/README.md +++ b/README.md @@ -681,9 +681,10 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print sanitized request and polling lifecycle events. Debug output -includes endpoint names, HTTP status codes, task IDs, and task statuses; it never -includes the API key, task payload, or solution. +Enable `debug` to print request, response, and polling lifecycle events. Debug output +includes the HTTP method and URL, request body, response status and body, task IDs, +and task statuses. Credential fields are replaced with `[REDACTED]`; long strings +such as base64 images and solution tokens are truncated to keep the output readable. ```javascript // Create a client with detailed, sanitized lifecycle logging enabled. diff --git a/src/client.ts b/src/client.ts index b3e7f6d..3c6544e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -2,6 +2,9 @@ import { ApiError, NetworkError, TimeoutError, ValidationError } from './excepti import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; +const MAX_DEBUG_STRING_LENGTH = 200; +const REDACTED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyLogin|proxyPassword)$/i; + /** Options accepted by the {@link CaptchaClient} constructor. */ export interface CaptchaClientOptions { /** Your Captcha Solver API key. Required. */ @@ -26,7 +29,8 @@ export interface CaptchaClientOptions { pollingInterval?: number; /** * Print request and polling lifecycle events to `console.debug`. - * API keys, task payloads, and solutions are never included. + * Request and response bodies are included after credentials are redacted + * and long strings such as base64 images and solution tokens are truncated. * @defaultValue `false` */ debug?: boolean; @@ -92,13 +96,29 @@ export class CaptchaClient { } /** - * Write a sanitized lifecycle event when debug mode is enabled. - * Callers pass only operational metadata here so credentials, CAPTCHA image - * data, task payloads, and solutions cannot leak into console output. + * Copy a value for debug output while keeping logs readable and safe to share. + * Credential fields are removed completely; long strings retain their edges + * and original length so base64 images and tokens can still be identified. */ + private _sanitizeForDebug(value: unknown, fieldName?: string): unknown { + if (fieldName && REDACTED_DEBUG_FIELDS.test(fieldName)) return '[REDACTED]'; + if (typeof value === 'string' && value.length > MAX_DEBUG_STRING_LENGTH) { + const edgeLength = Math.floor(MAX_DEBUG_STRING_LENGTH / 2); + return `${value.slice(0, edgeLength)}...[truncated; original length: ${value.length}]...${value.slice(-edgeLength)}`; + } + if (Array.isArray(value)) return value.map((item) => this._sanitizeForDebug(item)); + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [key, this._sanitizeForDebug(item, key)]) + ); + } + return value; + } + + /** Write one debug event after sanitizing every supplied field. */ private _debug(message: string, details?: Record): void { if (!this.debug) return; - if (details) console.debug(`[CaptchaClient] ${message}`, details); + if (details) console.debug(`[CaptchaClient] ${message}`, this._sanitizeForDebug(details)); else console.debug(`[CaptchaClient] ${message}`); } @@ -118,11 +138,22 @@ export class CaptchaClient { protected async _request(endpoint: string, payload: Record): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); const startedAt = Date.now(); + const url = `${this.baseUrl}${endpoint}`; + const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; this._debug('request started', { endpoint }); + this._debug('server request', { method: 'POST', url, headers, body: payload }); try { - const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }, body: JSON.stringify(payload), signal: controller.signal }); + const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); + let data: TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; + try { + data = await response.json() as typeof data; + } catch (parseError) { + this._debug('server response', { endpoint, status: response.status, statusText: response.statusText, body: '[unavailable: invalid JSON]' }); + if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); + throw parseError; + } + this._debug('server response', { endpoint, status: response.status, statusText: response.statusText, body: data }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); - const data = await response.json() as TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); this._debug('request completed', { endpoint, status: response.status, durationMs: Date.now() - startedAt }); return data; diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 6e09dc2..d434572 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -51,6 +51,22 @@ describe('CaptchaClient (async)', () => { await client.getBalance(); expect(debug).toHaveBeenCalledWith('[CaptchaClient] request started', { endpoint: '/getBalance' }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] server request', { + method: 'POST', + url: 'https://api.captcha-solver.com/getBalance', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + 'X-SDK': 'javascript-sdk/1.1.0' + }, + body: { clientKey: '[REDACTED]' } + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] server response', { + endpoint: '/getBalance', + status: 200, + statusText: undefined, + body: { errorId: 0, balance: '1.00' } + }); expect(debug).toHaveBeenCalledWith('[CaptchaClient] client initialized', { baseUrl: 'https://api.captcha-solver.com', timeout: 120000, @@ -77,7 +93,7 @@ describe('CaptchaClient (async)', () => { .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, - json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: 'secret_solution' } }) + json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: `start-${'x'.repeat(300)}-end` } }) })); const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', @@ -101,8 +117,11 @@ describe('CaptchaClient (async)', () => { pollAttempts: 1, elapsedMs: expect.any(Number) }); - expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_solution'); - expect(JSON.stringify(debug.mock.calls)).not.toContain('website_key'); + const logged = JSON.stringify(debug.mock.calls); + expect(logged).toContain('website_key'); + expect(logged).toContain('original length: 310'); + expect(logged).not.toContain(`start-${'x'.repeat(300)}-end`); + expect(logged).not.toContain('secret_key'); debug.mockRestore(); }); @@ -120,6 +139,32 @@ describe('CaptchaClient (async)', () => { debug.mockRestore(); }); + test('debug mode logs the original API error response before throwing', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + const errorBody = { + errorId: 1, + errorCode: 'ERROR_KEY_DOES_NOT_EXIST', + errorDescription: 'Account not found' + }; + global.fetch = jest.fn(() => Promise.resolve({ + ok: true, + status: 200, + statusText: 'OK', + json: () => Promise.resolve(errorBody) + })); + + await expect(client.getBalance()).rejects.toThrow(ApiError); + + expect(debug).toHaveBeenCalledWith('[CaptchaClient] server response', { + endpoint: '/getBalance', + status: 200, + statusText: 'OK', + body: errorBody + }); + debug.mockRestore(); + }); + test('aborts an HTTP request after timeout', async () => { client.timeout = 10; global.fetch = jest.fn((url, options) => new Promise((resolve, reject) => { @@ -387,7 +432,7 @@ describe('CaptchaClient error edge cases (async)', () => { }); }); - test('throws NetworkError on a non-2xx HTTP status without reading the body', async () => { + test('throws NetworkError on a non-2xx HTTP status after reading the error body', async () => { const json = jest.fn(); global.fetch = jest.fn(() => Promise.resolve({ ok: false, @@ -399,7 +444,7 @@ describe('CaptchaClient error edge cases (async)', () => { const error = await client.createTask(task()).catch((e) => e); expect(error).toBeInstanceOf(NetworkError); expect(error.message).toBe('HTTP error: 502 Bad Gateway'); - expect(json).not.toHaveBeenCalled(); + expect(json).toHaveBeenCalledTimes(1); }); test('throws NetworkError when the response body is not valid JSON', async () => { From a0f6c383a4828f9a7203d518bf2fe8e2c9dba0e9 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 17:31:25 +0300 Subject: [PATCH 06/31] test: enforce debug response ordering --- src/client.ts | 1 + tests/unit/async/client.test.js | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/client.ts b/src/client.ts index 3c6544e..6dfcedd 100644 --- a/src/client.ts +++ b/src/client.ts @@ -152,6 +152,7 @@ export class CaptchaClient { if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); throw parseError; } + // Log the server payload first; lifecycle messages below explain how the SDK interpreted it. this._debug('server response', { endpoint, status: response.status, statusText: response.statusText, body: data }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index d434572..e2d7355 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -77,6 +77,9 @@ describe('CaptchaClient (async)', () => { status: 200, durationMs: expect.any(Number) }); + const responseLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] server response'); + const completedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request completed'); + expect(responseLogIndex).toBeLessThan(completedLogIndex); expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); debug.mockRestore(); }); @@ -122,6 +125,15 @@ describe('CaptchaClient (async)', () => { expect(logged).toContain('original length: 310'); expect(logged).not.toContain(`start-${'x'.repeat(300)}-end`); expect(logged).not.toContain('secret_key'); + const resultResponseLogIndex = debug.mock.calls.findIndex(([message, details]) => + message === '[CaptchaClient] server response' && details.endpoint === '/getTaskResult' + ); + const resultCompletedLogIndex = debug.mock.calls.findIndex(([message, details]) => + message === '[CaptchaClient] request completed' && details.endpoint === '/getTaskResult' + ); + const statusLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] task status received'); + expect(resultResponseLogIndex).toBeLessThan(resultCompletedLogIndex); + expect(resultCompletedLogIndex).toBeLessThan(statusLogIndex); debug.mockRestore(); }); @@ -162,6 +174,9 @@ describe('CaptchaClient (async)', () => { statusText: 'OK', body: errorBody }); + const responseLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] server response'); + const failedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request failed'); + expect(responseLogIndex).toBeLessThan(failedLogIndex); debug.mockRestore(); }); From aa2a2701fe45fef1769d396452212a160ff02a28 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 17:33:07 +0300 Subject: [PATCH 07/31] feat: add final solve debug summary --- README.md | 6 +++-- src/client.ts | 45 ++++++++++++++++++++++----------- tests/unit/async/client.test.js | 36 ++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index d635bd5..6c3479e 100644 --- a/README.md +++ b/README.md @@ -683,8 +683,10 @@ const captchaSolver = new CaptchaClient({ Enable `debug` to print request, response, and polling lifecycle events. Debug output includes the HTTP method and URL, request body, response status and body, task IDs, -and task statuses. Credential fields are replaced with `[REDACTED]`; long strings -such as base64 images and solution tokens are truncated to keep the output readable. +and task statuses. At the end of `solve()`, a summary reports whether the CAPTCHA was +solved, its task ID, total elapsed time, and the number of result requests. Credential +fields are replaced with `[REDACTED]`; long strings such as base64 images and solution +tokens are truncated to keep the output readable. ```javascript // Create a client with detailed, sanitized lifecycle logging enabled. diff --git a/src/client.ts b/src/client.ts index 6dfcedd..ae55dea 100644 --- a/src/client.ts +++ b/src/client.ts @@ -252,23 +252,38 @@ export class CaptchaClient { */ async solve>(task: T, languagePool: string | null = null): Promise> { const taskType = task.constructor.name; + const startedAt = Date.now(); + let taskId: number | null = null; + let resultRequestCount = 0; this._debug('solve started', { taskType }); - const taskId = await this.createTask(task, languagePool); const startedAt = Date.now(); - let pollAttempt = 0; - while (true) { - const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - const delayMs = Math.min(this.pollingInterval, remaining); - pollAttempt += 1; - this._debug('waiting before poll', { taskId, pollAttempt, delayMs }); - await new Promise(resolve => setTimeout(resolve, delayMs)); - if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - const result = await this.getTaskResult(taskId); - const elapsedMs = Date.now() - startedAt; - this._debug('task status received', { taskId, pollAttempt, status: result.status, elapsedMs }); - if (result.status === 'ready') { - this._debug('task solved', { taskId, pollAttempts: pollAttempt, elapsedMs }); - return (result.solution ?? {}) as SolutionOf; + try { + taskId = await this.createTask(task, languagePool); + let pollAttempt = 0; + while (true) { + const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + const delayMs = Math.min(this.pollingInterval, remaining); + pollAttempt += 1; + this._debug('waiting before poll', { taskId, pollAttempt, delayMs }); + await new Promise(resolve => setTimeout(resolve, delayMs)); + if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + resultRequestCount += 1; + const result = await this.getTaskResult(taskId); + const elapsedMs = Date.now() - startedAt; + this._debug('task status received', { taskId, pollAttempt, status: result.status, elapsedMs }); + if (result.status === 'ready') { + this._debug('task solved', { taskId, pollAttempts: pollAttempt, elapsedMs }); + this._debug('solve summary', { status: 'solved', captchaId: taskId, elapsedMs, resultRequestCount }); + return (result.solution ?? {}) as SolutionOf; + } } + } catch (error) { + this._debug('solve summary', { + status: 'not solved', + captchaId: taskId, + elapsedMs: Date.now() - startedAt, + resultRequestCount + }); + throw error; } } } diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index e2d7355..b9d9805 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -120,6 +120,12 @@ describe('CaptchaClient (async)', () => { pollAttempts: 1, elapsedMs: expect.any(Number) }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { + status: 'solved', + captchaId: 12345, + elapsedMs: expect.any(Number), + resultRequestCount: 1 + }); const logged = JSON.stringify(debug.mock.calls); expect(logged).toContain('website_key'); expect(logged).toContain('original length: 310'); @@ -151,6 +157,36 @@ describe('CaptchaClient (async)', () => { debug.mockRestore(); }); + test('debug mode logs a not-solved summary after a result request fails', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) + })) + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' }) + })); + const task = new Tasks.RecaptchaV2Proxyless({ + websiteURL: 'https://example.com', + websiteKey: 'website_key' + }); + + await expect(client.solve(task)).rejects.toThrow(ApiError); + + expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { + status: 'not solved', + captchaId: 12345, + elapsedMs: expect.any(Number), + resultRequestCount: 1 + }); + debug.mockRestore(); + }); + test('debug mode logs the original API error response before throwing', async () => { const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); From f6f7f88d5f6709e15bf8e8a815c9310f5a9d1bf3 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 17:37:29 +0300 Subject: [PATCH 08/31] feat: show readable solve duration --- README.md | 3 ++- src/client.ts | 12 ++++++++++-- tests/unit/async/client.test.js | 2 ++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6c3479e..7639ffc 100644 --- a/README.md +++ b/README.md @@ -684,7 +684,8 @@ const captchaSolver = new CaptchaClient({ Enable `debug` to print request, response, and polling lifecycle events. Debug output includes the HTTP method and URL, request body, response status and body, task IDs, and task statuses. At the end of `solve()`, a summary reports whether the CAPTCHA was -solved, its task ID, total elapsed time, and the number of result requests. Credential +solved, its task ID, total elapsed time in readable seconds and exact milliseconds, +and the number of `/getTaskResult` requests. Credential fields are replaced with `[REDACTED]`; long strings such as base64 images and solution tokens are truncated to keep the output readable. diff --git a/src/client.ts b/src/client.ts index ae55dea..9d4eb63 100644 --- a/src/client.ts +++ b/src/client.ts @@ -272,15 +272,23 @@ export class CaptchaClient { this._debug('task status received', { taskId, pollAttempt, status: result.status, elapsedMs }); if (result.status === 'ready') { this._debug('task solved', { taskId, pollAttempts: pollAttempt, elapsedMs }); - this._debug('solve summary', { status: 'solved', captchaId: taskId, elapsedMs, resultRequestCount }); + this._debug('solve summary', { + status: 'solved', + captchaId: taskId, + elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, + elapsedMs, + resultRequestCount + }); return (result.solution ?? {}) as SolutionOf; } } } catch (error) { + const elapsedMs = Date.now() - startedAt; this._debug('solve summary', { status: 'not solved', captchaId: taskId, - elapsedMs: Date.now() - startedAt, + elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, + elapsedMs, resultRequestCount }); throw error; diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index b9d9805..ecf24eb 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -123,6 +123,7 @@ describe('CaptchaClient (async)', () => { expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { status: 'solved', captchaId: 12345, + elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), elapsedMs: expect.any(Number), resultRequestCount: 1 }); @@ -181,6 +182,7 @@ describe('CaptchaClient (async)', () => { expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { status: 'not solved', captchaId: 12345, + elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), elapsedMs: expect.any(Number), resultRequestCount: 1 }); From 533ff4b4fabe70bc4dc83f938c0b7d243164823f Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 17:39:38 +0300 Subject: [PATCH 09/31] feat: label server exchanges as JSON blocks --- README.md | 3 +++ src/client.ts | 13 ++++++++--- tests/unit/async/client.test.js | 39 ++++++++++++--------------------- 3 files changed, 27 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 7639ffc..b5bd24b 100644 --- a/README.md +++ b/README.md @@ -689,6 +689,9 @@ and the number of `/getTaskResult` requests. Credential fields are replaced with `[REDACTED]`; long strings such as base64 images and solution tokens are truncated to keep the output readable. +Server exchanges are printed as single labelled JSON blocks, so the response body +always remains visually attached to `[CaptchaClient] server response` in the console. + ```javascript // Create a client with detailed, sanitized lifecycle logging enabled. const captchaSolver = new CaptchaClient({ diff --git a/src/client.ts b/src/client.ts index 9d4eb63..9dce0aa 100644 --- a/src/client.ts +++ b/src/client.ts @@ -122,6 +122,13 @@ export class CaptchaClient { else console.debug(`[CaptchaClient] ${message}`); } + /** Print an HTTP exchange as one labelled JSON block instead of an ambiguous console object. */ + private _debugServerExchange(message: 'server request' | 'server response', details: Record): void { + if (!this.debug) return; + const json = JSON.stringify(this._sanitizeForDebug(details), null, 2); + console.debug(`[CaptchaClient] ${message}:\n${json}`); + } + /** * Send one JSON `POST` request to the API and validate the response envelope. * @@ -141,19 +148,19 @@ export class CaptchaClient { const url = `${this.baseUrl}${endpoint}`; const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; this._debug('request started', { endpoint }); - this._debug('server request', { method: 'POST', url, headers, body: payload }); + this._debugServerExchange('server request', { method: 'POST', url, headers, body: payload }); try { const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); let data: TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; try { data = await response.json() as typeof data; } catch (parseError) { - this._debug('server response', { endpoint, status: response.status, statusText: response.statusText, body: '[unavailable: invalid JSON]' }); + this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: '[unavailable: invalid JSON]' }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); throw parseError; } // Log the server payload first; lifecycle messages below explain how the SDK interpreted it. - this._debug('server response', { endpoint, status: response.status, statusText: response.statusText, body: data }); + this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: data }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); this._debug('request completed', { endpoint, status: response.status, durationMs: Date.now() - startedAt }); diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index ecf24eb..c662039 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -51,22 +51,13 @@ describe('CaptchaClient (async)', () => { await client.getBalance(); expect(debug).toHaveBeenCalledWith('[CaptchaClient] request started', { endpoint: '/getBalance' }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] server request', { - method: 'POST', - url: 'https://api.captcha-solver.com/getBalance', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json', - 'X-SDK': 'javascript-sdk/1.1.0' - }, - body: { clientKey: '[REDACTED]' } - }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] server response', { - endpoint: '/getBalance', - status: 200, - statusText: undefined, - body: { errorId: 0, balance: '1.00' } - }); + const requestLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server request:'))?.[0]; + expect(requestLog).toContain('"url": "https://api.captcha-solver.com/getBalance"'); + expect(requestLog).toContain('"clientKey": "[REDACTED]"'); + const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; + expect(responseLog).toContain('"endpoint": "/getBalance"'); + expect(responseLog).toContain('"status": 200'); + expect(responseLog).toContain('"balance": "1.00"'); expect(debug).toHaveBeenCalledWith('[CaptchaClient] client initialized', { baseUrl: 'https://api.captcha-solver.com', timeout: 120000, @@ -77,7 +68,7 @@ describe('CaptchaClient (async)', () => { status: 200, durationMs: expect.any(Number) }); - const responseLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] server response'); + const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); const completedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request completed'); expect(responseLogIndex).toBeLessThan(completedLogIndex); expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); @@ -133,7 +124,7 @@ describe('CaptchaClient (async)', () => { expect(logged).not.toContain(`start-${'x'.repeat(300)}-end`); expect(logged).not.toContain('secret_key'); const resultResponseLogIndex = debug.mock.calls.findIndex(([message, details]) => - message === '[CaptchaClient] server response' && details.endpoint === '/getTaskResult' + message.startsWith('[CaptchaClient] server response:') && message.includes('"endpoint": "/getTaskResult"') ); const resultCompletedLogIndex = debug.mock.calls.findIndex(([message, details]) => message === '[CaptchaClient] request completed' && details.endpoint === '/getTaskResult' @@ -206,13 +197,11 @@ describe('CaptchaClient (async)', () => { await expect(client.getBalance()).rejects.toThrow(ApiError); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] server response', { - endpoint: '/getBalance', - status: 200, - statusText: 'OK', - body: errorBody - }); - const responseLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] server response'); + const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; + expect(responseLog).toContain('"endpoint": "/getBalance"'); + expect(responseLog).toContain('"errorCode": "ERROR_KEY_DOES_NOT_EXIST"'); + expect(responseLog).toContain('"errorDescription": "Account not found"'); + const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); const failedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request failed'); expect(responseLogIndex).toBeLessThan(failedLogIndex); debug.mockRestore(); From 9901b817d78724e3b58da2fe288ec4cc74d6b200 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 17:55:41 +0300 Subject: [PATCH 10/31] feat: harden structured debug logging --- CHANGELOG.md | 13 + README.md | 26 +- examples/yandex_smartcaptcha_kaleidoscope.js | 2 +- src/client.ts | 208 ++++++++++----- src/index.ts | 2 +- tests/unit/async/client.test.js | 254 +++++++++---------- 6 files changed, 304 insertions(+), 201 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a7bf6d..96a4601 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ All notable changes are documented here. +## Unreleased + +### Added + +- add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries +- add a debug logger callback for forwarding events to application loggers or files + +### Fixed + +- enforce the overall solve timeout across task creation, polling delays, and result requests +- preserve non-JSON server response bodies in debug events +- redact credentials, tokens, URL secrets, and binary CAPTCHA data from debug output + ## [1.1.0] - 2026-11-03 ### Added diff --git a/README.md b/README.md index b5bd24b..ac47c9b 100644 --- a/README.md +++ b/README.md @@ -681,13 +681,12 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print request, response, and polling lifecycle events. Debug output -includes the HTTP method and URL, request body, response status and body, task IDs, -and task statuses. At the end of `solve()`, a summary reports whether the CAPTCHA was -solved, its task ID, total elapsed time in readable seconds and exact milliseconds, -and the number of `/getTaskResult` requests. Credential -fields are replaced with `[REDACTED]`; long strings such as base64 images and solution -tokens are truncated to keep the output readable. +Enable `debug` to print structured request, response, and polling lifecycle events. +Every event includes an ISO timestamp, severity level, event name, and correlation IDs. +Debug output includes the HTTP method and URL, sanitized request body, response status +and body, task IDs, and task statuses. At the end of `solve()`, a summary reports the +outcome or failure reason, total elapsed time, and request counts. Credential and token +fields are redacted; binary data and other long strings are omitted or truncated. Server exchanges are printed as single labelled JSON blocks, so the response body always remains visually attached to `[CaptchaClient] server response` in the console. @@ -700,6 +699,19 @@ const captchaSolver = new CaptchaClient({ }); ``` +Pass `logger` to receive the same structured events without writing to the console. +The callback can forward events to a file or an application logger; the SDK never +creates log files on its own: + +```javascript +const events = []; +const captchaSolver = new CaptchaClient({ + clientKey: 'your_api_key', + debug: true, + logger: (event) => events.push(event) +}); +``` + ### Worker language pool Pass `languagePool` as the second argument to `solve()` (or `createTask()`) to pick a diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 4f5bcbd..699f3c2 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -22,7 +22,7 @@ if (!process.env.CAPTCHA_API_KEY) { // STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY, - debug: true + debug: process.env.CAPTCHA_DEBUG === '1' }); const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) diff --git a/src/client.ts b/src/client.ts index 9dce0aa..d558e2e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -3,7 +3,27 @@ import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; const MAX_DEBUG_STRING_LENGTH = 200; -const REDACTED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyLogin|proxyPassword)$/i; +let operationSequence = 0; + +interface DebugContext { + solveId?: string; + requestId?: string; + taskId?: number; +} + +/** Severity assigned to a structured debug event. */ +export type DebugLevel = 'debug' | 'info' | 'error'; + +/** One structured event emitted while debug mode is enabled. */ +export interface DebugEvent extends DebugContext { + timestamp: string; + level: DebugLevel; + event: string; + [key: string]: unknown; +} + +/** Receives structured debug events. Use this to integrate a logger or file stream. */ +export type DebugLogger = (event: DebugEvent) => void; /** Options accepted by the {@link CaptchaClient} constructor. */ export interface CaptchaClientOptions { @@ -34,6 +54,11 @@ export interface CaptchaClientOptions { * @defaultValue `false` */ debug?: boolean; + /** + * Optional structured event receiver used instead of the default console renderer. + * Only called when {@link debug} is `true`. + */ + logger?: DebugLogger; } /** Raw response of `/getTaskResult` (and, structurally, of every other API endpoint). */ @@ -84,26 +109,45 @@ export class CaptchaClient { pollingInterval: number; /** Whether lifecycle debug logging is enabled. */ debug: boolean; + /** Structured debug event receiver. */ + logger: DebugLogger; /** * @param options - Client options; only `clientKey` is required. * @throws {ValidationError} If `clientKey` is empty. */ - constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false }: CaptchaClientOptions = {} as CaptchaClientOptions) { + constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false, logger }: CaptchaClientOptions = {} as CaptchaClientOptions) { if (!clientKey) throw new ValidationError('clientKey is required'); this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; this.debug = debug; - this._debug('client initialized', { baseUrl, timeout, pollingInterval }); + this.logger = logger ?? ((event) => this._writeDebugToConsole(event)); + this._emitDebug('client.initialized', { baseUrl, timeout, pollingInterval }, 'info'); } /** * Copy a value for debug output while keeping logs readable and safe to share. - * Credential fields are removed completely; long strings retain their edges - * and original length so base64 images and tokens can still be identified. + * Credentials and tokens are redacted, binary data is omitted, and other + * long strings retain short edges plus their original length. */ private _sanitizeForDebug(value: unknown, fieldName?: string): unknown { - if (fieldName && REDACTED_DEBUG_FIELDS.test(fieldName)) return '[REDACTED]'; + const normalizedField = fieldName?.replace(/[^a-z0-9]/gi, '').toLowerCase(); + if (normalizedField && /(authorization|clientkey|apikey|cookie|password|proxylogin|secret)/.test(normalizedField)) return '[REDACTED]'; + if (normalizedField && /(accesstoken|refreshtoken|^token$|grecaptcharesponse)/.test(normalizedField)) { + return typeof value === 'string' ? `[REDACTED token; original length: ${value.length}]` : '[REDACTED token]'; + } + if (normalizedField && /(body|image|imginstructions|pagedata)/.test(normalizedField) && typeof value === 'string' && value.length > MAX_DEBUG_STRING_LENGTH) { + return `[OMITTED binary data; original length: ${value.length}]`; + } + if (normalizedField?.endsWith('url') && typeof value === 'string') { + try { + const url = new URL(value); + for (const key of url.searchParams.keys()) { + if (/(key|token|secret|password|authorization)/i.test(key)) url.searchParams.set(key, '[REDACTED]'); + } + return url.toString(); + } catch { /* Keep non-standard URL placeholders unchanged. */ } + } if (typeof value === 'string' && value.length > MAX_DEBUG_STRING_LENGTH) { - const edgeLength = Math.floor(MAX_DEBUG_STRING_LENGTH / 2); + const edgeLength = 32; return `${value.slice(0, edgeLength)}...[truncated; original length: ${value.length}]...${value.slice(-edgeLength)}`; } if (Array.isArray(value)) return value.map((item) => this._sanitizeForDebug(item)); @@ -115,18 +159,38 @@ export class CaptchaClient { return value; } - /** Write one debug event after sanitizing every supplied field. */ - private _debug(message: string, details?: Record): void { - if (!this.debug) return; - if (details) console.debug(`[CaptchaClient] ${message}`, this._sanitizeForDebug(details)); - else console.debug(`[CaptchaClient] ${message}`); + /** Render one structured event for users who did not supply a logger callback. */ + private _writeDebugToConsole(event: DebugEvent): void { + const output = `[CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}`; + if (event.level === 'error') console.error(output); + else if (event.level === 'info') console.info(output); + else console.debug(output); } - /** Print an HTTP exchange as one labelled JSON block instead of an ambiguous console object. */ - private _debugServerExchange(message: 'server request' | 'server response', details: Record): void { + /** Emit one sanitized event. Logger failures never change the SDK operation result. */ + private _emitDebug(event: string, details: Record = {}, level: DebugLevel = 'debug', context: DebugContext = {}): void { if (!this.debug) return; - const json = JSON.stringify(this._sanitizeForDebug(details), null, 2); - console.debug(`[CaptchaClient] ${message}:\n${json}`); + const record = this._sanitizeForDebug({ timestamp: new Date().toISOString(), level, event, ...context, ...details }) as DebugEvent; + try { this.logger(record); } catch { /* Diagnostics must not break API calls. */ } + } + + private _newOperationId(prefix: 'solve' | 'request'): string { + operationSequence += 1; + return `${prefix}-${Date.now().toString(36)}-${operationSequence.toString(36)}`; + } + + private _errorDetails(error: unknown): Record { + if (!(error instanceof Error)) return { errorName: 'UnknownError', errorMessage: String(error) }; + const details: Record = { errorName: error.name, errorMessage: error.message }; + if (error instanceof ApiError) { details.errorCode = error.errorCode; details.errorDescription = error.errorDescription; } + return details; + } + + private _failureReason(error: unknown): string { + if (error instanceof TimeoutError) return 'timeout'; + if (error instanceof ApiError) return 'api_error'; + if (error instanceof NetworkError) return 'network_error'; + return 'unknown_error'; } /** @@ -142,34 +206,46 @@ export class CaptchaClient { * @throws {NetworkError} On a non-2xx HTTP status or any transport failure. * @internal */ - protected async _request(endpoint: string, payload: Record): Promise { - const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); - const startedAt = Date.now(); + protected async _request(endpoint: string, payload: Record, context: DebugContext = {}, requestTimeout = this.timeout): Promise { + const effectiveTimeout = Math.max(1, Math.ceil(requestTimeout)); + const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), effectiveTimeout); + const startedAt = performance.now(); const url = `${this.baseUrl}${endpoint}`; const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; - this._debug('request started', { endpoint }); - this._debugServerExchange('server request', { method: 'POST', url, headers, body: payload }); + const requestContext = { ...context, requestId: this._newOperationId('request') }; + this._emitDebug('request.started', { endpoint, timeoutMs: effectiveTimeout }, 'debug', requestContext); + this._emitDebug('server.request', { method: 'POST', url, headers, body: payload }, 'debug', requestContext); try { const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); let data: TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; - try { + if (typeof response.text === 'function') { + const rawBody = await response.text(); + try { + data = JSON.parse(rawBody) as typeof data; + } catch (parseError) { + this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: rawBody }, 'error', requestContext); + if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`, parseError); + throw new NetworkError(`Invalid JSON response from ${endpoint}`, parseError); + } + } else { + // The fallback keeps custom fetch implementations and lightweight test doubles compatible. data = await response.json() as typeof data; - } catch (parseError) { - this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: '[unavailable: invalid JSON]' }); - if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); - throw parseError; } - // Log the server payload first; lifecycle messages below explain how the SDK interpreted it. - this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: data }); + const responseLevel: DebugLevel = !response.ok || !data || data.errorId !== 0 ? 'error' : 'debug'; + this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: data }, responseLevel, requestContext); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); + if (!data || typeof data !== 'object') throw new NetworkError(`Invalid JSON response from ${endpoint}`); if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); - this._debug('request completed', { endpoint, status: response.status, durationMs: Date.now() - startedAt }); + this._emitDebug('request.completed', { endpoint, status: response.status, durationMs: Math.round(performance.now() - startedAt) }, 'debug', requestContext); return data; } catch (error) { - this._debug('request failed', { endpoint, error: error instanceof Error ? error.name : 'UnknownError', durationMs: Date.now() - startedAt }); - if (error instanceof ApiError || error instanceof NetworkError) throw error; - if (error && typeof error === 'object' && 'name' in error && error.name === 'AbortError') throw new TimeoutError(`Request timed out after ${this.timeout}ms`); - throw new NetworkError(error instanceof Error ? error.message : String(error), error); + const normalizedError = error && typeof error === 'object' && 'name' in error && error.name === 'AbortError' + ? new TimeoutError(`Request timed out after ${effectiveTimeout}ms`) + : error instanceof ApiError || error instanceof NetworkError + ? error + : new NetworkError(error instanceof Error ? error.message : String(error), error); + this._emitDebug('request.failed', { endpoint, durationMs: Math.round(performance.now() - startedAt), ...this._errorDetails(normalizedError) }, 'error', requestContext); + throw normalizedError; } finally { clearTimeout(timer); } } @@ -193,12 +269,16 @@ export class CaptchaClient { * ``` */ async createTask(task: BaseTask, languagePool: string | null = null): Promise { + return this._createTask(task, languagePool, { solveId: this._newOperationId('solve') }, this.timeout); + } + + private async _createTask(task: BaseTask, languagePool: string | null, context: DebugContext, requestTimeout: number): Promise { const taskPayload = task.toDict(); const taskType = typeof taskPayload.type === 'string' ? taskPayload.type : task.constructor.name; - this._debug('task submission started', { taskType, languagePool }); + this._emitDebug('task.submission.started', { taskType, languagePool }, 'debug', context); const payload: Record = { clientKey: this.clientKey, task: taskPayload }; if (languagePool !== null) payload.languagePool = languagePool; - const taskId = (await this._request('/createTask', payload)).taskId as number; - this._debug('task created', { taskId, taskType }); + const taskId = (await this._request('/createTask', payload, context, requestTimeout)).taskId as number; + this._emitDebug('task.created', { taskType }, 'info', { ...context, taskId }); return taskId; } @@ -220,7 +300,7 @@ export class CaptchaClient { * .catch(console.error); * ``` */ - getTaskResult(taskId: number): Promise { return this._request('/getTaskResult', { clientKey: this.clientKey, taskId }); } + getTaskResult(taskId: number): Promise { return this._request('/getTaskResult', { clientKey: this.clientKey, taskId }, { taskId }); } /** * Get the account balance. @@ -258,46 +338,58 @@ export class CaptchaClient { * ``` */ async solve>(task: T, languagePool: string | null = null): Promise> { - const taskType = task.constructor.name; - const startedAt = Date.now(); + const startedAt = performance.now(); + const solveId = this._newOperationId('solve'); let taskId: number | null = null; let resultRequestCount = 0; - this._debug('solve started', { taskType }); + let totalRequestCount = 0; + this._emitDebug('solve.started', { taskClass: task.constructor.name, timeoutMs: this.timeout }, 'info', { solveId }); try { - taskId = await this.createTask(task, languagePool); + // Validate and serialize before counting the createTask HTTP attempt. + task.toDict(); + const remainingForCreate = this.timeout - (performance.now() - startedAt); + if (remainingForCreate <= 0) throw new TimeoutError(`Task creation timed out after ${this.timeout}ms`); + totalRequestCount += 1; + taskId = await this._createTask(task, languagePool, { solveId }, remainingForCreate); let pollAttempt = 0; while (true) { - const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + const remaining = this.timeout - (performance.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); const delayMs = Math.min(this.pollingInterval, remaining); pollAttempt += 1; - this._debug('waiting before poll', { taskId, pollAttempt, delayMs }); + this._emitDebug('poll.waiting', { pollAttempt, delayMs }, 'debug', { solveId, taskId }); await new Promise(resolve => setTimeout(resolve, delayMs)); - if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + const remainingForResult = this.timeout - (performance.now() - startedAt); + if (remainingForResult <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); resultRequestCount += 1; - const result = await this.getTaskResult(taskId); - const elapsedMs = Date.now() - startedAt; - this._debug('task status received', { taskId, pollAttempt, status: result.status, elapsedMs }); + totalRequestCount += 1; + const result = await this._request('/getTaskResult', { clientKey: this.clientKey, taskId }, { solveId, taskId }, remainingForResult); + const elapsedMs = Math.round(performance.now() - startedAt); + this._emitDebug('task.status.received', { pollAttempt, status: result.status, elapsedMs }, 'debug', { solveId, taskId }); if (result.status === 'ready') { - this._debug('task solved', { taskId, pollAttempts: pollAttempt, elapsedMs }); - this._debug('solve summary', { + this._emitDebug('task.solved', { pollAttempts: pollAttempt, elapsedMs }, 'info', { solveId, taskId }); + this._emitDebug('solve.summary', { status: 'solved', - captchaId: taskId, elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, elapsedMs, - resultRequestCount - }); + createTaskRequestCount: 1, + resultRequestCount, + totalRequestCount + }, 'info', { solveId, taskId }); return (result.solution ?? {}) as SolutionOf; } } } catch (error) { - const elapsedMs = Date.now() - startedAt; - this._debug('solve summary', { - status: 'not solved', - captchaId: taskId, + const elapsedMs = Math.round(performance.now() - startedAt); + this._emitDebug('solve.summary', { + status: 'not_solved', + reason: this._failureReason(error), elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, elapsedMs, - resultRequestCount - }); + createTaskRequestCount: totalRequestCount > 0 ? 1 : 0, + resultRequestCount, + totalRequestCount, + ...this._errorDetails(error) + }, 'error', { solveId, ...(taskId === null ? {} : { taskId }) }); throw error; } } diff --git a/src/index.ts b/src/index.ts index 6cea1fb..b143875 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ export { CaptchaClient } from './client.js'; -export type { CaptchaClientOptions, TaskResult, SolutionOf } from './client.js'; +export type { CaptchaClientOptions, DebugEvent, DebugLevel, DebugLogger, TaskResult, SolutionOf } from './client.js'; export { ApiError, NetworkError, TimeoutError, ValidationError, CaptchaError } from './exceptions.js'; export * as Tasks from './tasks.js'; export type { diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index c662039..bada887 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -39,172 +39,158 @@ describe('CaptchaClient (async)', () => { expect(requestOptions.headers['X-SDK']).toBe('javascript-sdk/1.1.0'); }); - test('debug mode logs sanitized request lifecycle events', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); - global.fetch = jest.fn(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) - })); + test('debug logger receives timestamped and sanitized structured events', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); + global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); await client.getBalance(); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] request started', { endpoint: '/getBalance' }); - const requestLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server request:'))?.[0]; - expect(requestLog).toContain('"url": "https://api.captcha-solver.com/getBalance"'); - expect(requestLog).toContain('"clientKey": "[REDACTED]"'); - const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; - expect(responseLog).toContain('"endpoint": "/getBalance"'); - expect(responseLog).toContain('"status": 200'); - expect(responseLog).toContain('"balance": "1.00"'); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] client initialized', { - baseUrl: 'https://api.captcha-solver.com', - timeout: 120000, - pollingInterval: 5000 - }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] request completed', { - endpoint: '/getBalance', - status: 200, - durationMs: expect.any(Number) - }); - const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); - const completedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request completed'); - expect(responseLogIndex).toBeLessThan(completedLogIndex); - expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); - debug.mockRestore(); + expect(events.map(({ event }) => event)).toEqual([ + 'client.initialized', 'request.started', 'server.request', 'server.response', 'request.completed' + ]); + expect(events.every(({ timestamp }) => !Number.isNaN(Date.parse(timestamp)))).toBe(true); + expect(events.find(({ event }) => event === 'server.request').body.clientKey).toBe('[REDACTED]'); + expect(events.find(({ event }) => event === 'server.response')).toMatchObject({ level: 'debug', status: 200, body: { balance: '1.00' } }); + expect(JSON.stringify(events)).not.toContain('secret_key'); }); - test('debug mode logs task type, task ID, and polling progress', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + test('solve correlates events and counts processing result requests', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); global.fetch = jest.fn() - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) - })) - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: `start-${'x'.repeat(300)}-end` } }) - })); - const task = new Tasks.RecaptchaV2Proxyless({ - websiteURL: 'https://example.com', - websiteKey: 'website_key' - }); + .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) })) + .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, status: 'processing' }) })) + .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: 'secret_solution' } }) })); + const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); await client.solve(task); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] task created', { - taskId: 12345, - taskType: 'RecaptchaV2TaskProxyless' - }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] task status received', { - taskId: 12345, - pollAttempt: 1, - status: 'ready', - elapsedMs: expect.any(Number) - }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] task solved', { - taskId: 12345, - pollAttempts: 1, - elapsedMs: expect.any(Number) - }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { - status: 'solved', - captchaId: 12345, - elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), - elapsedMs: expect.any(Number), - resultRequestCount: 1 + const solveEvents = events.filter(({ solveId }) => solveId); + expect(new Set(solveEvents.map(({ solveId }) => solveId)).size).toBe(1); + expect(events.find(({ event }) => event === 'task.created')).toMatchObject({ taskId: 12345, taskType: 'RecaptchaV2TaskProxyless' }); + expect(events.find(({ event }) => event === 'solve.summary')).toMatchObject({ + level: 'info', status: 'solved', taskId: 12345, createTaskRequestCount: 1, resultRequestCount: 2, totalRequestCount: 3 }); - const logged = JSON.stringify(debug.mock.calls); - expect(logged).toContain('website_key'); - expect(logged).toContain('original length: 310'); - expect(logged).not.toContain(`start-${'x'.repeat(300)}-end`); - expect(logged).not.toContain('secret_key'); - const resultResponseLogIndex = debug.mock.calls.findIndex(([message, details]) => - message.startsWith('[CaptchaClient] server response:') && message.includes('"endpoint": "/getTaskResult"') - ); - const resultCompletedLogIndex = debug.mock.calls.findIndex(([message, details]) => - message === '[CaptchaClient] request completed' && details.endpoint === '/getTaskResult' - ); - const statusLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] task status received'); - expect(resultResponseLogIndex).toBeLessThan(resultCompletedLogIndex); - expect(resultCompletedLogIndex).toBeLessThan(statusLogIndex); - debug.mockRestore(); + expect(JSON.stringify(events)).toContain('[REDACTED token; original length: 15]'); + expect(JSON.stringify(events)).not.toContain('secret_solution'); }); test('debug mode is silent by default', async () => { const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - global.fetch = jest.fn(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) - })); - + global.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); await client.getBalance(); - expect(debug).not.toHaveBeenCalled(); debug.mockRestore(); }); - test('debug mode logs a not-solved summary after a result request fails', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + test('solve summary explains API failures', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); global.fetch = jest.fn() - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) - })) - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' }) - })); - const task = new Tasks.RecaptchaV2Proxyless({ - websiteURL: 'https://example.com', - websiteKey: 'website_key' - }); + .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) })) + .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' }) })); + const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); await expect(client.solve(task)).rejects.toThrow(ApiError); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { - status: 'not solved', - captchaId: 12345, - elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), - elapsedMs: expect.any(Number), - resultRequestCount: 1 + expect(events.find(({ event }) => event === 'solve.summary')).toMatchObject({ + level: 'error', status: 'not_solved', reason: 'api_error', taskId: 12345, + errorName: 'ApiError', errorCode: 'ERROR_TASK_FAILED', resultRequestCount: 1, totalRequestCount: 2 }); - debug.mockRestore(); }); - test('debug mode logs the original API error response before throwing', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); - const errorBody = { - errorId: 1, - errorCode: 'ERROR_KEY_DOES_NOT_EXIST', - errorDescription: 'Account not found' - }; + test('debug logger preserves a non-JSON server error body', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); + global.fetch = jest.fn(() => Promise.resolve({ ok: false, status: 502, statusText: 'Bad Gateway', text: () => Promise.resolve('upstream failed') })); + + await expect(client.getBalance()).rejects.toThrow(NetworkError); + + expect(events.find(({ event }) => event === 'server.response')).toMatchObject({ + level: 'error', status: 502, body: 'upstream failed' + }); + }); + + test('logger failures do not change the SDK result', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: () => { throw new Error('logger failed'); } }); + global.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); + await expect(client.getBalance()).resolves.toBe(1); + }); + + test('parallel solves use different correlation IDs', async () => { + const events = []; + let nextTaskId = 100; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); + global.fetch = jest.fn((url, options) => { + const body = JSON.parse(options.body); + const response = url.endsWith('/createTask') + ? { errorId: 0, taskId: nextTaskId++ } + : { errorId: 0, status: 'ready', solution: { token: `token-${body.taskId}` } }; + return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(response) }); + }); + const task = () => new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); + + await Promise.all([client.solve(task()), client.solve(task())]); + + const summaries = events.filter(({ event }) => event === 'solve.summary'); + expect(summaries).toHaveLength(2); + expect(new Set(summaries.map(({ solveId }) => solveId)).size).toBe(2); + expect(new Set(summaries.map(({ taskId }) => taskId))).toEqual(new Set([100, 101])); + }); + + test('createTask failure summary has no task ID and explains the error', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, - statusText: 'OK', - json: () => Promise.resolve(errorBody) + json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_ZERO_BALANCE', errorDescription: 'No funds' }) })); + const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); - await expect(client.getBalance()).rejects.toThrow(ApiError); + await expect(client.solve(task)).rejects.toThrow(ApiError); - const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; - expect(responseLog).toContain('"endpoint": "/getBalance"'); - expect(responseLog).toContain('"errorCode": "ERROR_KEY_DOES_NOT_EXIST"'); - expect(responseLog).toContain('"errorDescription": "Account not found"'); - const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); - const failedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request failed'); - expect(responseLogIndex).toBeLessThan(failedLogIndex); - debug.mockRestore(); + const summary = events.find(({ event }) => event === 'solve.summary'); + expect(summary).toMatchObject({ reason: 'api_error', createTaskRequestCount: 1, resultRequestCount: 0, totalRequestCount: 1 }); + expect(summary).not.toHaveProperty('taskId'); + }); + + test('debug sanitization omits binary data and redacts URL secrets', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); + global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) })); + const task = new Tasks.ImageToText({ body: 'a'.repeat(500), comment: 'test' }); + + await client.createTask(task); + await client.createTask(new Tasks.RecaptchaV2Proxyless({ + websiteURL: 'https://example.com/login?access_token=url-secret', + websiteKey: 'website_key' + })); + + const requests = events.filter(({ event }) => event === 'server.request'); + expect(requests[0].body.task.body).toBe('[OMITTED binary data; original length: 500]'); + expect(requests[1].body.task.websiteURL).not.toContain('url-secret'); + expect(JSON.stringify(events)).not.toContain('a'.repeat(200)); + }); + + test('solve timeout is a deadline for the complete operation', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), timeout: 300, pollingInterval: 0 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => new Promise((resolve) => setTimeout(() => resolve({ + ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) + }), 100))) + .mockImplementationOnce((url, options) => new Promise((resolve, reject) => { + options.signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))); + })); + const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); + const startedAt = performance.now(); + + await expect(client.solve(task)).rejects.toThrow(TimeoutError); + + expect(performance.now() - startedAt).toBeLessThan(380); + expect(events.find(({ event }) => event === 'solve.summary')).toMatchObject({ reason: 'timeout', totalRequestCount: 2 }); }); test('aborts an HTTP request after timeout', async () => { From c7657e381ba7f09d0a4670f3ef6da151f616eb18 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:20:40 +0300 Subject: [PATCH 11/31] docs: enable debug directly in Kaleidoscope example --- examples/yandex_smartcaptcha_kaleidoscope.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 699f3c2..4f5bcbd 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -22,7 +22,7 @@ if (!process.env.CAPTCHA_API_KEY) { // STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY, - debug: process.env.CAPTCHA_DEBUG === '1' + debug: true }); const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) From 96294e134eee81cb323618f68dfe7b3333ec5422 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:27:54 +0300 Subject: [PATCH 12/31] feat: add concise and trace debug modes --- CHANGELOG.md | 1 + README.md | 14 +++++++++++++- src/client.ts | 31 +++++++++++++++++++++++++------ src/index.ts | 2 +- tests/unit/async/client.test.js | 12 +++++++++++- 5 files changed, 51 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96a4601..e35f4b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes are documented here. ### Added - add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries +- add concise `debug: true` output and an opt-in `debug: 'trace'` mode for low-level lifecycle events - add a debug logger callback for forwarding events to application loggers or files ### Fixed diff --git a/README.md b/README.md index ac47c9b..5f74104 100644 --- a/README.md +++ b/README.md @@ -681,7 +681,8 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print structured request, response, and polling lifecycle events. +Enable `debug` to print a concise structured flow with server requests and responses, +task state changes, errors, and the final summary. Every event includes an ISO timestamp, severity level, event name, and correlation IDs. Debug output includes the HTTP method and URL, sanitized request body, response status and body, task IDs, and task statuses. At the end of `solve()`, a summary reports the @@ -699,6 +700,17 @@ const captchaSolver = new CaptchaClient({ }); ``` +Use `debug: 'trace'` only when low-level timing is needed. Trace mode additionally +prints client initialization, request start/completion, polling waits, and other +internal lifecycle events: + +```javascript +const captchaSolver = new CaptchaClient({ + clientKey: 'your_api_key', + debug: 'trace' +}); +``` + Pass `logger` to receive the same structured events without writing to the console. The callback can forward events to a file or an application logger; the SDK never creates log files on its own: diff --git a/src/client.ts b/src/client.ts index d558e2e..fec73f3 100644 --- a/src/client.ts +++ b/src/client.ts @@ -3,6 +3,14 @@ import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; const MAX_DEBUG_STRING_LENGTH = 200; +const TRACE_ONLY_EVENTS = new Set([ + 'client.initialized', + 'task.submission.started', + 'request.started', + 'request.completed', + 'poll.waiting', + 'task.solved' +]); let operationSequence = 0; interface DebugContext { @@ -25,6 +33,9 @@ export interface DebugEvent extends DebugContext { /** Receives structured debug events. Use this to integrate a logger or file stream. */ export type DebugLogger = (event: DebugEvent) => void; +/** Debug output mode: `true` is concise, while `'trace'` includes every lifecycle event. */ +export type DebugMode = boolean | 'trace'; + /** Options accepted by the {@link CaptchaClient} constructor. */ export interface CaptchaClientOptions { /** Your Captcha Solver API key. Required. */ @@ -48,12 +59,13 @@ export interface CaptchaClientOptions { */ pollingInterval?: number; /** - * Print request and polling lifecycle events to `console.debug`. + * Print structured request and polling events. `true` keeps the useful concise + * flow; `'trace'` also includes low-level request timing and polling events. * Request and response bodies are included after credentials are redacted * and long strings such as base64 images and solution tokens are truncated. * @defaultValue `false` */ - debug?: boolean; + debug?: DebugMode; /** * Optional structured event receiver used instead of the default console renderer. * Only called when {@link debug} is `true`. @@ -108,7 +120,7 @@ export class CaptchaClient { /** Delay between polls inside {@link solve}, in milliseconds. */ pollingInterval: number; /** Whether lifecycle debug logging is enabled. */ - debug: boolean; + debug: DebugMode; /** Structured debug event receiver. */ logger: DebugLogger; @@ -161,7 +173,13 @@ export class CaptchaClient { /** Render one structured event for users who did not supply a logger callback. */ private _writeDebugToConsole(event: DebugEvent): void { - const output = `[CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}`; + const isServerExchange = event.event === 'server.request' || event.event === 'server.response'; + const output = isServerExchange + ? `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}` + : `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event} ${Object.entries(event) + .filter(([key]) => !['timestamp', 'level', 'event'].includes(key)) + .map(([key, value]) => `${key}=${JSON.stringify(value)}`) + .join(' ')}`; if (event.level === 'error') console.error(output); else if (event.level === 'info') console.info(output); else console.debug(output); @@ -170,6 +188,7 @@ export class CaptchaClient { /** Emit one sanitized event. Logger failures never change the SDK operation result. */ private _emitDebug(event: string, details: Record = {}, level: DebugLevel = 'debug', context: DebugContext = {}): void { if (!this.debug) return; + if (this.debug !== 'trace' && TRACE_ONLY_EVENTS.has(event)) return; const record = this._sanitizeForDebug({ timestamp: new Date().toISOString(), level, event, ...context, ...details }) as DebugEvent; try { this.logger(record); } catch { /* Diagnostics must not break API calls. */ } } @@ -223,7 +242,7 @@ export class CaptchaClient { try { data = JSON.parse(rawBody) as typeof data; } catch (parseError) { - this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: rawBody }, 'error', requestContext); + this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, durationMs: Math.round(performance.now() - startedAt), body: rawBody }, 'error', requestContext); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`, parseError); throw new NetworkError(`Invalid JSON response from ${endpoint}`, parseError); } @@ -232,7 +251,7 @@ export class CaptchaClient { data = await response.json() as typeof data; } const responseLevel: DebugLevel = !response.ok || !data || data.errorId !== 0 ? 'error' : 'debug'; - this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: data }, responseLevel, requestContext); + this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, durationMs: Math.round(performance.now() - startedAt), body: data }, responseLevel, requestContext); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); if (!data || typeof data !== 'object') throw new NetworkError(`Invalid JSON response from ${endpoint}`); if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); diff --git a/src/index.ts b/src/index.ts index b143875..475c303 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ export { CaptchaClient } from './client.js'; -export type { CaptchaClientOptions, DebugEvent, DebugLevel, DebugLogger, TaskResult, SolutionOf } from './client.js'; +export type { CaptchaClientOptions, DebugEvent, DebugLevel, DebugLogger, DebugMode, TaskResult, SolutionOf } from './client.js'; export { ApiError, NetworkError, TimeoutError, ValidationError, CaptchaError } from './exceptions.js'; export * as Tasks from './tasks.js'; export type { diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index bada887..5783043 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -41,7 +41,7 @@ describe('CaptchaClient (async)', () => { test('debug logger receives timestamped and sanitized structured events', async () => { const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); + client = new CaptchaClient({ clientKey: 'secret_key', debug: 'trace', logger: (event) => events.push(event) }); global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); await client.getBalance(); @@ -55,6 +55,16 @@ describe('CaptchaClient (async)', () => { expect(JSON.stringify(events)).not.toContain('secret_key'); }); + test('concise debug omits trace-only lifecycle events', async () => { + const events = []; + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); + global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); + + await client.getBalance(); + + expect(events.map(({ event }) => event)).toEqual(['server.request', 'server.response']); + }); + test('solve correlates events and counts processing result requests', async () => { const events = []; client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); From 82298481e56820d34b70eb12b6fb4016f29e536d Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:30:34 +0300 Subject: [PATCH 13/31] feat: format debug output as Linux-style lines --- CHANGELOG.md | 1 + README.md | 5 +++-- src/client.ts | 22 ++++++++++++++++------ tests/unit/async/client.test.js | 13 +++++++++++++ 4 files changed, 33 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e35f4b3..c6d17b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes are documented here. - add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries - add concise `debug: true` output and an opt-in `debug: 'trace'` mode for low-level lifecycle events +- format default console diagnostics as Linux-style one-record-per-line logs - add a debug logger callback for forwarding events to application loggers or files ### Fixed diff --git a/README.md b/README.md index 5f74104..db91e1e 100644 --- a/README.md +++ b/README.md @@ -689,8 +689,9 @@ and body, task IDs, and task statuses. At the end of `solve()`, a summary report outcome or failure reason, total elapsed time, and request counts. Credential and token fields are redacted; binary data and other long strings are omitted or truncated. -Server exchanges are printed as single labelled JSON blocks, so the response body -always remains visually attached to `[CaptchaClient] server response` in the console. +Console output uses a Linux-style one-record-per-line format. `→` marks an outbound +request and `←` marks the matching server response; correlation IDs remain on the +same line. Custom loggers still receive the full structured event object. ```javascript // Create a client with detailed, sanitized lifecycle logging enabled. diff --git a/src/client.ts b/src/client.ts index fec73f3..4edcf48 100644 --- a/src/client.ts +++ b/src/client.ts @@ -173,13 +173,23 @@ export class CaptchaClient { /** Render one structured event for users who did not supply a logger callback. */ private _writeDebugToConsole(event: DebugEvent): void { - const isServerExchange = event.event === 'server.request' || event.event === 'server.response'; - const output = isServerExchange - ? `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}` - : `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event} ${Object.entries(event) - .filter(([key]) => !['timestamp', 'level', 'event'].includes(key)) + const level = event.level.toUpperCase().padEnd(5); + const context = [event.solveId && `solve=${event.solveId}`, event.taskId !== undefined && `task=${event.taskId}`, event.requestId && `request=${event.requestId}`] + .filter(Boolean) + .join(' '); + let message: string; + if (event.event === 'server.request') { + message = `→ ${event.method} ${event.url} body=${JSON.stringify(event.body)}`; + } else if (event.event === 'server.response') { + message = `← ${event.status} ${event.statusText || ''} ${event.endpoint} ${event.durationMs}ms body=${JSON.stringify(event.body)}`; + } else { + const details = Object.entries(event) + .filter(([key]) => !['timestamp', 'level', 'event', 'solveId', 'taskId', 'requestId'].includes(key)) .map(([key, value]) => `${key}=${JSON.stringify(value)}`) - .join(' ')}`; + .join(' '); + message = `${event.event}${details ? ` ${details}` : ''}`; + } + const output = `${event.timestamp} ${level} captcha-solver${context ? ` ${context}` : ''} ${message}`; if (event.level === 'error') console.error(output); else if (event.level === 'info') console.info(output); else console.debug(output); diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 5783043..101becd 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -65,6 +65,19 @@ describe('CaptchaClient (async)', () => { expect(events.map(({ event }) => event)).toEqual(['server.request', 'server.response']); }); + test('default console output uses readable Linux-style request lines', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); + + await client.getBalance(); + + expect(debug.mock.calls[0][0]).toMatch(/^\d{4}-\d{2}-\d{2}T.* DEBUG captcha-solver request=.* → POST https:\/\/api\.captcha-solver\.com\/getBalance body=/); + expect(debug.mock.calls[1][0]).toMatch(/ DEBUG captcha-solver request=.* ← 200 OK \/getBalance \d+ms body=/); + expect(debug.mock.calls.every((call) => !call[0].includes('\n'))).toBe(true); + debug.mockRestore(); + }); + test('solve correlates events and counts processing result requests', async () => { const events = []; client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); From ca39e9529a4619357de607920048071dd17c24b2 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:35:20 +0300 Subject: [PATCH 14/31] feat: improve concise debug readability --- CHANGELOG.md | 1 + README.md | 6 +++--- src/client.ts | 18 +++++++++++++----- tests/unit/async/client.test.js | 5 ++--- 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6d17b4..9a7b879 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes are documented here. - add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries - add concise `debug: true` output and an opt-in `debug: 'trace'` mode for low-level lifecycle events - format default console diagnostics as Linux-style one-record-per-line logs +- shorten console correlation IDs and place sanitized HTTP bodies on indented continuation lines - add a debug logger callback for forwarding events to application loggers or files ### Fixed diff --git a/README.md b/README.md index db91e1e..7a61e17 100644 --- a/README.md +++ b/README.md @@ -689,9 +689,9 @@ and body, task IDs, and task statuses. At the end of `solve()`, a summary report outcome or failure reason, total elapsed time, and request counts. Credential and token fields are redacted; binary data and other long strings are omitted or truncated. -Console output uses a Linux-style one-record-per-line format. `→` marks an outbound -request and `←` marks the matching server response; correlation IDs remain on the -same line. Custom loggers still receive the full structured event object. +Console output uses short Linux-style event lines. `→` marks an outbound request and +`←` marks the matching server response; sanitized bodies appear on one indented line +below the exchange. Custom loggers still receive the full structured event object. ```javascript // Create a client with detailed, sanitized lifecycle logging enabled. diff --git a/src/client.ts b/src/client.ts index 4edcf48..4b44c6d 100644 --- a/src/client.ts +++ b/src/client.ts @@ -2,13 +2,14 @@ import { ApiError, NetworkError, TimeoutError, ValidationError } from './excepti import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; -const MAX_DEBUG_STRING_LENGTH = 200; +const MAX_DEBUG_STRING_LENGTH = 120; const TRACE_ONLY_EVENTS = new Set([ 'client.initialized', 'task.submission.started', 'request.started', 'request.completed', 'poll.waiting', + 'task.status.received', 'task.solved' ]); let operationSequence = 0; @@ -179,9 +180,16 @@ export class CaptchaClient { .join(' '); let message: string; if (event.event === 'server.request') { - message = `→ ${event.method} ${event.url} body=${JSON.stringify(event.body)}`; + const host = typeof event.url === 'string' ? new URL(event.url).host : 'unknown'; + message = `→ ${event.method} ${event.endpoint} host=${host}\n request body: ${JSON.stringify(event.body)}`; } else if (event.event === 'server.response') { - message = `← ${event.status} ${event.statusText || ''} ${event.endpoint} ${event.durationMs}ms body=${JSON.stringify(event.body)}`; + message = `← ${event.status} ${event.statusText || ''} ${event.endpoint} ${event.durationMs}ms\n response body: ${JSON.stringify(event.body)}`; + } else if (event.event === 'solve.started') { + message = `START type=${event.taskClass} timeout=${event.timeoutMs}ms`; + } else if (event.event === 'task.created') { + message = `CREATED type=${event.taskType}`; + } else if (event.event === 'solve.summary') { + message = `DONE status=${event.status} time=${event.elapsedTime} requests=${event.totalRequestCount}${event.reason ? ` reason=${event.reason}` : ''}`; } else { const details = Object.entries(event) .filter(([key]) => !['timestamp', 'level', 'event', 'solveId', 'taskId', 'requestId'].includes(key)) @@ -205,7 +213,7 @@ export class CaptchaClient { private _newOperationId(prefix: 'solve' | 'request'): string { operationSequence += 1; - return `${prefix}-${Date.now().toString(36)}-${operationSequence.toString(36)}`; + return `${prefix}-${operationSequence.toString(36)}`; } private _errorDetails(error: unknown): Record { @@ -243,7 +251,7 @@ export class CaptchaClient { const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; const requestContext = { ...context, requestId: this._newOperationId('request') }; this._emitDebug('request.started', { endpoint, timeoutMs: effectiveTimeout }, 'debug', requestContext); - this._emitDebug('server.request', { method: 'POST', url, headers, body: payload }, 'debug', requestContext); + this._emitDebug('server.request', { method: 'POST', endpoint, url, headers, body: payload }, 'debug', requestContext); try { const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); let data: TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 101becd..f029a6f 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -72,9 +72,8 @@ describe('CaptchaClient (async)', () => { await client.getBalance(); - expect(debug.mock.calls[0][0]).toMatch(/^\d{4}-\d{2}-\d{2}T.* DEBUG captcha-solver request=.* → POST https:\/\/api\.captcha-solver\.com\/getBalance body=/); - expect(debug.mock.calls[1][0]).toMatch(/ DEBUG captcha-solver request=.* ← 200 OK \/getBalance \d+ms body=/); - expect(debug.mock.calls.every((call) => !call[0].includes('\n'))).toBe(true); + expect(debug.mock.calls[0][0]).toMatch(/^\d{4}-\d{2}-\d{2}T.* DEBUG captcha-solver request=request-\w+ → POST \/getBalance host=api\.captcha-solver\.com\n request body:/); + expect(debug.mock.calls[1][0]).toMatch(/ DEBUG captcha-solver request=request-\w+ ← 200 OK \/getBalance \d+ms\n response body:/); debug.mockRestore(); }); From f53a858e83590bb66cc92d069abe73ba76f01931 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:39:21 +0300 Subject: [PATCH 15/31] Revert "feat: improve concise debug readability" This reverts commit ca39e9529a4619357de607920048071dd17c24b2. --- CHANGELOG.md | 1 - README.md | 6 +++--- src/client.ts | 18 +++++------------- tests/unit/async/client.test.js | 5 +++-- 4 files changed, 11 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a7b879..c6d17b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,6 @@ All notable changes are documented here. - add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries - add concise `debug: true` output and an opt-in `debug: 'trace'` mode for low-level lifecycle events - format default console diagnostics as Linux-style one-record-per-line logs -- shorten console correlation IDs and place sanitized HTTP bodies on indented continuation lines - add a debug logger callback for forwarding events to application loggers or files ### Fixed diff --git a/README.md b/README.md index 7a61e17..db91e1e 100644 --- a/README.md +++ b/README.md @@ -689,9 +689,9 @@ and body, task IDs, and task statuses. At the end of `solve()`, a summary report outcome or failure reason, total elapsed time, and request counts. Credential and token fields are redacted; binary data and other long strings are omitted or truncated. -Console output uses short Linux-style event lines. `→` marks an outbound request and -`←` marks the matching server response; sanitized bodies appear on one indented line -below the exchange. Custom loggers still receive the full structured event object. +Console output uses a Linux-style one-record-per-line format. `→` marks an outbound +request and `←` marks the matching server response; correlation IDs remain on the +same line. Custom loggers still receive the full structured event object. ```javascript // Create a client with detailed, sanitized lifecycle logging enabled. diff --git a/src/client.ts b/src/client.ts index 4b44c6d..4edcf48 100644 --- a/src/client.ts +++ b/src/client.ts @@ -2,14 +2,13 @@ import { ApiError, NetworkError, TimeoutError, ValidationError } from './excepti import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; -const MAX_DEBUG_STRING_LENGTH = 120; +const MAX_DEBUG_STRING_LENGTH = 200; const TRACE_ONLY_EVENTS = new Set([ 'client.initialized', 'task.submission.started', 'request.started', 'request.completed', 'poll.waiting', - 'task.status.received', 'task.solved' ]); let operationSequence = 0; @@ -180,16 +179,9 @@ export class CaptchaClient { .join(' '); let message: string; if (event.event === 'server.request') { - const host = typeof event.url === 'string' ? new URL(event.url).host : 'unknown'; - message = `→ ${event.method} ${event.endpoint} host=${host}\n request body: ${JSON.stringify(event.body)}`; + message = `→ ${event.method} ${event.url} body=${JSON.stringify(event.body)}`; } else if (event.event === 'server.response') { - message = `← ${event.status} ${event.statusText || ''} ${event.endpoint} ${event.durationMs}ms\n response body: ${JSON.stringify(event.body)}`; - } else if (event.event === 'solve.started') { - message = `START type=${event.taskClass} timeout=${event.timeoutMs}ms`; - } else if (event.event === 'task.created') { - message = `CREATED type=${event.taskType}`; - } else if (event.event === 'solve.summary') { - message = `DONE status=${event.status} time=${event.elapsedTime} requests=${event.totalRequestCount}${event.reason ? ` reason=${event.reason}` : ''}`; + message = `← ${event.status} ${event.statusText || ''} ${event.endpoint} ${event.durationMs}ms body=${JSON.stringify(event.body)}`; } else { const details = Object.entries(event) .filter(([key]) => !['timestamp', 'level', 'event', 'solveId', 'taskId', 'requestId'].includes(key)) @@ -213,7 +205,7 @@ export class CaptchaClient { private _newOperationId(prefix: 'solve' | 'request'): string { operationSequence += 1; - return `${prefix}-${operationSequence.toString(36)}`; + return `${prefix}-${Date.now().toString(36)}-${operationSequence.toString(36)}`; } private _errorDetails(error: unknown): Record { @@ -251,7 +243,7 @@ export class CaptchaClient { const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; const requestContext = { ...context, requestId: this._newOperationId('request') }; this._emitDebug('request.started', { endpoint, timeoutMs: effectiveTimeout }, 'debug', requestContext); - this._emitDebug('server.request', { method: 'POST', endpoint, url, headers, body: payload }, 'debug', requestContext); + this._emitDebug('server.request', { method: 'POST', url, headers, body: payload }, 'debug', requestContext); try { const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); let data: TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index f029a6f..101becd 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -72,8 +72,9 @@ describe('CaptchaClient (async)', () => { await client.getBalance(); - expect(debug.mock.calls[0][0]).toMatch(/^\d{4}-\d{2}-\d{2}T.* DEBUG captcha-solver request=request-\w+ → POST \/getBalance host=api\.captcha-solver\.com\n request body:/); - expect(debug.mock.calls[1][0]).toMatch(/ DEBUG captcha-solver request=request-\w+ ← 200 OK \/getBalance \d+ms\n response body:/); + expect(debug.mock.calls[0][0]).toMatch(/^\d{4}-\d{2}-\d{2}T.* DEBUG captcha-solver request=.* → POST https:\/\/api\.captcha-solver\.com\/getBalance body=/); + expect(debug.mock.calls[1][0]).toMatch(/ DEBUG captcha-solver request=.* ← 200 OK \/getBalance \d+ms body=/); + expect(debug.mock.calls.every((call) => !call[0].includes('\n'))).toBe(true); debug.mockRestore(); }); From 280ceaa06f2e7d45e391e425aabf12e26eaea405 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:39:21 +0300 Subject: [PATCH 16/31] Revert "feat: format debug output as Linux-style lines" This reverts commit 82298481e56820d34b70eb12b6fb4016f29e536d. --- CHANGELOG.md | 1 - README.md | 5 ++--- src/client.ts | 22 ++++++---------------- tests/unit/async/client.test.js | 13 ------------- 4 files changed, 8 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6d17b4..e35f4b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,6 @@ All notable changes are documented here. - add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries - add concise `debug: true` output and an opt-in `debug: 'trace'` mode for low-level lifecycle events -- format default console diagnostics as Linux-style one-record-per-line logs - add a debug logger callback for forwarding events to application loggers or files ### Fixed diff --git a/README.md b/README.md index db91e1e..5f74104 100644 --- a/README.md +++ b/README.md @@ -689,9 +689,8 @@ and body, task IDs, and task statuses. At the end of `solve()`, a summary report outcome or failure reason, total elapsed time, and request counts. Credential and token fields are redacted; binary data and other long strings are omitted or truncated. -Console output uses a Linux-style one-record-per-line format. `→` marks an outbound -request and `←` marks the matching server response; correlation IDs remain on the -same line. Custom loggers still receive the full structured event object. +Server exchanges are printed as single labelled JSON blocks, so the response body +always remains visually attached to `[CaptchaClient] server response` in the console. ```javascript // Create a client with detailed, sanitized lifecycle logging enabled. diff --git a/src/client.ts b/src/client.ts index 4edcf48..fec73f3 100644 --- a/src/client.ts +++ b/src/client.ts @@ -173,23 +173,13 @@ export class CaptchaClient { /** Render one structured event for users who did not supply a logger callback. */ private _writeDebugToConsole(event: DebugEvent): void { - const level = event.level.toUpperCase().padEnd(5); - const context = [event.solveId && `solve=${event.solveId}`, event.taskId !== undefined && `task=${event.taskId}`, event.requestId && `request=${event.requestId}`] - .filter(Boolean) - .join(' '); - let message: string; - if (event.event === 'server.request') { - message = `→ ${event.method} ${event.url} body=${JSON.stringify(event.body)}`; - } else if (event.event === 'server.response') { - message = `← ${event.status} ${event.statusText || ''} ${event.endpoint} ${event.durationMs}ms body=${JSON.stringify(event.body)}`; - } else { - const details = Object.entries(event) - .filter(([key]) => !['timestamp', 'level', 'event', 'solveId', 'taskId', 'requestId'].includes(key)) + const isServerExchange = event.event === 'server.request' || event.event === 'server.response'; + const output = isServerExchange + ? `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}` + : `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event} ${Object.entries(event) + .filter(([key]) => !['timestamp', 'level', 'event'].includes(key)) .map(([key, value]) => `${key}=${JSON.stringify(value)}`) - .join(' '); - message = `${event.event}${details ? ` ${details}` : ''}`; - } - const output = `${event.timestamp} ${level} captcha-solver${context ? ` ${context}` : ''} ${message}`; + .join(' ')}`; if (event.level === 'error') console.error(output); else if (event.level === 'info') console.info(output); else console.debug(output); diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 101becd..5783043 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -65,19 +65,6 @@ describe('CaptchaClient (async)', () => { expect(events.map(({ event }) => event)).toEqual(['server.request', 'server.response']); }); - test('default console output uses readable Linux-style request lines', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); - - await client.getBalance(); - - expect(debug.mock.calls[0][0]).toMatch(/^\d{4}-\d{2}-\d{2}T.* DEBUG captcha-solver request=.* → POST https:\/\/api\.captcha-solver\.com\/getBalance body=/); - expect(debug.mock.calls[1][0]).toMatch(/ DEBUG captcha-solver request=.* ← 200 OK \/getBalance \d+ms body=/); - expect(debug.mock.calls.every((call) => !call[0].includes('\n'))).toBe(true); - debug.mockRestore(); - }); - test('solve correlates events and counts processing result requests', async () => { const events = []; client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); From 6e45217edbd63207d51b26416802c4e1f2624e37 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:39:21 +0300 Subject: [PATCH 17/31] Revert "feat: add concise and trace debug modes" This reverts commit 96294e134eee81cb323618f68dfe7b3333ec5422. --- CHANGELOG.md | 1 - README.md | 14 +------------- src/client.ts | 31 ++++++------------------------- src/index.ts | 2 +- tests/unit/async/client.test.js | 12 +----------- 5 files changed, 9 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e35f4b3..96a4601 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,6 @@ All notable changes are documented here. ### Added - add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries -- add concise `debug: true` output and an opt-in `debug: 'trace'` mode for low-level lifecycle events - add a debug logger callback for forwarding events to application loggers or files ### Fixed diff --git a/README.md b/README.md index 5f74104..ac47c9b 100644 --- a/README.md +++ b/README.md @@ -681,8 +681,7 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print a concise structured flow with server requests and responses, -task state changes, errors, and the final summary. +Enable `debug` to print structured request, response, and polling lifecycle events. Every event includes an ISO timestamp, severity level, event name, and correlation IDs. Debug output includes the HTTP method and URL, sanitized request body, response status and body, task IDs, and task statuses. At the end of `solve()`, a summary reports the @@ -700,17 +699,6 @@ const captchaSolver = new CaptchaClient({ }); ``` -Use `debug: 'trace'` only when low-level timing is needed. Trace mode additionally -prints client initialization, request start/completion, polling waits, and other -internal lifecycle events: - -```javascript -const captchaSolver = new CaptchaClient({ - clientKey: 'your_api_key', - debug: 'trace' -}); -``` - Pass `logger` to receive the same structured events without writing to the console. The callback can forward events to a file or an application logger; the SDK never creates log files on its own: diff --git a/src/client.ts b/src/client.ts index fec73f3..d558e2e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -3,14 +3,6 @@ import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; const MAX_DEBUG_STRING_LENGTH = 200; -const TRACE_ONLY_EVENTS = new Set([ - 'client.initialized', - 'task.submission.started', - 'request.started', - 'request.completed', - 'poll.waiting', - 'task.solved' -]); let operationSequence = 0; interface DebugContext { @@ -33,9 +25,6 @@ export interface DebugEvent extends DebugContext { /** Receives structured debug events. Use this to integrate a logger or file stream. */ export type DebugLogger = (event: DebugEvent) => void; -/** Debug output mode: `true` is concise, while `'trace'` includes every lifecycle event. */ -export type DebugMode = boolean | 'trace'; - /** Options accepted by the {@link CaptchaClient} constructor. */ export interface CaptchaClientOptions { /** Your Captcha Solver API key. Required. */ @@ -59,13 +48,12 @@ export interface CaptchaClientOptions { */ pollingInterval?: number; /** - * Print structured request and polling events. `true` keeps the useful concise - * flow; `'trace'` also includes low-level request timing and polling events. + * Print request and polling lifecycle events to `console.debug`. * Request and response bodies are included after credentials are redacted * and long strings such as base64 images and solution tokens are truncated. * @defaultValue `false` */ - debug?: DebugMode; + debug?: boolean; /** * Optional structured event receiver used instead of the default console renderer. * Only called when {@link debug} is `true`. @@ -120,7 +108,7 @@ export class CaptchaClient { /** Delay between polls inside {@link solve}, in milliseconds. */ pollingInterval: number; /** Whether lifecycle debug logging is enabled. */ - debug: DebugMode; + debug: boolean; /** Structured debug event receiver. */ logger: DebugLogger; @@ -173,13 +161,7 @@ export class CaptchaClient { /** Render one structured event for users who did not supply a logger callback. */ private _writeDebugToConsole(event: DebugEvent): void { - const isServerExchange = event.event === 'server.request' || event.event === 'server.response'; - const output = isServerExchange - ? `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}` - : `[${event.timestamp}] [${event.level.toUpperCase()}] [CaptchaClient] ${event.event} ${Object.entries(event) - .filter(([key]) => !['timestamp', 'level', 'event'].includes(key)) - .map(([key, value]) => `${key}=${JSON.stringify(value)}`) - .join(' ')}`; + const output = `[CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}`; if (event.level === 'error') console.error(output); else if (event.level === 'info') console.info(output); else console.debug(output); @@ -188,7 +170,6 @@ export class CaptchaClient { /** Emit one sanitized event. Logger failures never change the SDK operation result. */ private _emitDebug(event: string, details: Record = {}, level: DebugLevel = 'debug', context: DebugContext = {}): void { if (!this.debug) return; - if (this.debug !== 'trace' && TRACE_ONLY_EVENTS.has(event)) return; const record = this._sanitizeForDebug({ timestamp: new Date().toISOString(), level, event, ...context, ...details }) as DebugEvent; try { this.logger(record); } catch { /* Diagnostics must not break API calls. */ } } @@ -242,7 +223,7 @@ export class CaptchaClient { try { data = JSON.parse(rawBody) as typeof data; } catch (parseError) { - this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, durationMs: Math.round(performance.now() - startedAt), body: rawBody }, 'error', requestContext); + this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: rawBody }, 'error', requestContext); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`, parseError); throw new NetworkError(`Invalid JSON response from ${endpoint}`, parseError); } @@ -251,7 +232,7 @@ export class CaptchaClient { data = await response.json() as typeof data; } const responseLevel: DebugLevel = !response.ok || !data || data.errorId !== 0 ? 'error' : 'debug'; - this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, durationMs: Math.round(performance.now() - startedAt), body: data }, responseLevel, requestContext); + this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: data }, responseLevel, requestContext); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); if (!data || typeof data !== 'object') throw new NetworkError(`Invalid JSON response from ${endpoint}`); if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); diff --git a/src/index.ts b/src/index.ts index 475c303..b143875 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ export { CaptchaClient } from './client.js'; -export type { CaptchaClientOptions, DebugEvent, DebugLevel, DebugLogger, DebugMode, TaskResult, SolutionOf } from './client.js'; +export type { CaptchaClientOptions, DebugEvent, DebugLevel, DebugLogger, TaskResult, SolutionOf } from './client.js'; export { ApiError, NetworkError, TimeoutError, ValidationError, CaptchaError } from './exceptions.js'; export * as Tasks from './tasks.js'; export type { diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 5783043..bada887 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -41,7 +41,7 @@ describe('CaptchaClient (async)', () => { test('debug logger receives timestamped and sanitized structured events', async () => { const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: 'trace', logger: (event) => events.push(event) }); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); await client.getBalance(); @@ -55,16 +55,6 @@ describe('CaptchaClient (async)', () => { expect(JSON.stringify(events)).not.toContain('secret_key'); }); - test('concise debug omits trace-only lifecycle events', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); - - await client.getBalance(); - - expect(events.map(({ event }) => event)).toEqual(['server.request', 'server.response']); - }); - test('solve correlates events and counts processing result requests', async () => { const events = []; client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); From b239ffc09ebc932018bba4dd62e65e731c1ebf45 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:39:21 +0300 Subject: [PATCH 18/31] Revert "docs: enable debug directly in Kaleidoscope example" This reverts commit c7657e381ba7f09d0a4670f3ef6da151f616eb18. --- examples/yandex_smartcaptcha_kaleidoscope.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 4f5bcbd..699f3c2 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -22,7 +22,7 @@ if (!process.env.CAPTCHA_API_KEY) { // STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY, - debug: true + debug: process.env.CAPTCHA_DEBUG === '1' }); const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) From f2d28934e0bd766efc0be1dd5723ca53988685f6 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:39:21 +0300 Subject: [PATCH 19/31] Revert "feat: harden structured debug logging" This reverts commit 9901b817d78724e3b58da2fe288ec4cc74d6b200. --- CHANGELOG.md | 13 - README.md | 26 +- examples/yandex_smartcaptcha_kaleidoscope.js | 2 +- src/client.ts | 208 +++++---------- src/index.ts | 2 +- tests/unit/async/client.test.js | 254 ++++++++++--------- 6 files changed, 201 insertions(+), 304 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96a4601..9a7bf6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,19 +2,6 @@ All notable changes are documented here. -## Unreleased - -### Added - -- add structured debug logging with timestamps, severity, correlation IDs, sanitized HTTP exchanges, request counts, and solve summaries -- add a debug logger callback for forwarding events to application loggers or files - -### Fixed - -- enforce the overall solve timeout across task creation, polling delays, and result requests -- preserve non-JSON server response bodies in debug events -- redact credentials, tokens, URL secrets, and binary CAPTCHA data from debug output - ## [1.1.0] - 2026-11-03 ### Added diff --git a/README.md b/README.md index ac47c9b..b5bd24b 100644 --- a/README.md +++ b/README.md @@ -681,12 +681,13 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print structured request, response, and polling lifecycle events. -Every event includes an ISO timestamp, severity level, event name, and correlation IDs. -Debug output includes the HTTP method and URL, sanitized request body, response status -and body, task IDs, and task statuses. At the end of `solve()`, a summary reports the -outcome or failure reason, total elapsed time, and request counts. Credential and token -fields are redacted; binary data and other long strings are omitted or truncated. +Enable `debug` to print request, response, and polling lifecycle events. Debug output +includes the HTTP method and URL, request body, response status and body, task IDs, +and task statuses. At the end of `solve()`, a summary reports whether the CAPTCHA was +solved, its task ID, total elapsed time in readable seconds and exact milliseconds, +and the number of `/getTaskResult` requests. Credential +fields are replaced with `[REDACTED]`; long strings such as base64 images and solution +tokens are truncated to keep the output readable. Server exchanges are printed as single labelled JSON blocks, so the response body always remains visually attached to `[CaptchaClient] server response` in the console. @@ -699,19 +700,6 @@ const captchaSolver = new CaptchaClient({ }); ``` -Pass `logger` to receive the same structured events without writing to the console. -The callback can forward events to a file or an application logger; the SDK never -creates log files on its own: - -```javascript -const events = []; -const captchaSolver = new CaptchaClient({ - clientKey: 'your_api_key', - debug: true, - logger: (event) => events.push(event) -}); -``` - ### Worker language pool Pass `languagePool` as the second argument to `solve()` (or `createTask()`) to pick a diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 699f3c2..4f5bcbd 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -22,7 +22,7 @@ if (!process.env.CAPTCHA_API_KEY) { // STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY, - debug: process.env.CAPTCHA_DEBUG === '1' + debug: true }); const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) diff --git a/src/client.ts b/src/client.ts index d558e2e..9dce0aa 100644 --- a/src/client.ts +++ b/src/client.ts @@ -3,27 +3,7 @@ import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; const MAX_DEBUG_STRING_LENGTH = 200; -let operationSequence = 0; - -interface DebugContext { - solveId?: string; - requestId?: string; - taskId?: number; -} - -/** Severity assigned to a structured debug event. */ -export type DebugLevel = 'debug' | 'info' | 'error'; - -/** One structured event emitted while debug mode is enabled. */ -export interface DebugEvent extends DebugContext { - timestamp: string; - level: DebugLevel; - event: string; - [key: string]: unknown; -} - -/** Receives structured debug events. Use this to integrate a logger or file stream. */ -export type DebugLogger = (event: DebugEvent) => void; +const REDACTED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyLogin|proxyPassword)$/i; /** Options accepted by the {@link CaptchaClient} constructor. */ export interface CaptchaClientOptions { @@ -54,11 +34,6 @@ export interface CaptchaClientOptions { * @defaultValue `false` */ debug?: boolean; - /** - * Optional structured event receiver used instead of the default console renderer. - * Only called when {@link debug} is `true`. - */ - logger?: DebugLogger; } /** Raw response of `/getTaskResult` (and, structurally, of every other API endpoint). */ @@ -109,45 +84,26 @@ export class CaptchaClient { pollingInterval: number; /** Whether lifecycle debug logging is enabled. */ debug: boolean; - /** Structured debug event receiver. */ - logger: DebugLogger; /** * @param options - Client options; only `clientKey` is required. * @throws {ValidationError} If `clientKey` is empty. */ - constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false, logger }: CaptchaClientOptions = {} as CaptchaClientOptions) { + constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false }: CaptchaClientOptions = {} as CaptchaClientOptions) { if (!clientKey) throw new ValidationError('clientKey is required'); this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; this.debug = debug; - this.logger = logger ?? ((event) => this._writeDebugToConsole(event)); - this._emitDebug('client.initialized', { baseUrl, timeout, pollingInterval }, 'info'); + this._debug('client initialized', { baseUrl, timeout, pollingInterval }); } /** * Copy a value for debug output while keeping logs readable and safe to share. - * Credentials and tokens are redacted, binary data is omitted, and other - * long strings retain short edges plus their original length. + * Credential fields are removed completely; long strings retain their edges + * and original length so base64 images and tokens can still be identified. */ private _sanitizeForDebug(value: unknown, fieldName?: string): unknown { - const normalizedField = fieldName?.replace(/[^a-z0-9]/gi, '').toLowerCase(); - if (normalizedField && /(authorization|clientkey|apikey|cookie|password|proxylogin|secret)/.test(normalizedField)) return '[REDACTED]'; - if (normalizedField && /(accesstoken|refreshtoken|^token$|grecaptcharesponse)/.test(normalizedField)) { - return typeof value === 'string' ? `[REDACTED token; original length: ${value.length}]` : '[REDACTED token]'; - } - if (normalizedField && /(body|image|imginstructions|pagedata)/.test(normalizedField) && typeof value === 'string' && value.length > MAX_DEBUG_STRING_LENGTH) { - return `[OMITTED binary data; original length: ${value.length}]`; - } - if (normalizedField?.endsWith('url') && typeof value === 'string') { - try { - const url = new URL(value); - for (const key of url.searchParams.keys()) { - if (/(key|token|secret|password|authorization)/i.test(key)) url.searchParams.set(key, '[REDACTED]'); - } - return url.toString(); - } catch { /* Keep non-standard URL placeholders unchanged. */ } - } + if (fieldName && REDACTED_DEBUG_FIELDS.test(fieldName)) return '[REDACTED]'; if (typeof value === 'string' && value.length > MAX_DEBUG_STRING_LENGTH) { - const edgeLength = 32; + const edgeLength = Math.floor(MAX_DEBUG_STRING_LENGTH / 2); return `${value.slice(0, edgeLength)}...[truncated; original length: ${value.length}]...${value.slice(-edgeLength)}`; } if (Array.isArray(value)) return value.map((item) => this._sanitizeForDebug(item)); @@ -159,38 +115,18 @@ export class CaptchaClient { return value; } - /** Render one structured event for users who did not supply a logger callback. */ - private _writeDebugToConsole(event: DebugEvent): void { - const output = `[CaptchaClient] ${event.event}:\n${JSON.stringify(event, null, 2)}`; - if (event.level === 'error') console.error(output); - else if (event.level === 'info') console.info(output); - else console.debug(output); - } - - /** Emit one sanitized event. Logger failures never change the SDK operation result. */ - private _emitDebug(event: string, details: Record = {}, level: DebugLevel = 'debug', context: DebugContext = {}): void { + /** Write one debug event after sanitizing every supplied field. */ + private _debug(message: string, details?: Record): void { if (!this.debug) return; - const record = this._sanitizeForDebug({ timestamp: new Date().toISOString(), level, event, ...context, ...details }) as DebugEvent; - try { this.logger(record); } catch { /* Diagnostics must not break API calls. */ } - } - - private _newOperationId(prefix: 'solve' | 'request'): string { - operationSequence += 1; - return `${prefix}-${Date.now().toString(36)}-${operationSequence.toString(36)}`; - } - - private _errorDetails(error: unknown): Record { - if (!(error instanceof Error)) return { errorName: 'UnknownError', errorMessage: String(error) }; - const details: Record = { errorName: error.name, errorMessage: error.message }; - if (error instanceof ApiError) { details.errorCode = error.errorCode; details.errorDescription = error.errorDescription; } - return details; + if (details) console.debug(`[CaptchaClient] ${message}`, this._sanitizeForDebug(details)); + else console.debug(`[CaptchaClient] ${message}`); } - private _failureReason(error: unknown): string { - if (error instanceof TimeoutError) return 'timeout'; - if (error instanceof ApiError) return 'api_error'; - if (error instanceof NetworkError) return 'network_error'; - return 'unknown_error'; + /** Print an HTTP exchange as one labelled JSON block instead of an ambiguous console object. */ + private _debugServerExchange(message: 'server request' | 'server response', details: Record): void { + if (!this.debug) return; + const json = JSON.stringify(this._sanitizeForDebug(details), null, 2); + console.debug(`[CaptchaClient] ${message}:\n${json}`); } /** @@ -206,46 +142,34 @@ export class CaptchaClient { * @throws {NetworkError} On a non-2xx HTTP status or any transport failure. * @internal */ - protected async _request(endpoint: string, payload: Record, context: DebugContext = {}, requestTimeout = this.timeout): Promise { - const effectiveTimeout = Math.max(1, Math.ceil(requestTimeout)); - const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), effectiveTimeout); - const startedAt = performance.now(); + protected async _request(endpoint: string, payload: Record): Promise { + const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); + const startedAt = Date.now(); const url = `${this.baseUrl}${endpoint}`; const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; - const requestContext = { ...context, requestId: this._newOperationId('request') }; - this._emitDebug('request.started', { endpoint, timeoutMs: effectiveTimeout }, 'debug', requestContext); - this._emitDebug('server.request', { method: 'POST', url, headers, body: payload }, 'debug', requestContext); + this._debug('request started', { endpoint }); + this._debugServerExchange('server request', { method: 'POST', url, headers, body: payload }); try { const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); let data: TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; - if (typeof response.text === 'function') { - const rawBody = await response.text(); - try { - data = JSON.parse(rawBody) as typeof data; - } catch (parseError) { - this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: rawBody }, 'error', requestContext); - if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`, parseError); - throw new NetworkError(`Invalid JSON response from ${endpoint}`, parseError); - } - } else { - // The fallback keeps custom fetch implementations and lightweight test doubles compatible. + try { data = await response.json() as typeof data; + } catch (parseError) { + this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: '[unavailable: invalid JSON]' }); + if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); + throw parseError; } - const responseLevel: DebugLevel = !response.ok || !data || data.errorId !== 0 ? 'error' : 'debug'; - this._emitDebug('server.response', { endpoint, status: response.status, statusText: response.statusText, body: data }, responseLevel, requestContext); + // Log the server payload first; lifecycle messages below explain how the SDK interpreted it. + this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: data }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); - if (!data || typeof data !== 'object') throw new NetworkError(`Invalid JSON response from ${endpoint}`); if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); - this._emitDebug('request.completed', { endpoint, status: response.status, durationMs: Math.round(performance.now() - startedAt) }, 'debug', requestContext); + this._debug('request completed', { endpoint, status: response.status, durationMs: Date.now() - startedAt }); return data; } catch (error) { - const normalizedError = error && typeof error === 'object' && 'name' in error && error.name === 'AbortError' - ? new TimeoutError(`Request timed out after ${effectiveTimeout}ms`) - : error instanceof ApiError || error instanceof NetworkError - ? error - : new NetworkError(error instanceof Error ? error.message : String(error), error); - this._emitDebug('request.failed', { endpoint, durationMs: Math.round(performance.now() - startedAt), ...this._errorDetails(normalizedError) }, 'error', requestContext); - throw normalizedError; + this._debug('request failed', { endpoint, error: error instanceof Error ? error.name : 'UnknownError', durationMs: Date.now() - startedAt }); + if (error instanceof ApiError || error instanceof NetworkError) throw error; + if (error && typeof error === 'object' && 'name' in error && error.name === 'AbortError') throw new TimeoutError(`Request timed out after ${this.timeout}ms`); + throw new NetworkError(error instanceof Error ? error.message : String(error), error); } finally { clearTimeout(timer); } } @@ -269,16 +193,12 @@ export class CaptchaClient { * ``` */ async createTask(task: BaseTask, languagePool: string | null = null): Promise { - return this._createTask(task, languagePool, { solveId: this._newOperationId('solve') }, this.timeout); - } - - private async _createTask(task: BaseTask, languagePool: string | null, context: DebugContext, requestTimeout: number): Promise { const taskPayload = task.toDict(); const taskType = typeof taskPayload.type === 'string' ? taskPayload.type : task.constructor.name; - this._emitDebug('task.submission.started', { taskType, languagePool }, 'debug', context); + this._debug('task submission started', { taskType, languagePool }); const payload: Record = { clientKey: this.clientKey, task: taskPayload }; if (languagePool !== null) payload.languagePool = languagePool; - const taskId = (await this._request('/createTask', payload, context, requestTimeout)).taskId as number; - this._emitDebug('task.created', { taskType }, 'info', { ...context, taskId }); + const taskId = (await this._request('/createTask', payload)).taskId as number; + this._debug('task created', { taskId, taskType }); return taskId; } @@ -300,7 +220,7 @@ export class CaptchaClient { * .catch(console.error); * ``` */ - getTaskResult(taskId: number): Promise { return this._request('/getTaskResult', { clientKey: this.clientKey, taskId }, { taskId }); } + getTaskResult(taskId: number): Promise { return this._request('/getTaskResult', { clientKey: this.clientKey, taskId }); } /** * Get the account balance. @@ -338,58 +258,46 @@ export class CaptchaClient { * ``` */ async solve>(task: T, languagePool: string | null = null): Promise> { - const startedAt = performance.now(); - const solveId = this._newOperationId('solve'); + const taskType = task.constructor.name; + const startedAt = Date.now(); let taskId: number | null = null; let resultRequestCount = 0; - let totalRequestCount = 0; - this._emitDebug('solve.started', { taskClass: task.constructor.name, timeoutMs: this.timeout }, 'info', { solveId }); + this._debug('solve started', { taskType }); try { - // Validate and serialize before counting the createTask HTTP attempt. - task.toDict(); - const remainingForCreate = this.timeout - (performance.now() - startedAt); - if (remainingForCreate <= 0) throw new TimeoutError(`Task creation timed out after ${this.timeout}ms`); - totalRequestCount += 1; - taskId = await this._createTask(task, languagePool, { solveId }, remainingForCreate); + taskId = await this.createTask(task, languagePool); let pollAttempt = 0; while (true) { - const remaining = this.timeout - (performance.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); const delayMs = Math.min(this.pollingInterval, remaining); pollAttempt += 1; - this._emitDebug('poll.waiting', { pollAttempt, delayMs }, 'debug', { solveId, taskId }); + this._debug('waiting before poll', { taskId, pollAttempt, delayMs }); await new Promise(resolve => setTimeout(resolve, delayMs)); - const remainingForResult = this.timeout - (performance.now() - startedAt); - if (remainingForResult <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); resultRequestCount += 1; - totalRequestCount += 1; - const result = await this._request('/getTaskResult', { clientKey: this.clientKey, taskId }, { solveId, taskId }, remainingForResult); - const elapsedMs = Math.round(performance.now() - startedAt); - this._emitDebug('task.status.received', { pollAttempt, status: result.status, elapsedMs }, 'debug', { solveId, taskId }); + const result = await this.getTaskResult(taskId); + const elapsedMs = Date.now() - startedAt; + this._debug('task status received', { taskId, pollAttempt, status: result.status, elapsedMs }); if (result.status === 'ready') { - this._emitDebug('task.solved', { pollAttempts: pollAttempt, elapsedMs }, 'info', { solveId, taskId }); - this._emitDebug('solve.summary', { + this._debug('task solved', { taskId, pollAttempts: pollAttempt, elapsedMs }); + this._debug('solve summary', { status: 'solved', + captchaId: taskId, elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, elapsedMs, - createTaskRequestCount: 1, - resultRequestCount, - totalRequestCount - }, 'info', { solveId, taskId }); + resultRequestCount + }); return (result.solution ?? {}) as SolutionOf; } } } catch (error) { - const elapsedMs = Math.round(performance.now() - startedAt); - this._emitDebug('solve.summary', { - status: 'not_solved', - reason: this._failureReason(error), + const elapsedMs = Date.now() - startedAt; + this._debug('solve summary', { + status: 'not solved', + captchaId: taskId, elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, elapsedMs, - createTaskRequestCount: totalRequestCount > 0 ? 1 : 0, - resultRequestCount, - totalRequestCount, - ...this._errorDetails(error) - }, 'error', { solveId, ...(taskId === null ? {} : { taskId }) }); + resultRequestCount + }); throw error; } } diff --git a/src/index.ts b/src/index.ts index b143875..6cea1fb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ export { CaptchaClient } from './client.js'; -export type { CaptchaClientOptions, DebugEvent, DebugLevel, DebugLogger, TaskResult, SolutionOf } from './client.js'; +export type { CaptchaClientOptions, TaskResult, SolutionOf } from './client.js'; export { ApiError, NetworkError, TimeoutError, ValidationError, CaptchaError } from './exceptions.js'; export * as Tasks from './tasks.js'; export type { diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index bada887..c662039 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -39,158 +39,172 @@ describe('CaptchaClient (async)', () => { expect(requestOptions.headers['X-SDK']).toBe('javascript-sdk/1.1.0'); }); - test('debug logger receives timestamped and sanitized structured events', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); + test('debug mode logs sanitized request lifecycle events', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) + })); await client.getBalance(); - expect(events.map(({ event }) => event)).toEqual([ - 'client.initialized', 'request.started', 'server.request', 'server.response', 'request.completed' - ]); - expect(events.every(({ timestamp }) => !Number.isNaN(Date.parse(timestamp)))).toBe(true); - expect(events.find(({ event }) => event === 'server.request').body.clientKey).toBe('[REDACTED]'); - expect(events.find(({ event }) => event === 'server.response')).toMatchObject({ level: 'debug', status: 200, body: { balance: '1.00' } }); - expect(JSON.stringify(events)).not.toContain('secret_key'); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] request started', { endpoint: '/getBalance' }); + const requestLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server request:'))?.[0]; + expect(requestLog).toContain('"url": "https://api.captcha-solver.com/getBalance"'); + expect(requestLog).toContain('"clientKey": "[REDACTED]"'); + const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; + expect(responseLog).toContain('"endpoint": "/getBalance"'); + expect(responseLog).toContain('"status": 200'); + expect(responseLog).toContain('"balance": "1.00"'); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] client initialized', { + baseUrl: 'https://api.captcha-solver.com', + timeout: 120000, + pollingInterval: 5000 + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] request completed', { + endpoint: '/getBalance', + status: 200, + durationMs: expect.any(Number) + }); + const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); + const completedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request completed'); + expect(responseLogIndex).toBeLessThan(completedLogIndex); + expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); + debug.mockRestore(); }); - test('solve correlates events and counts processing result requests', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); + test('debug mode logs task type, task ID, and polling progress', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); global.fetch = jest.fn() - .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) })) - .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, status: 'processing' }) })) - .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: 'secret_solution' } }) })); - const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) + })) + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: `start-${'x'.repeat(300)}-end` } }) + })); + const task = new Tasks.RecaptchaV2Proxyless({ + websiteURL: 'https://example.com', + websiteKey: 'website_key' + }); await client.solve(task); - const solveEvents = events.filter(({ solveId }) => solveId); - expect(new Set(solveEvents.map(({ solveId }) => solveId)).size).toBe(1); - expect(events.find(({ event }) => event === 'task.created')).toMatchObject({ taskId: 12345, taskType: 'RecaptchaV2TaskProxyless' }); - expect(events.find(({ event }) => event === 'solve.summary')).toMatchObject({ - level: 'info', status: 'solved', taskId: 12345, createTaskRequestCount: 1, resultRequestCount: 2, totalRequestCount: 3 + expect(debug).toHaveBeenCalledWith('[CaptchaClient] task created', { + taskId: 12345, + taskType: 'RecaptchaV2TaskProxyless' + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] task status received', { + taskId: 12345, + pollAttempt: 1, + status: 'ready', + elapsedMs: expect.any(Number) + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] task solved', { + taskId: 12345, + pollAttempts: 1, + elapsedMs: expect.any(Number) + }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { + status: 'solved', + captchaId: 12345, + elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), + elapsedMs: expect.any(Number), + resultRequestCount: 1 }); - expect(JSON.stringify(events)).toContain('[REDACTED token; original length: 15]'); - expect(JSON.stringify(events)).not.toContain('secret_solution'); + const logged = JSON.stringify(debug.mock.calls); + expect(logged).toContain('website_key'); + expect(logged).toContain('original length: 310'); + expect(logged).not.toContain(`start-${'x'.repeat(300)}-end`); + expect(logged).not.toContain('secret_key'); + const resultResponseLogIndex = debug.mock.calls.findIndex(([message, details]) => + message.startsWith('[CaptchaClient] server response:') && message.includes('"endpoint": "/getTaskResult"') + ); + const resultCompletedLogIndex = debug.mock.calls.findIndex(([message, details]) => + message === '[CaptchaClient] request completed' && details.endpoint === '/getTaskResult' + ); + const statusLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] task status received'); + expect(resultResponseLogIndex).toBeLessThan(resultCompletedLogIndex); + expect(resultCompletedLogIndex).toBeLessThan(statusLogIndex); + debug.mockRestore(); }); test('debug mode is silent by default', async () => { const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); + global.fetch = jest.fn(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) + })); + await client.getBalance(); + expect(debug).not.toHaveBeenCalled(); debug.mockRestore(); }); - test('solve summary explains API failures', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); + test('debug mode logs a not-solved summary after a result request fails', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); global.fetch = jest.fn() - .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) })) - .mockImplementationOnce(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' }) })); - const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); - - await expect(client.solve(task)).rejects.toThrow(ApiError); - - expect(events.find(({ event }) => event === 'solve.summary')).toMatchObject({ - level: 'error', status: 'not_solved', reason: 'api_error', taskId: 12345, - errorName: 'ApiError', errorCode: 'ERROR_TASK_FAILED', resultRequestCount: 1, totalRequestCount: 2 - }); - }); - - test('debug logger preserves a non-JSON server error body', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); - global.fetch = jest.fn(() => Promise.resolve({ ok: false, status: 502, statusText: 'Bad Gateway', text: () => Promise.resolve('upstream failed') })); - - await expect(client.getBalance()).rejects.toThrow(NetworkError); - - expect(events.find(({ event }) => event === 'server.response')).toMatchObject({ - level: 'error', status: 502, body: 'upstream failed' + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) + })) + .mockImplementationOnce(() => Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' }) + })); + const task = new Tasks.RecaptchaV2Proxyless({ + websiteURL: 'https://example.com', + websiteKey: 'website_key' }); - }); - test('logger failures do not change the SDK result', async () => { - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: () => { throw new Error('logger failed'); } }); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) })); - await expect(client.getBalance()).resolves.toBe(1); - }); + await expect(client.solve(task)).rejects.toThrow(ApiError); - test('parallel solves use different correlation IDs', async () => { - const events = []; - let nextTaskId = 100; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), pollingInterval: 1 }); - global.fetch = jest.fn((url, options) => { - const body = JSON.parse(options.body); - const response = url.endsWith('/createTask') - ? { errorId: 0, taskId: nextTaskId++ } - : { errorId: 0, status: 'ready', solution: { token: `token-${body.taskId}` } }; - return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(response) }); + expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { + status: 'not solved', + captchaId: 12345, + elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), + elapsedMs: expect.any(Number), + resultRequestCount: 1 }); - const task = () => new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); - - await Promise.all([client.solve(task()), client.solve(task())]); - - const summaries = events.filter(({ event }) => event === 'solve.summary'); - expect(summaries).toHaveLength(2); - expect(new Set(summaries.map(({ solveId }) => solveId)).size).toBe(2); - expect(new Set(summaries.map(({ taskId }) => taskId))).toEqual(new Set([100, 101])); + debug.mockRestore(); }); - test('createTask failure summary has no task ID and explains the error', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); + test('debug mode logs the original API error response before throwing', async () => { + const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + const errorBody = { + errorId: 1, + errorCode: 'ERROR_KEY_DOES_NOT_EXIST', + errorDescription: 'Account not found' + }; global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, - json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_ZERO_BALANCE', errorDescription: 'No funds' }) + statusText: 'OK', + json: () => Promise.resolve(errorBody) })); - const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); - - await expect(client.solve(task)).rejects.toThrow(ApiError); - const summary = events.find(({ event }) => event === 'solve.summary'); - expect(summary).toMatchObject({ reason: 'api_error', createTaskRequestCount: 1, resultRequestCount: 0, totalRequestCount: 1 }); - expect(summary).not.toHaveProperty('taskId'); - }); - - test('debug sanitization omits binary data and redacts URL secrets', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event) }); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) })); - const task = new Tasks.ImageToText({ body: 'a'.repeat(500), comment: 'test' }); + await expect(client.getBalance()).rejects.toThrow(ApiError); - await client.createTask(task); - await client.createTask(new Tasks.RecaptchaV2Proxyless({ - websiteURL: 'https://example.com/login?access_token=url-secret', - websiteKey: 'website_key' - })); - - const requests = events.filter(({ event }) => event === 'server.request'); - expect(requests[0].body.task.body).toBe('[OMITTED binary data; original length: 500]'); - expect(requests[1].body.task.websiteURL).not.toContain('url-secret'); - expect(JSON.stringify(events)).not.toContain('a'.repeat(200)); - }); - - test('solve timeout is a deadline for the complete operation', async () => { - const events = []; - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, logger: (event) => events.push(event), timeout: 300, pollingInterval: 0 }); - global.fetch = jest.fn() - .mockImplementationOnce(() => new Promise((resolve) => setTimeout(() => resolve({ - ok: true, status: 200, json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) - }), 100))) - .mockImplementationOnce((url, options) => new Promise((resolve, reject) => { - options.signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))); - })); - const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); - const startedAt = performance.now(); - - await expect(client.solve(task)).rejects.toThrow(TimeoutError); - - expect(performance.now() - startedAt).toBeLessThan(380); - expect(events.find(({ event }) => event === 'solve.summary')).toMatchObject({ reason: 'timeout', totalRequestCount: 2 }); + const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; + expect(responseLog).toContain('"endpoint": "/getBalance"'); + expect(responseLog).toContain('"errorCode": "ERROR_KEY_DOES_NOT_EXIST"'); + expect(responseLog).toContain('"errorDescription": "Account not found"'); + const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); + const failedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request failed'); + expect(responseLogIndex).toBeLessThan(failedLogIndex); + debug.mockRestore(); }); test('aborts an HTTP request after timeout', async () => { From 2b777a987666a175f7573c2bc4a2811a67254188 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Thu, 12 Nov 2026 18:58:12 +0300 Subject: [PATCH 20/31] docs: align README with current SDK --- README.md | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index b5bd24b..1997b9f 100644 --- a/README.md +++ b/README.md @@ -164,8 +164,9 @@ Constructor. Takes a single options object. |---|---|---|---| | `clientKey` | `string` | required | Your Captcha Solver API key. Throws `ValidationError` if empty. | | `baseUrl` | `string` | `https://api.captcha-solver.com` | API base URL. Override only for self-hosted/staging deployments. | -| `timeout` | `number` | `120000` | Default max milliseconds `solve()` waits for a solution before throwing `TimeoutError`. | +| `timeout` | `number` | `120000` | Per-request HTTP timeout and polling time budget used by `solve()`. | | `pollingInterval` | `number` | `5000` | Milliseconds between `getTaskResult` polls inside `solve()`. | +| `debug` | `boolean` | `false` | Print sanitized request, response, polling, and final solve diagnostics to the console. | There's no manual connection pool to open or close -- `fetch` (via Node's built-in `undici`) already reuses keep-alive connections per host automatically, unlike Python's @@ -181,8 +182,9 @@ solution -- wraps `createTask()` + `getTaskResult()` so you don't poll by hand. | `task` | task object | One of the classes from `Tasks` (see [Captcha Types](#captcha-types)). | | `languagePool` | `string \| null` | Optional worker pool selector, `'en'` or `'ru'`. Defaults to `null` (account default pool). | -Returns a `Promise` resolving to the `solution` object once `status` is `'ready'` -- -its shape depends on the task type (see [Captcha Types](#captcha-types)). +Returns a `Promise` resolving to the task-specific `solution` value once `status` is +`'ready'`. Most tasks return an object; Yandex SmartCaptcha Kaleidoscope returns a +string. See [Captcha Types](#captcha-types) for each result format. Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. ### `createTask(task, languagePool)` @@ -190,19 +192,20 @@ Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. Submits `task` and returns a `Promise` resolving to its numeric task ID, without waiting for a solution. Same parameters as `solve()`. Use this instead of `solve()` only if you need to manage polling yourself (e.g. checking on many tasks from a -different process). Rejects with `ApiError`, `NetworkError`. +different process). Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. ### `getTaskResult(taskId)` Fetches the current status of a task created with `createTask()`. Resolves to an -object with a `status` key (`'processing'` or `'ready'`); when `'ready'`, also has a -`solution` object. This is a single poll, not a wait -- call it repeatedly (as -`solve()` does) until `status` is `'ready'`. Rejects with `ApiError`, `NetworkError`. +response with a `status` key (`'processing'` or `'ready'`); when `'ready'`, it also +has a task-specific `solution` value. This is a single poll, not a wait -- call it +repeatedly (as `solve()` does) until `status` is `'ready'`. Rejects with `ApiError`, +`TimeoutError`, or `NetworkError`. ### `getBalance()` Returns a `Promise` resolving to the account's current balance (`number`) in the -account's currency. Rejects with `ApiError`, `NetworkError`. +account's currency. Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. ## Captcha Types @@ -779,9 +782,12 @@ matches this README. ## Running the examples -- **Image/click captchas** (`image_to_text.js`, `coordinates.js`) run end-to-end +- **Image/click captchas** (`image_to_text.js`, `image_to_text_math.js`, + `image_to_text_language_pool.js`, `coordinates.js`, `coordinates_traffic_lights.js`, + `yandex_smartcaptcha_image.js`, `yandex_smartcaptcha_kaleidoscope.js`) run end-to-end with nothing but a valid `CAPTCHA_API_KEY` -- they read sample images bundled in [examples/assets](examples/assets), no target page needed. +- **Token captchas** (`recaptcha_v2.js`, `recaptcha_v2_enterprise.js`, `recaptcha_v3.js`, `turnstile.js`, `yandex_smartcaptcha.js`, `geetest_v4.js`, `tencent.js`) use placeholder values (`https://example.com/...`, `YOUR_WEBSITE_KEY`, `YOUR_APP_ID`, `YOUR_CAPTCHA_ID`) -- replace these with the real values from your own target @@ -809,7 +815,7 @@ covers live in [examples/README.md](examples/README.md). ## Requirements -- Node.js 18 or newer. Modern browser with fetch support. +- Node.js 18 or newer. The repository examples also rely on Node.js APIs and `dotenv`. - Captcha Solver account with a valid API key. ## API Documentation From 88893ef6f8c9578c22a1f89617b9b8049008ecbb Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 00:22:06 +0300 Subject: [PATCH 21/31] feat: compact timestamped debug output - prefix every debug line with local time, milliseconds and UTC offset - one line per API request; REQUEST (POST ) and RESPONSE (HTTP ...) blocks for task creation, balance, errors and ready results only - mask credentials as [MASKED], replace base64 images with their length - log the error the caller receives, including fetch failure causes - print SOLVE SUMMARY line by line with serverSolveTime and error Co-Authored-By: Claude Opus 5.5 --- README.md | 77 +++++++-- src/client.ts | 227 ++++++++++++++++++-------- tests/unit/async/client.test.js | 273 +++++++++++++++----------------- 3 files changed, 349 insertions(+), 228 deletions(-) diff --git a/README.md b/README.md index 1997b9f..f154c03 100644 --- a/README.md +++ b/README.md @@ -166,7 +166,7 @@ Constructor. Takes a single options object. | `baseUrl` | `string` | `https://api.captcha-solver.com` | API base URL. Override only for self-hosted/staging deployments. | | `timeout` | `number` | `120000` | Per-request HTTP timeout and polling time budget used by `solve()`. | | `pollingInterval` | `number` | `5000` | Milliseconds between `getTaskResult` polls inside `solve()`. | -| `debug` | `boolean` | `false` | Print sanitized request, response, polling, and final solve diagnostics to the console. | +| `debug` | `boolean` | `false` | Print timestamped, sanitized request and `solve()` diagnostics with `console.debug`. See [Debug mode](#debug-mode). | There's no manual connection pool to open or close -- `fetch` (via Node's built-in `undici`) already reuses keep-alive connections per host automatically, unlike Python's @@ -196,7 +196,7 @@ different process). Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. ### `getTaskResult(taskId)` -Fetches the current status of a task created with `createTask()`. Resolves to an +Fetches the current status of a task created with `createTask()`. Resolves to the API response with a `status` key (`'processing'` or `'ready'`); when `'ready'`, it also has a task-specific `solution` value. This is a single poll, not a wait -- call it repeatedly (as `solve()` does) until `status` is `'ready'`. Rejects with `ApiError`, @@ -684,25 +684,76 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print request, response, and polling lifecycle events. Debug output -includes the HTTP method and URL, request body, response status and body, task IDs, -and task statuses. At the end of `solve()`, a summary reports whether the CAPTCHA was -solved, its task ID, total elapsed time in readable seconds and exact milliseconds, -and the number of `/getTaskResult` requests. Credential -fields are replaced with `[REDACTED]`; long strings such as base64 images and solution -tokens are truncated to keep the output readable. - -Server exchanges are printed as single labelled JSON blocks, so the response body -always remains visually attached to `[CaptchaClient] server response` in the console. +Enable `debug` to print one `console.debug` line per API request and a summary at the +end of `solve()`. Every line starts with the local time, milliseconds and UTC offset, +so the output can be matched against your application and server logs. ```javascript -// Create a client with detailed, sanitized lifecycle logging enabled. +// Create a client with sanitized debug logging enabled. const captchaSolver = new CaptchaClient({ clientKey: 'your_api_key', debug: true }); ``` +Example output of `solve()`: + +```text +[2026-11-12 14:03:12.879 +03:00] [CaptchaClient] client initialized sdk=javascript-sdk/1.1.0 baseUrl=https://api.captcha-solver.com timeout=120000ms pollingInterval=5000ms +[2026-11-12 14:03:17.204 +03:00] [CaptchaClient] createTask PazlCaptchaTask -> taskId=3668 (4325ms) +REQUEST (POST https://api.captcha-solver.com/createTask): +{ + "clientKey": "[MASKED]", + "task": { + "type": "PazlCaptchaTask", + "image": "[base64, 142668 chars]", + "task": "[7,15,14,0,11,6,6,0]" + } +} +RESPONSE (HTTP 200 OK): +{ + "errorId": 0, + "taskId": 3668 +} +[2026-11-12 14:03:23.430 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> processing (1226ms) +[2026-11-12 14:03:29.170 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> ready (740ms) +REQUEST (POST https://api.captcha-solver.com/getTaskResult): +{ + "clientKey": "[MASKED]", + "taskId": 3668 +} +RESPONSE (HTTP 200 OK): +{ + "errorId": 0, + "status": "ready", + "solution": "7", + "createTime": 1794515548, + "endTime": 1794515556 +} +[2026-11-12 14:03:29.171 +03:00] [CaptchaClient] SOLVE SUMMARY: + status: solved + taskId: 3668 + taskType: PazlCaptchaTask + elapsed: 16.292s + serverSolveTime: 8s + polls: 2 +``` + +- `REQUEST (POST ):` is the endpoint URL and JSON body the SDK sent; + `RESPONSE (HTTP ...):` is the server body exactly as received. They are printed for + task creation, balance checks, errors, and the `ready` result; routine `processing` + polls stay on one line. +- Failed requests print the error the caller receives, e.g. + `getTaskResult taskId=3668 -> failed: ApiError ERROR_TASK_FAILED: ...`, followed by + `REQUEST (POST ):` and, when the server answered, `RESPONSE (HTTP ...):`. A + failed `solve()` ends with a `SOLVE SUMMARY` whose `status` is `not solved` and + which has an extra `error` line. +- `serverSolveTime` comes from the API's `createTime` / `endTime`; the difference from + `elapsed` is task creation plus waiting between polls. +- The API key and other credentials (`proxyLogin`, `proxyPassword`, `cookies`) are + replaced with `[MASKED]`, base64 images with their length, and other long strings + such as solution tokens are shortened. The output is safe to attach to bug reports. + ### Worker language pool Pass `languagePool` as the second argument to `solve()` (or `createTask()`) to pick a diff --git a/src/client.ts b/src/client.ts index 9dce0aa..ab0eab3 100644 --- a/src/client.ts +++ b/src/client.ts @@ -3,7 +3,54 @@ import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; const MAX_DEBUG_STRING_LENGTH = 200; -const REDACTED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyLogin|proxyPassword)$/i; +const DEBUG_STRING_EDGE_LENGTH = 40; +const MASKED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyLogin|proxyPassword)$/i; +/** Task fields that carry base64 images; their content is never useful in a log. */ +const BASE64_DEBUG_FIELDS = /^(body|image|imgInstructions)$/; + +/** Format a moment as local time with milliseconds and UTC offset: `2026-11-12 14:03:21.512 +03:00`. */ +function formatDebugTimestamp(date: Date): string { + const pad = (value: number, length = 2) => String(value).padStart(length, '0'); + const offsetMinutes = -date.getTimezoneOffset(); + const sign = offsetMinutes >= 0 ? '+' : '-'; + const absOffset = Math.abs(offsetMinutes); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)} ` + + `${sign}${pad(Math.floor(absOffset / 60))}:${pad(absOffset % 60)}`; +} + +/** Describe a single error: name, `code` when present (e.g. undici `UND_ERR_CONNECT_TIMEOUT`) and message. */ +function describeSingleDebugError(error: unknown): string { + if (error instanceof ApiError) return `${error.name} ${error.errorCode}: ${error.errorDescription}`; + if (error instanceof Error) { + const code = 'code' in error && typeof error.code === 'string' ? ` ${error.code}` : ''; + return `${error.name}${code}: ${error.message}`; + } + return String(error); +} + +/** + * Describe an error in one line, following `originalError` / `cause` links. + * `fetch` reports every transport failure as a bare `TypeError: fetch failed`; + * the actual reason (DNS, connect timeout, TLS) is only in its `cause`. + */ +function describeDebugError(error: unknown): string { + const parts: string[] = []; + let current: unknown = error; + for (let depth = 0; current !== undefined && current !== null && depth < 4; depth += 1) { + const description = describeSingleDebugError(current); + // NetworkError copies the message of the error it wraps; skip the duplicate link. + if (!(depth === 1 && error instanceof NetworkError && current instanceof Error && current.message === error.message)) parts.push(description); + current = current instanceof NetworkError ? current.originalError : (current as { cause?: unknown }).cause; + } + return parts.join(' <- '); +} + +/** One part of a debug event below its line: an optional title and a JSON value. */ +interface DebugSection { + title?: string; + value?: unknown; +} /** Options accepted by the {@link CaptchaClient} constructor. */ export interface CaptchaClientOptions { @@ -28,9 +75,11 @@ export interface CaptchaClientOptions { */ pollingInterval?: number; /** - * Print request and polling lifecycle events to `console.debug`. - * Request and response bodies are included after credentials are redacted - * and long strings such as base64 images and solution tokens are truncated. + * Print one timestamped `console.debug` line per API request plus a final + * {@link CaptchaClient.solve} summary. Request and response bodies are added + * for task creation, errors and solved tasks; routine `processing` polls stay + * on one line. Credentials are masked, base64 images are replaced by their + * length and other long strings such as solution tokens are shortened. * @defaultValue `false` */ debug?: boolean; @@ -92,19 +141,19 @@ export class CaptchaClient { constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false }: CaptchaClientOptions = {} as CaptchaClientOptions) { if (!clientKey) throw new ValidationError('clientKey is required'); this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; this.debug = debug; - this._debug('client initialized', { baseUrl, timeout, pollingInterval }); + this._debug(`client initialized sdk=javascript-sdk/${__version__} baseUrl=${baseUrl} timeout=${timeout}ms pollingInterval=${pollingInterval}ms`); } /** * Copy a value for debug output while keeping logs readable and safe to share. - * Credential fields are removed completely; long strings retain their edges - * and original length so base64 images and tokens can still be identified. + * Credential fields are masked, base64 image fields are reduced to their + * length, and other long strings keep their edges so tokens stay comparable. */ private _sanitizeForDebug(value: unknown, fieldName?: string): unknown { - if (fieldName && REDACTED_DEBUG_FIELDS.test(fieldName)) return '[REDACTED]'; + if (fieldName && MASKED_DEBUG_FIELDS.test(fieldName)) return '[MASKED]'; + if (typeof value === 'string' && fieldName && BASE64_DEBUG_FIELDS.test(fieldName)) return `[base64, ${value.length} chars]`; if (typeof value === 'string' && value.length > MAX_DEBUG_STRING_LENGTH) { - const edgeLength = Math.floor(MAX_DEBUG_STRING_LENGTH / 2); - return `${value.slice(0, edgeLength)}...[truncated; original length: ${value.length}]...${value.slice(-edgeLength)}`; + return `${value.slice(0, DEBUG_STRING_EDGE_LENGTH)}...[${value.length} chars]...${value.slice(-DEBUG_STRING_EDGE_LENGTH)}`; } if (Array.isArray(value)) return value.map((item) => this._sanitizeForDebug(item)); if (value && typeof value === 'object') { @@ -115,18 +164,20 @@ export class CaptchaClient { return value; } - /** Write one debug event after sanitizing every supplied field. */ - private _debug(message: string, details?: Record): void { - if (!this.debug) return; - if (details) console.debug(`[CaptchaClient] ${message}`, this._sanitizeForDebug(details)); - else console.debug(`[CaptchaClient] ${message}`); - } - - /** Print an HTTP exchange as one labelled JSON block instead of an ambiguous console object. */ - private _debugServerExchange(message: 'server request' | 'server response', details: Record): void { + /** + * Write one debug event: a timestamped line, optionally followed by titled + * sections such as `REQUEST (POST ):` and `RESPONSE (HTTP 200 OK):`, each with a + * sanitized JSON value. Everything goes through a single `console.debug` + * call so the sections cannot be separated from their line. + */ + private _debug(message: string, sections: DebugSection[] = []): void { if (!this.debug) return; - const json = JSON.stringify(this._sanitizeForDebug(details), null, 2); - console.debug(`[CaptchaClient] ${message}:\n${json}`); + const lines = [`[${formatDebugTimestamp(new Date())}] [CaptchaClient] ${message}`]; + for (const { title, value } of sections) { + if (title) lines.push(value === undefined ? title : `${title}:`); + if (value !== undefined) lines.push(JSON.stringify(this._sanitizeForDebug(value), null, 2)); + } + console.debug(lines.join('\n')); } /** @@ -145,34 +196,70 @@ export class CaptchaClient { protected async _request(endpoint: string, payload: Record): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); const startedAt = Date.now(); - const url = `${this.baseUrl}${endpoint}`; const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; - this._debug('request started', { endpoint }); - this._debugServerExchange('server request', { method: 'POST', url, headers, body: payload }); + let httpStatus: string | undefined; + let data: (TaskResult & { errorCode?: string; errorDescription?: string; error?: string }) | undefined; try { - const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); - let data: TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; + const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); + httpStatus = `${response.status} ${response.statusText ?? ''}`.trim(); try { data = await response.json() as typeof data; } catch (parseError) { - this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: '[unavailable: invalid JSON]' }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); throw parseError; } - // Log the server payload first; lifecycle messages below explain how the SDK interpreted it. - this._debugServerExchange('server response', { endpoint, status: response.status, statusText: response.statusText, body: data }); if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); - if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); - this._debug('request completed', { endpoint, status: response.status, durationMs: Date.now() - startedAt }); - return data; + if (data!.errorId !== 0) throw new ApiError(data!.errorCode || 'UNKNOWN_ERROR', data!.errorDescription || data!.error || 'Unknown API error'); + this._debugExchange(endpoint, payload, startedAt, { httpStatus, response: data }); + return data!; } catch (error) { - this._debug('request failed', { endpoint, error: error instanceof Error ? error.name : 'UnknownError', durationMs: Date.now() - startedAt }); - if (error instanceof ApiError || error instanceof NetworkError) throw error; - if (error && typeof error === 'object' && 'name' in error && error.name === 'AbortError') throw new TimeoutError(`Request timed out after ${this.timeout}ms`); - throw new NetworkError(error instanceof Error ? error.message : String(error), error); + let failure: unknown = error; + if (!(error instanceof ApiError || error instanceof NetworkError)) { + failure = error && typeof error === 'object' && 'name' in error && error.name === 'AbortError' + ? new TimeoutError(`Request timed out after ${this.timeout}ms`) + : new NetworkError(error instanceof Error ? error.message : String(error), error); + } + this._debugExchange(endpoint, payload, startedAt, { error: failure, httpStatus, response: data }); + throw failure; } finally { clearTimeout(timer); } } + /** + * Log one API exchange. The line names the endpoint, task type or task ID, + * outcome and duration. Below it come `REQUEST (POST ):` (the body sent, + * credentials masked) and `RESPONSE (HTTP ...):` (the server body as + * received); both are skipped for routine `processing` polls so long waits + * stay readable. + */ + private _debugExchange(endpoint: string, payload: Record, startedAt: number, outcome: { response?: TaskResult; error?: unknown; httpStatus?: string }): void { + if (!this.debug) return; + const task = payload.task as Record | undefined; + const label = [ + endpoint.replace(/^\//, ''), + typeof task?.type === 'string' ? task.type : null, + payload.taskId !== undefined ? `taskId=${payload.taskId}` : null + ].filter(Boolean).join(' '); + const durationMs = Date.now() - startedAt; + const { response, error, httpStatus } = outcome; + + const sections: DebugSection[] = [{ title: `REQUEST (POST ${this.baseUrl}${endpoint})`, value: payload }]; + // httpStatus is set only once the server answered; without it there is no response to show. + if (httpStatus) { + sections.push(response === undefined + ? { title: `RESPONSE (HTTP ${httpStatus}): body is not valid JSON` } + : { title: `RESPONSE (HTTP ${httpStatus})`, value: response }); + } + + if (error === undefined) { + const result = response?.status + ?? (response?.taskId !== undefined ? `taskId=${response.taskId}` : undefined) + ?? (response?.balance !== undefined ? `balance=${response.balance}` : 'ok'); + this._debug(`${label} -> ${result} (${durationMs}ms)`, response?.status === 'processing' ? [] : sections); + return; + } + this._debug(`${label} -> failed: ${describeDebugError(error)} (${durationMs}ms)`, sections); + } + /** * Submit a task and return its ID without waiting for the solution. * @@ -193,13 +280,8 @@ export class CaptchaClient { * ``` */ async createTask(task: BaseTask, languagePool: string | null = null): Promise { - const taskPayload = task.toDict(); - const taskType = typeof taskPayload.type === 'string' ? taskPayload.type : task.constructor.name; - this._debug('task submission started', { taskType, languagePool }); - const payload: Record = { clientKey: this.clientKey, task: taskPayload }; if (languagePool !== null) payload.languagePool = languagePool; - const taskId = (await this._request('/createTask', payload)).taskId as number; - this._debug('task created', { taskId, taskType }); - return taskId; + const payload: Record = { clientKey: this.clientKey, task: task.toDict() }; if (languagePool !== null) payload.languagePool = languagePool; + return (await this._request('/createTask', payload)).taskId as number; } /** @@ -258,47 +340,52 @@ export class CaptchaClient { * ``` */ async solve>(task: T, languagePool: string | null = null): Promise> { - const taskType = task.constructor.name; const startedAt = Date.now(); let taskId: number | null = null; - let resultRequestCount = 0; - this._debug('solve started', { taskType }); + let polls = 0; try { taskId = await this.createTask(task, languagePool); - let pollAttempt = 0; while (true) { const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - const delayMs = Math.min(this.pollingInterval, remaining); - pollAttempt += 1; - this._debug('waiting before poll', { taskId, pollAttempt, delayMs }); - await new Promise(resolve => setTimeout(resolve, delayMs)); + await new Promise(resolve => setTimeout(resolve, Math.min(this.pollingInterval, remaining))); if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - resultRequestCount += 1; + polls += 1; const result = await this.getTaskResult(taskId); - const elapsedMs = Date.now() - startedAt; - this._debug('task status received', { taskId, pollAttempt, status: result.status, elapsedMs }); if (result.status === 'ready') { - this._debug('task solved', { taskId, pollAttempts: pollAttempt, elapsedMs }); - this._debug('solve summary', { - status: 'solved', - captchaId: taskId, - elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, - elapsedMs, - resultRequestCount - }); + this._debugSolveSummary(task, startedAt, { status: 'solved', taskId, polls, result }); return (result.solution ?? {}) as SolutionOf; } } } catch (error) { - const elapsedMs = Date.now() - startedAt; - this._debug('solve summary', { - status: 'not solved', - captchaId: taskId, - elapsedTime: `${(elapsedMs / 1000).toFixed(3)}s`, - elapsedMs, - resultRequestCount - }); + this._debugSolveSummary(task, startedAt, { status: 'not solved', taskId, polls, error }); throw error; } } + + /** + * Log the final {@link solve} outcome. `serverSolveTime` comes from the API's + * `createTime` / `endTime` and shows how much of the total wait was spent + * solving versus creating the task and waiting between polls. + */ + private _debugSolveSummary(task: BaseTask, startedAt: number, outcome: { status: 'solved' | 'not solved'; taskId: number | null; polls: number; result?: TaskResult; error?: unknown }): void { + if (!this.debug) return; + const { status, taskId, polls, result, error } = outcome; + let taskType: unknown; + try { taskType = task.toDict().type; } catch { taskType = undefined; } + const createTime = result?.createTime; const endTime = result?.endTime; + const fields: Array<[string, string] | null> = [ + ['status', status], + ['taskId', String(taskId)], + typeof taskType === 'string' ? ['taskType', taskType] : null, + ['elapsed', `${((Date.now() - startedAt) / 1000).toFixed(3)}s`], + typeof createTime === 'number' && typeof endTime === 'number' ? ['serverSolveTime', `${endTime - createTime}s`] : null, + ['polls', String(polls)], + error !== undefined ? ['error', describeDebugError(error)] : null + ]; + const present = fields.filter((field): field is [string, string] => field !== null); + const width = Math.max(...present.map(([name]) => name.length)) + 1; + // One aligned "name: value" line per field; line breaks inside a value are flattened. + const lines = present.map(([name, value]) => ` ${`${name}:`.padEnd(width)} ${value.replace(/\s*\n\s*/g, ' ')}`); + this._debug(`SOLVE SUMMARY:\n${lines.join('\n')}`); + } } diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index c662039..ebd3bd3 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -39,172 +39,155 @@ describe('CaptchaClient (async)', () => { expect(requestOptions.headers['X-SDK']).toBe('javascript-sdk/1.1.0'); }); - test('debug mode logs sanitized request lifecycle events', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); - global.fetch = jest.fn(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) + describe('debug mode', () => { + const TIMESTAMP = /^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} [+-]\d{2}:\d{2}\] \[CaptchaClient\] /; + let debug; + const okResponse = (body) => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve(body) }); + const logs = () => debug.mock.calls.map(([message]) => message); + const messageOf = (text) => logs().find((message) => message.split('\n')[0].includes(text)); + const lineOf = (text) => messageOf(text)?.split('\n')[0]; + // Split the lines below an event into titled sections ("REQUEST (POST )", "RESPONSE (HTTP 200 OK)"); + const sectionsOf = (text) => { + const sections = {}; + let title = ''; + for (const line of messageOf(text).split('\n').slice(1)) { + if (/^[A-Z]/.test(line)) { title = line.replace(/:$/, ''); sections[title] = ''; } + else sections[title] = (sections[title] ?? '') + line + '\n'; + } + return Object.fromEntries(Object.entries(sections).map(([key, json]) => [key, json ? JSON.parse(json) : undefined])); + }; + // Parse the " name: value" lines below SOLVE SUMMARY into an object. + const summaryOf = () => Object.fromEntries(messageOf('SOLVE SUMMARY:').split('\n').slice(1).map((line) => { + const [, name, value] = line.match(/^ {2}(\w+): +(.*)$/); + return [name, value]; })); + const recaptchaTask = () => new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); - await client.getBalance(); - - expect(debug).toHaveBeenCalledWith('[CaptchaClient] request started', { endpoint: '/getBalance' }); - const requestLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server request:'))?.[0]; - expect(requestLog).toContain('"url": "https://api.captcha-solver.com/getBalance"'); - expect(requestLog).toContain('"clientKey": "[REDACTED]"'); - const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; - expect(responseLog).toContain('"endpoint": "/getBalance"'); - expect(responseLog).toContain('"status": 200'); - expect(responseLog).toContain('"balance": "1.00"'); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] client initialized', { - baseUrl: 'https://api.captcha-solver.com', - timeout: 120000, - pollingInterval: 5000 + beforeEach(() => { + debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] request completed', { - endpoint: '/getBalance', - status: 200, - durationMs: expect.any(Number) - }); - const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); - const completedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request completed'); - expect(responseLogIndex).toBeLessThan(completedLogIndex); - expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); - debug.mockRestore(); - }); - test('debug mode logs task type, task ID, and polling progress', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); - global.fetch = jest.fn() - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) - })) - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { token: `start-${'x'.repeat(300)}-end` } }) - })); - const task = new Tasks.RecaptchaV2Proxyless({ - websiteURL: 'https://example.com', - websiteKey: 'website_key' + afterEach(() => { + debug.mockRestore(); }); - await client.solve(task); + test('is silent by default', async () => { + global.fetch = jest.fn(() => okResponse({ errorId: 0, balance: '1.00' })); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] task created', { - taskId: 12345, - taskType: 'RecaptchaV2TaskProxyless' - }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] task status received', { - taskId: 12345, - pollAttempt: 1, - status: 'ready', - elapsedMs: expect.any(Number) + await client.getBalance(); + + expect(debug).not.toHaveBeenCalled(); }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] task solved', { - taskId: 12345, - pollAttempts: 1, - elapsedMs: expect.any(Number) + + test('prefixes every event with a local timestamp and UTC offset, in one console call each', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 0, balance: '1.00' })); + + await client.getBalance(); + + expect(logs().length).toBeGreaterThan(0); + for (const message of logs()) expect(message).toMatch(TIMESTAMP); + for (const call of debug.mock.calls) expect(call).toHaveLength(1); + expect(lineOf('client initialized')).toContain('sdk=javascript-sdk/1.1.0 baseUrl=https://api.captcha-solver.com timeout=120000ms pollingInterval=5000ms'); + expect(lineOf('getBalance')).toMatch(/getBalance -> balance=1\.00 \(\d+ms\)$/); + expect(sectionsOf('getBalance')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/getBalance)': { clientKey: '[MASKED]' }, + 'RESPONSE (HTTP 200 OK)': { errorId: 0, balance: '1.00' } + }); + expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); }); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { - status: 'solved', - captchaId: 12345, - elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), - elapsedMs: expect.any(Number), - resultRequestCount: 1 + + test('keeps processing polls on one line and logs bodies for creation and the ready result', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementationOnce(() => okResponse({ errorId: 0, status: 'processing' })) + .mockImplementationOnce(() => okResponse({ + errorId: 0, status: 'ready', solution: { token: `start-${'x'.repeat(300)}-end` }, createTime: 100, endTime: 108 + })); + + await client.solve(recaptchaTask()); + + expect(lineOf('createTask')).toMatch(/createTask RecaptchaV2TaskProxyless -> taskId=12345 \(\d+ms\)$/); + expect(sectionsOf('createTask')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/createTask)': { clientKey: '[MASKED]', task: { type: 'RecaptchaV2TaskProxyless', websiteURL: 'https://example.com', websiteKey: 'website_key' } }, + 'RESPONSE (HTTP 200 OK)': { errorId: 0, taskId: 12345 } + }); + const processing = messageOf('-> processing'); + expect(processing).toMatch(/getTaskResult taskId=12345 -> processing \(\d+ms\)$/); + expect(processing).not.toContain('\n'); + expect(lineOf('-> ready')).toMatch(/getTaskResult taskId=12345 -> ready \(\d+ms\)$/); + expect(sectionsOf('-> ready')['REQUEST (POST https://api.captcha-solver.com/getTaskResult)']).toEqual({ clientKey: '[MASKED]', taskId: 12345 }); + expect(sectionsOf('-> ready')['RESPONSE (HTTP 200 OK)'].solution.token).toMatch(/^start-x+\.\.\.\[310 chars\]\.\.\.x+-end$/); + expect(summaryOf()).toEqual({ + status: 'solved', + taskId: '12345', + taskType: 'RecaptchaV2TaskProxyless', + elapsed: expect.stringMatching(/^\d+\.\d{3}s$/), + serverSolveTime: '8s', + polls: '2' + }); + expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); }); - const logged = JSON.stringify(debug.mock.calls); - expect(logged).toContain('website_key'); - expect(logged).toContain('original length: 310'); - expect(logged).not.toContain(`start-${'x'.repeat(300)}-end`); - expect(logged).not.toContain('secret_key'); - const resultResponseLogIndex = debug.mock.calls.findIndex(([message, details]) => - message.startsWith('[CaptchaClient] server response:') && message.includes('"endpoint": "/getTaskResult"') - ); - const resultCompletedLogIndex = debug.mock.calls.findIndex(([message, details]) => - message === '[CaptchaClient] request completed' && details.endpoint === '/getTaskResult' - ); - const statusLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] task status received'); - expect(resultResponseLogIndex).toBeLessThan(resultCompletedLogIndex); - expect(resultCompletedLogIndex).toBeLessThan(statusLogIndex); - debug.mockRestore(); - }); - test('debug mode is silent by default', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - global.fetch = jest.fn(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, balance: '1.00' }) - })); + test('replaces base64 image fields with their length', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 0, taskId: 1 })); - await client.getBalance(); + await client.createTask(new Tasks.ImageToText({ body: 'A'.repeat(1000) })); - expect(debug).not.toHaveBeenCalled(); - debug.mockRestore(); - }); + expect(sectionsOf('createTask')['REQUEST (POST https://api.captcha-solver.com/createTask)'].task.body).toBe('[base64, 1000 chars]'); + }); - test('debug mode logs a not-solved summary after a result request fails', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); - global.fetch = jest.fn() - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 0, taskId: 12345 }) - })) - .mockImplementationOnce(() => Promise.resolve({ - ok: true, - status: 200, - json: () => Promise.resolve({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' }) - })); - const task = new Tasks.RecaptchaV2Proxyless({ - websiteURL: 'https://example.com', - websiteKey: 'website_key' + test('logs the API error response and adds the error to a not-solved summary', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementationOnce(() => okResponse({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' })); + + await expect(client.solve(recaptchaTask())).rejects.toThrow(ApiError); + + expect(lineOf('getTaskResult')).toMatch(/getTaskResult taskId=12345 -> failed: ApiError ERROR_TASK_FAILED: Task failed \(\d+ms\)$/); + expect(sectionsOf('getTaskResult')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/getTaskResult)': { clientKey: '[MASKED]', taskId: 12345 }, + 'RESPONSE (HTTP 200 OK)': { errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' } + }); + expect(summaryOf()).toEqual({ + status: 'not solved', + taskId: '12345', + taskType: 'RecaptchaV2TaskProxyless', + elapsed: expect.stringMatching(/^\d+\.\d{3}s$/), + polls: '1', + error: 'ApiError ERROR_TASK_FAILED: Task failed' + }); }); - await expect(client.solve(task)).rejects.toThrow(ApiError); + test('includes the transport cause hidden behind "fetch failed"', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + const cause = Object.assign(new Error('Connect Timeout Error (attempted address: api.captcha-solver.com:443, timeout: 10000ms)'), { + name: 'ConnectTimeoutError', + code: 'UND_ERR_CONNECT_TIMEOUT' + }); + global.fetch = jest.fn(() => Promise.reject(new TypeError('fetch failed', { cause }))); - expect(debug).toHaveBeenCalledWith('[CaptchaClient] solve summary', { - status: 'not solved', - captchaId: 12345, - elapsedTime: expect.stringMatching(/^\d+\.\d{3}s$/), - elapsedMs: expect.any(Number), - resultRequestCount: 1 + await expect(client.getBalance()).rejects.toThrow(NetworkError); + + expect(lineOf('getBalance')).toContain( + 'failed: NetworkError: fetch failed <- ConnectTimeoutError UND_ERR_CONNECT_TIMEOUT: Connect Timeout Error (attempted address: api.captcha-solver.com:443, timeout: 10000ms)' + ); }); - debug.mockRestore(); - }); - test('debug mode logs the original API error response before throwing', async () => { - const debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); - client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); - const errorBody = { - errorId: 1, - errorCode: 'ERROR_KEY_DOES_NOT_EXIST', - errorDescription: 'Account not found' - }; - global.fetch = jest.fn(() => Promise.resolve({ - ok: true, - status: 200, - statusText: 'OK', - json: () => Promise.resolve(errorBody) - })); + test('logs the error the caller receives, not the raw transport error', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 10 }); + global.fetch = jest.fn((url, options) => new Promise((resolve, reject) => { + options.signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))); + })); - await expect(client.getBalance()).rejects.toThrow(ApiError); + await expect(client.getBalance()).rejects.toThrow(TimeoutError); - const responseLog = debug.mock.calls.find(([message]) => message.startsWith('[CaptchaClient] server response:'))?.[0]; - expect(responseLog).toContain('"endpoint": "/getBalance"'); - expect(responseLog).toContain('"errorCode": "ERROR_KEY_DOES_NOT_EXIST"'); - expect(responseLog).toContain('"errorDescription": "Account not found"'); - const responseLogIndex = debug.mock.calls.findIndex(([message]) => message.startsWith('[CaptchaClient] server response:')); - const failedLogIndex = debug.mock.calls.findIndex(([message]) => message === '[CaptchaClient] request failed'); - expect(responseLogIndex).toBeLessThan(failedLogIndex); - debug.mockRestore(); + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: TimeoutError: Request timed out after 10ms \(\d+ms\)$/); + expect(lineOf('getBalance')).not.toContain('AbortError'); + }); }); test('aborts an HTTP request after timeout', async () => { From 0af287182d4dabaac13ef827e66f26d210eed117 Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 00:33:31 +0300 Subject: [PATCH 22/31] feat: always pair debug REQUEST with a RESPONSE line When the server never answers (connection refused, timeout), print "RESPONSE: none - no response from the server ()" so every logged request shows what happened to its response. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +++-- src/client.ts | 8 ++++++-- tests/unit/async/client.test.js | 2 ++ 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f154c03..cf0a958 100644 --- a/README.md +++ b/README.md @@ -745,8 +745,9 @@ RESPONSE (HTTP 200 OK): polls stay on one line. - Failed requests print the error the caller receives, e.g. `getTaskResult taskId=3668 -> failed: ApiError ERROR_TASK_FAILED: ...`, followed by - `REQUEST (POST ):` and, when the server answered, `RESPONSE (HTTP ...):`. A - failed `solve()` ends with a `SOLVE SUMMARY` whose `status` is `not solved` and + `REQUEST (POST ):` and `RESPONSE (HTTP ...):`. If the server never answered + (connection refused, timeout), the last line is + `RESPONSE: none - no response from the server (NetworkError)`. A failed `solve()` ends with a `SOLVE SUMMARY` whose `status` is `not solved` and which has an extra `error` line. - `serverSolveTime` comes from the API's `createTime` / `endTime`; the difference from `elapsed` is task creation plus waiting between polls. diff --git a/src/client.ts b/src/client.ts index ab0eab3..04b535d 100644 --- a/src/client.ts +++ b/src/client.ts @@ -243,8 +243,12 @@ export class CaptchaClient { const { response, error, httpStatus } = outcome; const sections: DebugSection[] = [{ title: `REQUEST (POST ${this.baseUrl}${endpoint})`, value: payload }]; - // httpStatus is set only once the server answered; without it there is no response to show. - if (httpStatus) { + // httpStatus is set only once the server answered; without it the request failed in transit, + // and an explicit "none" line keeps every REQUEST paired with a RESPONSE. + if (!httpStatus) { + const errorName = error instanceof Error ? error.name : 'Error'; + sections.push({ title: `RESPONSE: none - no response from the server (${errorName})` }); + } else { sections.push(response === undefined ? { title: `RESPONSE (HTTP ${httpStatus}): body is not valid JSON` } : { title: `RESPONSE (HTTP ${httpStatus})`, value: response }); diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index ebd3bd3..3bd12ee 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -175,6 +175,7 @@ describe('CaptchaClient (async)', () => { expect(lineOf('getBalance')).toContain( 'failed: NetworkError: fetch failed <- ConnectTimeoutError UND_ERR_CONNECT_TIMEOUT: Connect Timeout Error (attempted address: api.captcha-solver.com:443, timeout: 10000ms)' ); + expect(messageOf('getBalance').split('\n').at(-1)).toBe('RESPONSE: none - no response from the server (NetworkError)'); }); test('logs the error the caller receives, not the raw transport error', async () => { @@ -187,6 +188,7 @@ describe('CaptchaClient (async)', () => { expect(lineOf('getBalance')).toMatch(/getBalance -> failed: TimeoutError: Request timed out after 10ms \(\d+ms\)$/); expect(lineOf('getBalance')).not.toContain('AbortError'); + expect(messageOf('getBalance').split('\n').at(-1)).toBe('RESPONSE: none - no response from the server (TimeoutError)'); }); }); From f2bf4fa001b2a9f61fb336b83c4e63b2af9d2793 Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 00:39:04 +0300 Subject: [PATCH 23/31] feat: show request duration in debug RESPONSE Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +++++++------ src/client.ts | 6 +++--- tests/unit/async/client.test.js | 7 ++++--- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index cf0a958..0752e46 100644 --- a/README.md +++ b/README.md @@ -710,7 +710,7 @@ REQUEST (POST https://api.captcha-solver.com/createTask): "task": "[7,15,14,0,11,6,6,0]" } } -RESPONSE (HTTP 200 OK): +RESPONSE (HTTP 200 OK, 4325ms): { "errorId": 0, "taskId": 3668 @@ -722,7 +722,7 @@ REQUEST (POST https://api.captcha-solver.com/getTaskResult): "clientKey": "[MASKED]", "taskId": 3668 } -RESPONSE (HTTP 200 OK): +RESPONSE (HTTP 200 OK, 740ms): { "errorId": 0, "status": "ready", @@ -740,14 +740,15 @@ RESPONSE (HTTP 200 OK): ``` - `REQUEST (POST ):` is the endpoint URL and JSON body the SDK sent; - `RESPONSE (HTTP ...):` is the server body exactly as received. They are printed for + `RESPONSE (HTTP ..., ms):` is the server body exactly as received. They are printed for task creation, balance checks, errors, and the `ready` result; routine `processing` polls stay on one line. - Failed requests print the error the caller receives, e.g. `getTaskResult taskId=3668 -> failed: ApiError ERROR_TASK_FAILED: ...`, followed by - `REQUEST (POST ):` and `RESPONSE (HTTP ...):`. If the server never answered - (connection refused, timeout), the last line is - `RESPONSE: none - no response from the server (NetworkError)`. A failed `solve()` ends with a `SOLVE SUMMARY` whose `status` is `not solved` and + `REQUEST (POST ):` and `RESPONSE (HTTP ..., ms):`. If the server never + answered (connection refused, timeout), the last line is + `RESPONSE: none - no response from the server (NetworkError, 36ms)`. +- A failed `solve()` ends with a `SOLVE SUMMARY` whose `status` is `not solved` and which has an extra `error` line. - `serverSolveTime` comes from the API's `createTime` / `endTime`; the difference from `elapsed` is task creation plus waiting between polls. diff --git a/src/client.ts b/src/client.ts index 04b535d..bf75a69 100644 --- a/src/client.ts +++ b/src/client.ts @@ -247,11 +247,11 @@ export class CaptchaClient { // and an explicit "none" line keeps every REQUEST paired with a RESPONSE. if (!httpStatus) { const errorName = error instanceof Error ? error.name : 'Error'; - sections.push({ title: `RESPONSE: none - no response from the server (${errorName})` }); + sections.push({ title: `RESPONSE: none - no response from the server (${errorName}, ${durationMs}ms)` }); } else { sections.push(response === undefined - ? { title: `RESPONSE (HTTP ${httpStatus}): body is not valid JSON` } - : { title: `RESPONSE (HTTP ${httpStatus})`, value: response }); + ? { title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms): body is not valid JSON` } + : { title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms)`, value: response }); } if (error === undefined) { diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 3bd12ee..e323925 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -47,11 +47,12 @@ describe('CaptchaClient (async)', () => { const messageOf = (text) => logs().find((message) => message.split('\n')[0].includes(text)); const lineOf = (text) => messageOf(text)?.split('\n')[0]; // Split the lines below an event into titled sections ("REQUEST (POST )", "RESPONSE (HTTP 200 OK)"); + // the variable ", ms" duration is dropped from titles so tests can use fixed keys. const sectionsOf = (text) => { const sections = {}; let title = ''; for (const line of messageOf(text).split('\n').slice(1)) { - if (/^[A-Z]/.test(line)) { title = line.replace(/:$/, ''); sections[title] = ''; } + if (/^[A-Z]/.test(line)) { title = line.replace(/:$/, '').replace(/, \d+ms\)/, ')'); sections[title] = ''; } else sections[title] = (sections[title] ?? '') + line + '\n'; } return Object.fromEntries(Object.entries(sections).map(([key, json]) => [key, json ? JSON.parse(json) : undefined])); @@ -175,7 +176,7 @@ describe('CaptchaClient (async)', () => { expect(lineOf('getBalance')).toContain( 'failed: NetworkError: fetch failed <- ConnectTimeoutError UND_ERR_CONNECT_TIMEOUT: Connect Timeout Error (attempted address: api.captcha-solver.com:443, timeout: 10000ms)' ); - expect(messageOf('getBalance').split('\n').at(-1)).toBe('RESPONSE: none - no response from the server (NetworkError)'); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE: none - no response from the server \(NetworkError, \d+ms\)$/); }); test('logs the error the caller receives, not the raw transport error', async () => { @@ -188,7 +189,7 @@ describe('CaptchaClient (async)', () => { expect(lineOf('getBalance')).toMatch(/getBalance -> failed: TimeoutError: Request timed out after 10ms \(\d+ms\)$/); expect(lineOf('getBalance')).not.toContain('AbortError'); - expect(messageOf('getBalance').split('\n').at(-1)).toBe('RESPONSE: none - no response from the server (TimeoutError)'); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE: none - no response from the server \(TimeoutError, \d+ms\)$/); }); }); From 5f5f1cc0a7e8b62e974741c27df4972c82af9203 Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 01:41:30 +0300 Subject: [PATCH 24/31] docs: add debug mode example, disable debug in Kaleidoscope example Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++- examples/README.md | 1 + examples/debug_mode.js | 46 ++++++++++++++++++++ examples/yandex_smartcaptcha_kaleidoscope.js | 3 +- 4 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 examples/debug_mode.js diff --git a/README.md b/README.md index 0752e46..24f61fd 100644 --- a/README.md +++ b/README.md @@ -696,6 +696,8 @@ const captchaSolver = new CaptchaClient({ }); ``` +A runnable version is in [examples/debug_mode.js](examples/debug_mode.js). + Example output of `solve()`: ```text @@ -837,7 +839,7 @@ matches this README. - **Image/click captchas** (`image_to_text.js`, `image_to_text_math.js`, `image_to_text_language_pool.js`, `coordinates.js`, `coordinates_traffic_lights.js`, - `yandex_smartcaptcha_image.js`, `yandex_smartcaptcha_kaleidoscope.js`) run end-to-end + `yandex_smartcaptcha_image.js`, `yandex_smartcaptcha_kaleidoscope.js`, `debug_mode.js`) run end-to-end with nothing but a valid `CAPTCHA_API_KEY` -- they read sample images bundled in [examples/assets](examples/assets), no target page needed. - **Token captchas** (`recaptcha_v2.js`, `recaptcha_v2_enterprise.js`, `recaptcha_v3.js`, @@ -861,6 +863,7 @@ export CAPTCHA_API_KEY=your_api_key node examples/balance.js node examples/image_to_text.js node examples/coordinates.js +node examples/debug_mode.js ``` Full details, an example index, and a per-type breakdown of what each script diff --git a/examples/README.md b/examples/README.md index 21d5b14..34f9cea 100644 --- a/examples/README.md +++ b/examples/README.md @@ -47,6 +47,7 @@ Additional one-scenario examples: - [`image_to_text_math.js`](image_to_text_math.js) — math CAPTCHA with an instruction image. - [`image_to_text_language_pool.js`](image_to_text_language_pool.js) — select the English worker pool. - [`coordinates_traffic_lights.js`](coordinates_traffic_lights.js) — click coordinates with an instruction image. +- [`debug_mode.js`](debug_mode.js) — enable `debug: true` and watch the SDK's request, response and solve summary log. > **Important:** `geetest_v3.js` and `geetest_v3_proxy.js` contain a placeholder > initialization endpoint. Replace it with the target website's endpoint and diff --git a/examples/debug_mode.js b/examples/debug_mode.js new file mode 100644 index 0000000..eff0297 --- /dev/null +++ b/examples/debug_mode.js @@ -0,0 +1,46 @@ +import 'dotenv/config'; +import fs from 'fs'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; + +/** + * Debug mode: watch every API request, server response and the final solve summary. + * It enables `debug: true`, solves a text CAPTCHA from a bundled image with + * CaptchaClient.solve(), and prints the recognized text. The `[CaptchaClient] ...` + * lines are the SDK's debug log; the last line is printed by this example. + * Credentials in the log are shown as [MASKED], so the output is safe to share. + * + * How it works: + * STEP-01 - Configure the SDK client with debug logging enabled. + * STEP-02 - Create the CAPTCHA task from a local image. + * STEP-03 - Submit the task; the SDK logs each request and a SOLVE SUMMARY. + * STEP-04 - Print the solution or report an error. + */ + +if (!process.env.CAPTCHA_API_KEY) { + throw new Error('Set CAPTCHA_API_KEY in .env or in the current shell before running this example.'); +} + +// STEP-01: Configure the SDK client; debug: true turns on the debug log. +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY, + debug: true +}); + +// STEP-02: Create the CAPTCHA task from the bundled sample image. +const task = new Tasks.ImageToText({ + body: fs.readFileSync(new URL('./assets/text-captcha.png', import.meta.url)).toString('base64'), + numeric: 2, + minLength: 4, + maxLength: 6 +}); + +// STEP-03: Submit the task; solve() handles task creation and polling and logs each step. +client.solve(task) + .then((solution) => { + // STEP-04: Print the result returned by solve(), after the SDK's SOLVE SUMMARY. + console.log('Result:', solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 4f5bcbd..2d0a282 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -21,8 +21,7 @@ if (!process.env.CAPTCHA_API_KEY) { // STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ - clientKey: process.env.CAPTCHA_API_KEY, - debug: true + clientKey: process.env.CAPTCHA_API_KEY }); const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) From 69382fd943475cca9f386380ad262c13261d7c53 Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 01:45:04 +0300 Subject: [PATCH 25/31] feat: mask proxyAddress in debug output Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/client.ts | 2 +- tests/unit/async/client.test.js | 20 ++++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 24f61fd..36287b9 100644 --- a/README.md +++ b/README.md @@ -754,7 +754,7 @@ RESPONSE (HTTP 200 OK, 740ms): which has an extra `error` line. - `serverSolveTime` comes from the API's `createTime` / `endTime`; the difference from `elapsed` is task creation plus waiting between polls. -- The API key and other credentials (`proxyLogin`, `proxyPassword`, `cookies`) are +- The API key, proxy details (`proxyAddress`, `proxyLogin`, `proxyPassword`) and `cookies` are replaced with `[MASKED]`, base64 images with their length, and other long strings such as solution tokens are shortened. The output is safe to attach to bug reports. diff --git a/src/client.ts b/src/client.ts index bf75a69..8a05947 100644 --- a/src/client.ts +++ b/src/client.ts @@ -4,7 +4,7 @@ import type { BaseTask } from './tasks.js'; const MAX_DEBUG_STRING_LENGTH = 200; const DEBUG_STRING_EDGE_LENGTH = 40; -const MASKED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyLogin|proxyPassword)$/i; +const MASKED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyAddress|proxyLogin|proxyPassword)$/i; /** Task fields that carry base64 images; their content is never useful in a log. */ const BASE64_DEBUG_FIELDS = /^(body|image|imgInstructions)$/; diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index e323925..6b73e06 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -140,6 +140,26 @@ describe('CaptchaClient (async)', () => { expect(sectionsOf('createTask')['REQUEST (POST https://api.captcha-solver.com/createTask)'].task.body).toBe('[base64, 1000 chars]'); }); + test('masks proxy address and credentials', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 0, taskId: 1 })); + + await client.createTask(new Tasks.Turnstile({ + websiteURL: 'https://example.com', + websiteKey: 'website_key', + proxyType: 'http', + proxyAddress: '203.0.113.7', + proxyPort: 8080, + proxyLogin: 'proxy_user', + proxyPassword: 'proxy_pass' + })); + + const { task } = sectionsOf('createTask')['REQUEST (POST https://api.captcha-solver.com/createTask)']; + expect(task).toMatchObject({ proxyAddress: '[MASKED]', proxyPort: 8080, proxyLogin: '[MASKED]', proxyPassword: '[MASKED]' }); + const logged = JSON.stringify(debug.mock.calls); + for (const secret of ['203.0.113.7', 'proxy_user', 'proxy_pass', 'secret_key']) expect(logged).not.toContain(secret); + }); + test('logs the API error response and adds the error to a not-solved summary', async () => { client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); global.fetch = jest.fn() From 95d99fea0cabf94b3508bf8b387c61eaa7b74ee5 Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 01:49:34 +0300 Subject: [PATCH 26/31] feat: explain missing taskId in SOLVE SUMMARY Co-Authored-By: Claude Opus 5.5 --- src/client.ts | 2 +- tests/unit/async/client.test.js | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/client.ts b/src/client.ts index 8a05947..4940202 100644 --- a/src/client.ts +++ b/src/client.ts @@ -379,7 +379,7 @@ export class CaptchaClient { const createTime = result?.createTime; const endTime = result?.endTime; const fields: Array<[string, string] | null> = [ ['status', status], - ['taskId', String(taskId)], + ['taskId', taskId === null ? '- (task was not created)' : String(taskId)], typeof taskType === 'string' ? ['taskType', taskType] : null, ['elapsed', `${((Date.now() - startedAt) / 1000).toFixed(3)}s`], typeof createTime === 'number' && typeof endTime === 'number' ? ['serverSolveTime', `${endTime - createTime}s`] : null, diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 6b73e06..498617a 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -183,6 +183,20 @@ describe('CaptchaClient (async)', () => { }); }); + test('says the task was not created when createTask fails inside solve()', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 1, errorCode: 'ERROR_KEY_DOES_NOT_EXIST', errorDescription: 'Key not found' })); + + await expect(client.solve(recaptchaTask())).rejects.toThrow(ApiError); + + expect(summaryOf()).toMatchObject({ + status: 'not solved', + taskId: '- (task was not created)', + polls: '0', + error: 'ApiError ERROR_KEY_DOES_NOT_EXIST: Key not found' + }); + }); + test('includes the transport cause hidden behind "fetch failed"', async () => { client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); const cause = Object.assign(new Error('Connect Timeout Error (attempted address: api.captcha-solver.com:443, timeout: 10000ms)'), { From 1ae1355c82fbc05cb9c2f7a2f95eece368ff076e Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 01:54:52 +0300 Subject: [PATCH 27/31] test: cover debug output for HTTP errors, invalid JSON and solve timeout Co-Authored-By: Claude Opus 5.5 --- tests/unit/async/client.test.js | 51 +++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 498617a..09d8bd3 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -213,6 +213,57 @@ describe('CaptchaClient (async)', () => { expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE: none - no response from the server \(NetworkError, \d+ms\)$/); }); + test('logs the JSON body of a non-2xx HTTP response', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, baseUrl: 'https://api.captcha-solver.com/no-such-path' }); + global.fetch = jest.fn(() => Promise.resolve({ + ok: false, + status: 404, + statusText: 'Not Found', + json: () => Promise.resolve({ message: 'The route could not be found.' }) + })); + + await expect(client.getBalance()).rejects.toThrow(NetworkError); + + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: NetworkError: HTTP error: 404 Not Found \(\d+ms\)$/); + expect(sectionsOf('getBalance')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/no-such-path/getBalance)': { clientKey: '[MASKED]' }, + 'RESPONSE (HTTP 404 Not Found)': { message: 'The route could not be found.' } + }); + }); + + test('says when the response body is not valid JSON', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => Promise.resolve({ + ok: false, + status: 502, + statusText: 'Bad Gateway', + json: () => Promise.reject(new SyntaxError('Unexpected token < in JSON')) + })); + + await expect(client.getBalance()).rejects.toThrow(NetworkError); + + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: NetworkError: HTTP error: 502 Bad Gateway \(\d+ms\)$/); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE \(HTTP 502 Bad Gateway, \d+ms\): body is not valid JSON$/); + }); + + test('reports a solve() timeout in the summary', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 40, pollingInterval: 5 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementation(() => okResponse({ errorId: 0, status: 'processing' })); + + await expect(client.solve(recaptchaTask())).rejects.toThrow(TimeoutError); + + const summary = summaryOf(); + expect(summary).toMatchObject({ + status: 'not solved', + taskId: '12345', + error: 'TimeoutError: Task 12345 timed out after 40ms' + }); + expect(Number(summary.polls)).toBeGreaterThan(0); + expect(summary).not.toHaveProperty('serverSolveTime'); + }); + test('logs the error the caller receives, not the raw transport error', async () => { client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 10 }); global.fetch = jest.fn((url, options) => new Promise((resolve, reject) => { From 84f15f4e12d77978ee5db1c7e83d056e2708a56a Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 01:56:04 +0300 Subject: [PATCH 28/31] fix: tell a timed-out response body apart from invalid JSON in debug log Co-Authored-By: Claude Opus 5.5 --- src/client.ts | 20 +++++++++++++------- tests/unit/async/client.test.js | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/client.ts b/src/client.ts index 4940202..32f1979 100644 --- a/src/client.ts +++ b/src/client.ts @@ -198,6 +198,7 @@ export class CaptchaClient { const startedAt = Date.now(); const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; let httpStatus: string | undefined; + let bodyNotJson = false; let data: (TaskResult & { errorCode?: string; errorDescription?: string; error?: string }) | undefined; try { const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); @@ -205,6 +206,9 @@ export class CaptchaClient { try { data = await response.json() as typeof data; } catch (parseError) { + // A SyntaxError means the body arrived but is not JSON; anything else (e.g. AbortError + // on timeout) means the body never fully arrived. + bodyNotJson = parseError instanceof SyntaxError; if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); throw parseError; } @@ -219,7 +223,7 @@ export class CaptchaClient { ? new TimeoutError(`Request timed out after ${this.timeout}ms`) : new NetworkError(error instanceof Error ? error.message : String(error), error); } - this._debugExchange(endpoint, payload, startedAt, { error: failure, httpStatus, response: data }); + this._debugExchange(endpoint, payload, startedAt, { error: failure, httpStatus, response: data, bodyNotJson }); throw failure; } finally { clearTimeout(timer); } } @@ -231,7 +235,7 @@ export class CaptchaClient { * received); both are skipped for routine `processing` polls so long waits * stay readable. */ - private _debugExchange(endpoint: string, payload: Record, startedAt: number, outcome: { response?: TaskResult; error?: unknown; httpStatus?: string }): void { + private _debugExchange(endpoint: string, payload: Record, startedAt: number, outcome: { response?: TaskResult; error?: unknown; httpStatus?: string; bodyNotJson?: boolean }): void { if (!this.debug) return; const task = payload.task as Record | undefined; const label = [ @@ -240,18 +244,20 @@ export class CaptchaClient { payload.taskId !== undefined ? `taskId=${payload.taskId}` : null ].filter(Boolean).join(' '); const durationMs = Date.now() - startedAt; - const { response, error, httpStatus } = outcome; + const { response, error, httpStatus, bodyNotJson } = outcome; + const errorName = error instanceof Error ? error.name : 'Error'; const sections: DebugSection[] = [{ title: `REQUEST (POST ${this.baseUrl}${endpoint})`, value: payload }]; // httpStatus is set only once the server answered; without it the request failed in transit, // and an explicit "none" line keeps every REQUEST paired with a RESPONSE. if (!httpStatus) { - const errorName = error instanceof Error ? error.name : 'Error'; sections.push({ title: `RESPONSE: none - no response from the server (${errorName}, ${durationMs}ms)` }); + } else if (response !== undefined) { + sections.push({ title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms)`, value: response }); + } else if (bodyNotJson) { + sections.push({ title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms): body is not valid JSON` }); } else { - sections.push(response === undefined - ? { title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms): body is not valid JSON` } - : { title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms)`, value: response }); + sections.push({ title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms): body was not received (${errorName})` }); } if (error === undefined) { diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 09d8bd3..1c0f13d 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -246,6 +246,24 @@ describe('CaptchaClient (async)', () => { expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE \(HTTP 502 Bad Gateway, \d+ms\): body is not valid JSON$/); }); + test('says the body was not received when the timeout hits while reading it', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 20 }); + // Headers arrive at once; the body only fails when the request is aborted by the timeout. + global.fetch = jest.fn((url, options) => Promise.resolve({ + ok: true, + status: 200, + statusText: 'OK', + json: () => new Promise((resolve, reject) => { + options.signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))); + }) + })); + + await expect(client.getBalance()).rejects.toThrow(TimeoutError); + + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: TimeoutError: Request timed out after 20ms \(\d+ms\)$/); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE \(HTTP 200 OK, \d+ms\): body was not received \(TimeoutError\)$/); + }); + test('reports a solve() timeout in the summary', async () => { client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 40, pollingInterval: 5 }); global.fetch = jest.fn() From 60a3faaee7131835e01f1f32d22d03123fd761e0 Mon Sep 17 00:00:00 2001 From: dzmitry-duboyski Date: Fri, 13 Nov 2026 02:00:30 +0300 Subject: [PATCH 29/31] fix: never let debug output change request results Co-Authored-By: Claude Opus 5.5 --- src/client.ts | 31 +++++++++++++++++++++---------- tests/unit/async/client.test.js | 15 +++++++++++++++ 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/src/client.ts b/src/client.ts index 32f1979..09c9e05 100644 --- a/src/client.ts +++ b/src/client.ts @@ -172,12 +172,23 @@ export class CaptchaClient { */ private _debug(message: string, sections: DebugSection[] = []): void { if (!this.debug) return; - const lines = [`[${formatDebugTimestamp(new Date())}] [CaptchaClient] ${message}`]; - for (const { title, value } of sections) { - if (title) lines.push(value === undefined ? title : `${title}:`); - if (value !== undefined) lines.push(JSON.stringify(this._sanitizeForDebug(value), null, 2)); - } - console.debug(lines.join('\n')); + this._ignoreDebugFailure(() => { + const lines = [`[${formatDebugTimestamp(new Date())}] [CaptchaClient] ${message}`]; + for (const { title, value } of sections) { + if (title) lines.push(value === undefined ? title : `${title}:`); + if (value !== undefined) lines.push(JSON.stringify(this._sanitizeForDebug(value), null, 2)); + } + console.debug(lines.join('\n')); + }); + } + + /** + * Run debug-only code so that it can never change what the caller gets: + * a failure while building or printing a debug event (e.g. a replaced + * `console.debug` that throws) is swallowed instead of failing the request. + */ + private _ignoreDebugFailure(write: () => void): void { + try { write(); } catch { /* debug output must not affect the request */ } } /** @@ -214,7 +225,7 @@ export class CaptchaClient { } if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); if (data!.errorId !== 0) throw new ApiError(data!.errorCode || 'UNKNOWN_ERROR', data!.errorDescription || data!.error || 'Unknown API error'); - this._debugExchange(endpoint, payload, startedAt, { httpStatus, response: data }); + this._ignoreDebugFailure(() => this._debugExchange(endpoint, payload, startedAt, { httpStatus, response: data })); return data!; } catch (error) { let failure: unknown = error; @@ -223,7 +234,7 @@ export class CaptchaClient { ? new TimeoutError(`Request timed out after ${this.timeout}ms`) : new NetworkError(error instanceof Error ? error.message : String(error), error); } - this._debugExchange(endpoint, payload, startedAt, { error: failure, httpStatus, response: data, bodyNotJson }); + this._ignoreDebugFailure(() => this._debugExchange(endpoint, payload, startedAt, { error: failure, httpStatus, response: data, bodyNotJson })); throw failure; } finally { clearTimeout(timer); } } @@ -362,12 +373,12 @@ export class CaptchaClient { polls += 1; const result = await this.getTaskResult(taskId); if (result.status === 'ready') { - this._debugSolveSummary(task, startedAt, { status: 'solved', taskId, polls, result }); + this._ignoreDebugFailure(() => this._debugSolveSummary(task, startedAt, { status: 'solved', taskId, polls, result })); return (result.solution ?? {}) as SolutionOf; } } } catch (error) { - this._debugSolveSummary(task, startedAt, { status: 'not solved', taskId, polls, error }); + this._ignoreDebugFailure(() => this._debugSolveSummary(task, startedAt, { status: 'not solved', taskId, polls, error })); throw error; } } diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index 1c0f13d..4445415 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -246,6 +246,21 @@ describe('CaptchaClient (async)', () => { expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE \(HTTP 502 Bad Gateway, \d+ms\): body is not valid JSON$/); }); + test('a failing debug output never changes what the caller gets', async () => { + debug.mockImplementation(() => { throw new Error('console is broken'); }); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementationOnce(() => okResponse({ errorId: 0, status: 'ready', solution: { gRecaptchaResponse: 'token' } })) + .mockImplementationOnce(() => okResponse({ errorId: 1, errorCode: 'ERROR_KEY_DOES_NOT_EXIST', errorDescription: 'Key not found' })); + + await expect(client.solve(recaptchaTask())).resolves.toEqual({ gRecaptchaResponse: 'token' }); + const error = await client.getBalance().catch((e) => e); + expect(error).toBeInstanceOf(ApiError); + expect(error.errorCode).toBe('ERROR_KEY_DOES_NOT_EXIST'); + expect(debug).toHaveBeenCalled(); + }); + test('says the body was not received when the timeout hits while reading it', async () => { client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 20 }); // Headers arrive at once; the body only fails when the request is aborted by the timeout. From 4e513cbc3d18a64d6a62e423c2c42d97d3ddc95f Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Fri, 13 Nov 2026 16:20:13 +0300 Subject: [PATCH 30/31] docs: align debug guide with runnable example --- README.md | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 36287b9..4d2b848 100644 --- a/README.md +++ b/README.md @@ -684,9 +684,10 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print one `console.debug` line per API request and a summary at the -end of `solve()`. Every line starts with the local time, milliseconds and UTC offset, -so the output can be matched against your application and server logs. +Enable `debug` to print one `console.debug` event for each significant API exchange +and a summary at the end of `solve()`. Each event starts with the local time, +milliseconds and UTC offset, so the output can be matched against your application +and server logs. Request and response JSON is grouped below the event's first line. ```javascript // Create a client with sanitized debug logging enabled. @@ -701,15 +702,17 @@ A runnable version is in [examples/debug_mode.js](examples/debug_mode.js). Example output of `solve()`: ```text -[2026-11-12 14:03:12.879 +03:00] [CaptchaClient] client initialized sdk=javascript-sdk/1.1.0 baseUrl=https://api.captcha-solver.com timeout=120000ms pollingInterval=5000ms -[2026-11-12 14:03:17.204 +03:00] [CaptchaClient] createTask PazlCaptchaTask -> taskId=3668 (4325ms) +[2026-11-13 12:41:02.879 +03:00] [CaptchaClient] client initialized sdk=javascript-sdk/1.1.0 baseUrl=https://api.captcha-solver.com timeout=120000ms pollingInterval=5000ms +[2026-11-13 12:41:07.204 +03:00] [CaptchaClient] createTask ImageToTextTask -> taskId=3668 (4325ms) REQUEST (POST https://api.captcha-solver.com/createTask): { "clientKey": "[MASKED]", "task": { - "type": "PazlCaptchaTask", - "image": "[base64, 142668 chars]", - "task": "[7,15,14,0,11,6,6,0]" + "type": "ImageToTextTask", + "body": "[base64, 41188 chars]", + "numeric": 2, + "minLength": 4, + "maxLength": 6 } } RESPONSE (HTTP 200 OK, 4325ms): @@ -717,8 +720,8 @@ RESPONSE (HTTP 200 OK, 4325ms): "errorId": 0, "taskId": 3668 } -[2026-11-12 14:03:23.430 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> processing (1226ms) -[2026-11-12 14:03:29.170 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> ready (740ms) +[2026-11-13 12:41:13.430 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> processing (1226ms) +[2026-11-13 12:41:19.170 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> ready (740ms) REQUEST (POST https://api.captcha-solver.com/getTaskResult): { "clientKey": "[MASKED]", @@ -728,21 +731,24 @@ RESPONSE (HTTP 200 OK, 740ms): { "errorId": 0, "status": "ready", - "solution": "7", + "solution": { + "text": "wm47" + }, "createTime": 1794515548, "endTime": 1794515556 } -[2026-11-12 14:03:29.171 +03:00] [CaptchaClient] SOLVE SUMMARY: +[2026-11-13 12:41:19.171 +03:00] [CaptchaClient] SOLVE SUMMARY: status: solved taskId: 3668 - taskType: PazlCaptchaTask + taskType: ImageToTextTask elapsed: 16.292s serverSolveTime: 8s polls: 2 ``` - `REQUEST (POST ):` is the endpoint URL and JSON body the SDK sent; - `RESPONSE (HTTP ..., ms):` is the server body exactly as received. They are printed for + `RESPONSE (HTTP ..., ms):` is the parsed server JSON after the same masking and + shortening used for request data. They are printed for task creation, balance checks, errors, and the `ready` result; routine `processing` polls stay on one line. - Failed requests print the error the caller receives, e.g. @@ -756,7 +762,8 @@ RESPONSE (HTTP 200 OK, 740ms): `elapsed` is task creation plus waiting between polls. - The API key, proxy details (`proxyAddress`, `proxyLogin`, `proxyPassword`) and `cookies` are replaced with `[MASKED]`, base64 images with their length, and other long strings - such as solution tokens are shortened. The output is safe to attach to bug reports. + such as solution tokens are shortened. Review the output before attaching it to a bug + report because URLs and custom task fields can still contain application-specific data. ### Worker language pool From ddabe0e0804c8776edd844c1c8ef0da8f64feb53 Mon Sep 17 00:00:00 2001 From: dariyaanis Date: Fri, 13 Nov 2026 16:22:26 +0300 Subject: [PATCH 31/31] docs: shorten debug mode guide --- README.md | 77 +++++-------------------------------------------------- 1 file changed, 7 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 4d2b848..8d9a3dc 100644 --- a/README.md +++ b/README.md @@ -684,10 +684,9 @@ const captchaSolver = new CaptchaClient({ ### Debug mode -Enable `debug` to print one `console.debug` event for each significant API exchange -and a summary at the end of `solve()`. Each event starts with the local time, -milliseconds and UTC offset, so the output can be matched against your application -and server logs. Request and response JSON is grouped below the event's first line. +Enable `debug` to inspect how the SDK communicates with the API. It logs timestamped +requests, server responses, errors, request duration, task status, and a final +`solve()` summary with the task ID, elapsed time, and poll count. ```javascript // Create a client with sanitized debug logging enabled. @@ -697,73 +696,11 @@ const captchaSolver = new CaptchaClient({ }); ``` -A runnable version is in [examples/debug_mode.js](examples/debug_mode.js). +Credentials and cookies are masked, base64 images are replaced with their length, +and long strings are shortened. Review logs before sharing them because URLs and +custom task fields may still contain application-specific data. -Example output of `solve()`: - -```text -[2026-11-13 12:41:02.879 +03:00] [CaptchaClient] client initialized sdk=javascript-sdk/1.1.0 baseUrl=https://api.captcha-solver.com timeout=120000ms pollingInterval=5000ms -[2026-11-13 12:41:07.204 +03:00] [CaptchaClient] createTask ImageToTextTask -> taskId=3668 (4325ms) -REQUEST (POST https://api.captcha-solver.com/createTask): -{ - "clientKey": "[MASKED]", - "task": { - "type": "ImageToTextTask", - "body": "[base64, 41188 chars]", - "numeric": 2, - "minLength": 4, - "maxLength": 6 - } -} -RESPONSE (HTTP 200 OK, 4325ms): -{ - "errorId": 0, - "taskId": 3668 -} -[2026-11-13 12:41:13.430 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> processing (1226ms) -[2026-11-13 12:41:19.170 +03:00] [CaptchaClient] getTaskResult taskId=3668 -> ready (740ms) -REQUEST (POST https://api.captcha-solver.com/getTaskResult): -{ - "clientKey": "[MASKED]", - "taskId": 3668 -} -RESPONSE (HTTP 200 OK, 740ms): -{ - "errorId": 0, - "status": "ready", - "solution": { - "text": "wm47" - }, - "createTime": 1794515548, - "endTime": 1794515556 -} -[2026-11-13 12:41:19.171 +03:00] [CaptchaClient] SOLVE SUMMARY: - status: solved - taskId: 3668 - taskType: ImageToTextTask - elapsed: 16.292s - serverSolveTime: 8s - polls: 2 -``` - -- `REQUEST (POST ):` is the endpoint URL and JSON body the SDK sent; - `RESPONSE (HTTP ..., ms):` is the parsed server JSON after the same masking and - shortening used for request data. They are printed for - task creation, balance checks, errors, and the `ready` result; routine `processing` - polls stay on one line. -- Failed requests print the error the caller receives, e.g. - `getTaskResult taskId=3668 -> failed: ApiError ERROR_TASK_FAILED: ...`, followed by - `REQUEST (POST ):` and `RESPONSE (HTTP ..., ms):`. If the server never - answered (connection refused, timeout), the last line is - `RESPONSE: none - no response from the server (NetworkError, 36ms)`. -- A failed `solve()` ends with a `SOLVE SUMMARY` whose `status` is `not solved` and - which has an extra `error` line. -- `serverSolveTime` comes from the API's `createTime` / `endTime`; the difference from - `elapsed` is task creation plus waiting between polls. -- The API key, proxy details (`proxyAddress`, `proxyLogin`, `proxyPassword`) and `cookies` are - replaced with `[MASKED]`, base64 images with their length, and other long strings - such as solution tokens are shortened. Review the output before attaching it to a bug - report because URLs and custom task fields can still contain application-specific data. +See [examples/debug_mode.js](examples/debug_mode.js) for a runnable example. ### Worker language pool