UNPKG

anil-brd-typescript-sdk

Version:

TypeScript SDK for Bright Data APIs - Web Unlocker, SERP, and Scraper APIs

70 lines (69 loc) 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BrightData = void 0; const client_1 = require("./client"); const config_1 = require("./config"); const error_1 = require("./error"); class BrightData { constructor(apiKey, config) { if (!apiKey) { throw new error_1.BrightDataError('API key is required', undefined, undefined, undefined, 'Get your key at https://dashboard.brightdata.com/api-keys', 'https://brightdata.com/docs/api-keys'); } this.config = { ...config_1.DEFAULT_CONFIG, ...config, apiKey }; this.client = new client_1.BrightDataClient({ apiKey: this.config.apiKey, zone: 'web_unlocker1', timeout: 30000 }); } // Simple Interface Methods async getHtml(url, country) { return this.unlock(url, { format: 'raw', country }); } async getMarkdown(url, country) { return this.unlock(url, { data_format: 'markdown', country }); } async getScreenshot(url, country) { return this.unlock(url, { data_format: 'screenshot', country }); } async getJson(url, country) { return this.unlock(url, { format: 'json', country }); } // Unified unlock method that works with all options async unlock(url, options) { try { if (!url) { throw new error_1.BrightDataError('URL is required'); } // Only merge non-data_format options from config const { data_format, ...configWithoutDataFormat } = this.config; const mergedOptions = { ...configWithoutDataFormat, ...options }; const requestOptions = { url, ...(mergedOptions.country && { country: mergedOptions.country }), format: mergedOptions.format || 'raw', method: mergedOptions.method || 'GET', ...((options === null || options === void 0 ? void 0 : options.data_format) && { data_format: options.data_format }) }; const result = await this.client.webUnlocker.unlock(url, requestOptions); // Return just the content for simple interface if ((options === null || options === void 0 ? void 0 : options.format) === 'raw' || (options === null || options === void 0 ? void 0 : options.format) === 'json') { return result.content; } // Return full response for other cases return result; } catch (error) { if (error instanceof error_1.BrightDataError) { throw error; } const err = error; throw new error_1.BrightDataError(`Failed to unlock website: ${err.message || 'Unknown error'}`, undefined, undefined, undefined, 'Try using a different country or format', 'https://brightdata.com/docs/troubleshooting'); } } } exports.BrightData = BrightData;