npm package: @segress/google-search
Description: Google search automation with reCAPTCHA solving capabilities
Author: Deadgress
Latest version: 1.0.3

# @segress/google-search

Google search automation library with automatic reCAPTCHA solving capabilities using cap.guru service.

## Features

- 🔍 **Automated Google Search**: Search across multiple pages of results
- 🤖 **Automatic reCAPTCHA Solving**: Automatic captcha detection and solving using cap.guru API  
- 🥷 **Stealth Mode**: Uses puppeteer-extra-plugin-stealth to avoid bot detection
- 📊 **Position Tracking**: Track domain positions for specific keywords
- 🔄 **Recursive Monitoring**: Sequential captcha checking (no overlapping intervals)
- 🎯 **TypeScript Support**: Full TypeScript definitions included
- 🔐 **Secure API Key Management**: Support for environment variables and direct passing

## Installation

```bash
npm install @segress/google-search
```

## Configuration

### ⚠️ Required: Cap.guru API Key

This library requires a cap.guru API key for automatic captcha solving.

#### Method 1: Environment Variable (Recommended)
Create a `.env` file in your project root:
```env
CAPGURU_API_KEY=your_api_key_here
```

#### Method 2: Set Globally in Code
```typescript
import { setCapGuruApiKey } from '@segress/google-search';

// Set once at application start
setCapGuruApiKey('your_api_key_here');
```

#### Method 3: Pass to Session/Search
```typescript
// Pass to browser session
const { browser, page } = await createBrowserSession({
  capGuruApiKey: 'your_api_key_here'
});

// Or pass to specific search
await googleSearch(page, query, 3, {
  capGuruApiKey: 'your_api_key_here'
});
```

### Getting cap.guru API Key

1. Register at [cap.guru](https://cap.guru/)
2. Add funds to your account (minimum $1)
3. Copy your API key from the dashboard
4. Set it using one of the methods above

## Usage

### Basic Example

```typescript
import { createBrowserSession, googleSearch, setCapGuruApiKey } from '@segress/google-search';

async function main() {
  // Set API key (required!)
  setCapGuruApiKey('your_api_key_here');
  
  // Create browser session
  const { browser, page, stopMonitoring } = await createBrowserSession({
    debugLogging: true // Enable detailed logs
  });

  try {
    // Search Google
    const results = await googleSearch(page, 'your search query', 3, {
      debugLogging: true // Enable search-specific logs
    });

    console.log(`Found ${results.searchResults.length} results`);
    results.searchResults.forEach((result, index) => {
      console.log(`${index + 1}. ${result.title}`);
      console.log(`   URL: ${result.url}`);
    });
  } finally {
    await stopMonitoring();
    await browser.close();
  }
}

main().catch(console.error);
```

### Position Tracking Example

```typescript
import { createBrowserSession, googleSearch, setCapGuruApiKey } from '@segress/google-search';
import * as dotenv from 'dotenv';

// Load environment variables
dotenv.config();

async function trackPositions() {
  // Get API key from environment
  const apiKey = process.env.CAPGURU_API_KEY;
  if (!apiKey) {
    throw new Error('CAPGURU_API_KEY not found in .env file');
  }
  
  // Create session with API key
  const { browser, page, stopMonitoring } = await createBrowserSession({
    debugLogging: true,
    capGuruApiKey: apiKey
  });

  const targetDomain = 'example.com';
  const keywords = ['keyword1', 'keyword2', 'keyword3'];
  const results = [];
  
  for (const keyword of keywords) {
    const searchResults = await googleSearch(page, keyword, 3);
    
    // Find position of target domain
    const position = searchResults.searchResults.findIndex(r => 
      r.url.includes(targetDomain)
    ) + 1;
    
    results.push({
      keyword,
      position: position || 'Not found',
      totalResults: searchResults.resultsCount
    });
    
    // Random delay between searches (2-5 seconds)
    await new Promise(resolve => 
      setTimeout(resolve, 2000 + Math.random() * 3000)
    );
  }
  
  // Display results table
  console.table(results);
  
  await stopMonitoring();
  await browser.close();
}
```

### Advanced Usage

See `src/example.ts` for a complete example with:
- Multiple keyword checking
- Results table with statistics
- Average position calculation
- Top positions tracking

## API Reference

### `setCapGuruApiKey(apiKey: string)`

Sets the global API key for cap.guru service.

**Parameters:**
- `apiKey: string` - Your cap.guru API key

**Throws:**
- Error if API key is empty

### `createBrowserSession(options?)`

Creates a new browser session with reCAPTCHA monitoring.

**Parameters:**
- `options.debugLogging?: boolean` - Enable detailed logging (default: false)
- `options.capGuruApiKey?: string` - Cap.guru API key (overrides global setting)

**Returns:**
- `browser: Browser` - Puppeteer browser instance
- `page: Page` - Main page instance  
- `stopMonitoring: () => Promise<void>` - Function to stop captcha monitoring

### `googleSearch(page, query, pages?, options?)`

Performs Google search with automatic captcha handling.

**Parameters:**
- `page: Page` - Puppeteer page instance
- `query: string` - Search query
- `pages?: number` - Number of result pages to search (default: 1, max 100 results per page)
- `options.debugLogging?: boolean` - Enable search-specific logging
- `options.capGuruApiKey?: string` - Cap.guru API key (overrides global setting)

**Returns:**
- `hasIndexation: boolean` - Whether results were found
- `resultsCount: number` - Total number of results reported by Google
- `searchResults: Array` - Parsed search results with title, URL, and snippet
- `rawHtml?: string` - Raw HTML of search pages

## Environment Variables

Create a `.env` file in your project root:

```env
# Required: Cap.guru API key
CAPGURU_API_KEY=your_api_key_here

# Optional: Enable debug logging
DEBUG_LOGGING=true
```

## Captcha Solving Process

The library handles reCAPTCHA automatically:

1. **Detection**: Monitors page every second for captcha presence
2. **Checkbox Click**: Automatically clicks the reCAPTCHA checkbox
3. **Image Challenge**: Takes screenshot and sends to cap.guru API
4. **Solution Application**: Clicks on coordinates returned by API
5. **Multi-round Solving**: Handles dynamic captchas with multiple image sets
6. **Retry Logic**: Up to 3 attempts with captcha reload on failure

## Development

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run the example
npm run example

# Watch mode for development
npm run watch

# Type checking only
npm run typecheck
```

## Troubleshooting

### "API key not set" Error
Make sure to either:
- Create a `.env` file with `CAPGURU_API_KEY=your_key`
- Call `setCapGuruApiKey('your_key')` before using
- Pass `capGuruApiKey` option to functions

### "Failed to launch browser" Error
The library will automatically fallback to regular puppeteer if stealth mode fails.

### Captcha Not Solving
- Check your cap.guru balance
- Ensure API key is valid
- Enable `debugLogging: true` to see detailed logs

## License

MIT

## Author

Deadgress