#!/usr/bin/env node // vp – the VirginProxy command line (one file, no dependencies, Node.js 18+). // Docs: https://docs.virginproxy.com/cli/ // // vp login # store your key (~/.config/virginproxy/key, mode 600) // vp scrape https://example.com/ # the page as Markdown // vp scrape https://example.com/ --render-auto --auto-extract product --json // vp search "best trail running shoes" --scrape // // Exit codes: 0 ok, 1 the API (or the network) answered with an error, 2 wrong usage or no key. import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; export const VERSION = '0.1.0'; const DEFAULT_API = 'https://api.virginproxy.com'; const RETRY_CODES = new Set(['rate_limited', 'concurrency_limited', 'busy', 'maintenance', 'executor_unavailable', 'idempotency_in_progress', 'render_unavailable']); const FORMATS = ['raw', 'markdown', 'text', 'clean_html']; const AUTO_EXTRACT = ['product', 'article', 'job', 'review_list', 'recipe', 'event', 'organization']; const REDACT = ['email', 'phone', 'iban', 'card', 'ip']; const ENGINES = ['duckduckgo', 'google']; const TIME_RANGES = ['day', 'week', 'month', 'year']; const IMAGE_TYPES = { png: 'png', jpeg: 'jpg', webp: 'webp' }; const KEY_RE = /^vp_(live|test)_[A-Za-z0-9_-]{8,}$/; // --------------------------------------------------------------------------------------------- // Errors class UsageError extends Error {} class ApiError extends Error { constructor(status, body, headers) { const e = body?.error || {}; super(e.message || `The API answered with HTTP ${status}.`); this.status = status; this.code = e.code || `http_${status}`; this.retryAfterMs = e.retry_after_ms ?? (headers?.get?.('retry-after') ? Number(headers.get('retry-after')) * 1000 : undefined); this.requestId = body?.request_id || headers?.get?.('x-request-id') || headers?.get?.('x-vp-request-id') || undefined; this.body = body && body.error ? body : { error: { code: this.code, message: this.message } }; } } // --------------------------------------------------------------------------------------------- // Key storage export function configDir(env = process.env) { const base = env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config'); return path.join(base, 'virginproxy'); } const keyFile = (env) => path.join(configDir(env), 'key'); function readKey(env) { if (env.VP_API_KEY) return { key: env.VP_API_KEY.trim(), source: 'VP_API_KEY' }; if (env.VP_KEY) return { key: env.VP_KEY.trim(), source: 'VP_KEY' }; try { const key = fs.readFileSync(keyFile(env), 'utf8').trim(); if (key) return { key, source: keyFile(env) }; } catch { /* no file */ } return null; } function writeKey(env, key) { const dir = configDir(env); fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); const file = keyFile(env); fs.writeFileSync(file, `${key}\n`, { mode: 0o600 }); fs.chmodSync(file, 0o600); // also when the file existed with wider rights return file; } const maskKey = (key) => `${key.slice(0, key.indexOf('_', 3) + 1)}…${key.slice(-4)}`; // --------------------------------------------------------------------------------------------- // HTTP const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const qs = (query = {}) => { const p = new URLSearchParams(); for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null && v !== false) p.append(k, String(v)); const s = p.toString(); return s ? `?${s}` : ''; }; class Client { constructor({ key, baseUrl, timeoutMs, maxRetries, onRetry }) { this.key = key; this.baseUrl = baseUrl.replace(/\/+$/, ''); this.timeoutMs = timeoutMs; this.maxRetries = maxRetries; this.onRetry = onRetry; } /** One call. JSON in and out unless raw (then the Response). Short-lived limits are retried. */ async call(method, p, { body, query, raw = false, timeoutMs = this.timeoutMs, headers = {} } = {}) { for (let attempt = 0; ; attempt++) { let res; try { res = await fetch(`${this.baseUrl}${p}${qs(query)}`, { method, headers: { Authorization: `Bearer ${this.key}`, 'User-Agent': `virginproxy-cli/${VERSION}`, Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers, }, body: body !== undefined ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(timeoutMs), }); } catch (err) { const code = err?.name === 'TimeoutError' ? 'client_timeout' : 'network_error'; const msg = code === 'client_timeout' ? `No answer within ${Math.round(timeoutMs / 1000)} s.` : `Could not reach ${this.baseUrl}: ${err?.cause?.code || err?.message || err}`; throw new ApiError(0, { error: { code, message: msg } }); } if (res.ok) { if (raw) return res; if (res.status === 204) return null; const text = await res.text(); return text ? JSON.parse(text) : null; } let data = null; try { data = await res.json(); } catch { /* not JSON */ } const err = new ApiError(res.status, data, res.headers); if (RETRY_CODES.has(err.code) && attempt < this.maxRetries) { const wait = Math.min(30000, Math.max(250, err.retryAfterMs ?? 1000)); this.onRetry?.(err, wait, attempt + 1); await sleep(wait); continue; } throw err; } } } // --------------------------------------------------------------------------------------------- // Argument parsing // Flag types: bool, str, int, num, list (repeatable and/or comma separated), json. const GLOBAL_FLAGS = { json: 'bool', help: 'bool', version: 'bool', quiet: 'bool', timeout: 'int', retries: 'int', }; const ALIASES = { h: 'help', V: 'version', o: 'output', q: 'quiet', n: 'limit' }; export function parseArgs(argv, spec) { const flags = {}; const positional = []; const all = { ...GLOBAL_FLAGS, ...spec }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === '--') { positional.push(...argv.slice(i + 1)); break; } if (a === '-' || !a.startsWith('-')) { positional.push(a); continue; } let name; let value; if (a.startsWith('--')) { const eq = a.indexOf('='); name = eq > 0 ? a.slice(2, eq) : a.slice(2); if (eq > 0) value = a.slice(eq + 1); } else { name = ALIASES[a.slice(1)]; if (!name) throw new UsageError(`Unknown option ${a}.`); } let type = all[name]; let negated = false; if (!type && name.startsWith('no-') && all[name.slice(3)] === 'bool') { name = name.slice(3); type = 'bool'; negated = true; } if (!type) throw new UsageError(`Unknown option --${name}.`); const key = name.replace(/-([a-z])/g, (_, ch) => ch.toUpperCase()); if (type === 'bool') { if (value !== undefined) throw new UsageError(`--${name} takes no value.`); flags[key] = !negated; continue; } if (value === undefined) { if (i + 1 >= argv.length) throw new UsageError(`--${name} needs a value.`); value = argv[++i]; } if (type === 'int' || type === 'num') { const n = Number(value); if (!Number.isFinite(n) || (type === 'int' && !Number.isInteger(n))) throw new UsageError(`--${name} must be a${type === 'int' ? 'n integer' : ' number'}, got "${value}".`); flags[key] = n; } else if (type === 'list') { flags[key] = [...(flags[key] || []), ...String(value).split(',').map((s) => s.trim()).filter(Boolean)]; } else if (type === 'json') { flags[key] = parseJsonArg(value, `--${name}`); } else { flags[key] = value; } } return { flags, positional }; } function parseJsonArg(value, what) { let text = value; if (value === '-') text = fs.readFileSync(0, 'utf8'); else if (value.startsWith('@')) { try { text = fs.readFileSync(value.slice(1), 'utf8'); } catch (e) { throw new UsageError(`${what}: cannot read ${value.slice(1)} (${e.code || e.message}).`); } } try { return JSON.parse(text); } catch { throw new UsageError(`${what} must be JSON (or @file.json, or - for stdin).`); } } const oneOf = (name, value, allowed) => { if (value !== undefined && !allowed.includes(value)) throw new UsageError(`--${name} must be one of ${allowed.join(', ')}.`); return value; }; const needUrl = (positional, what = 'url') => { const u = positional[0]; if (!u) throw new UsageError(`Missing <${what}>.`); if (what === 'url' && !/^https?:\/\//i.test(u)) throw new UsageError(` must start with http:// or https:// (got "${u}").`); return u; }; const compact = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && !(Array.isArray(v) && v.length === 0) && !(v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0))); // --------------------------------------------------------------------------------------------- // Output class Out { constructor({ json, quiet, stdout = process.stdout, stderr = process.stderr }) { this.json = json; this.quiet = quiet; this.stdout = stdout; this.stderr = stderr; } data(obj) { this.stdout.write(`${JSON.stringify(obj, null, 2)}\n`); } line(text = '') { this.stdout.write(`${text}\n`); } /** Side information (credits, file written…) on stderr, so stdout stays clean for pipes. */ info(text) { if (!this.quiet && !this.json) this.stderr.write(`${text}\n`); } warn(text) { if (!this.quiet) this.stderr.write(`vp: ${text}\n`); } } const creditsText = (n) => `${n} credit${n === 1 ? '' : 's'}`; function costLine(r) { const parts = []; if (r.status !== undefined && r.status !== null) parts.push(`status ${r.status}`); if (r.strategy) parts.push(`strategy ${r.strategy}`); if (r.tokens !== undefined) parts.push(`≈${r.tokens} tokens`); if (r.cost?.credits !== undefined) parts.push(creditsText(r.cost.credits)); if (r.cost?.credits_used !== undefined && r.cost?.credits_included !== undefined) parts.push(`${r.cost.credits_used}/${r.cost.credits_included} used this period`); if (r.cached) parts.push('from cache'); if (r.id) parts.push(r.id); return parts.join(' · '); } function writeFileOrStdout(out, file, buf) { if (file === '-') { out.stdout.write(buf); return '-'; } fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true }); fs.writeFileSync(file, buf); return file; } const hostOf = (u) => { try { return new URL(u).hostname || 'page'; } catch { return 'page'; } }; // --------------------------------------------------------------------------------------------- // Request building (exported for tests) export function buildScrapeBody(url, f) { if (f.render && f.renderAuto) throw new UsageError('Use either --render or --render-auto, not both.'); oneOf('format', f.format, FORMATS); oneOf('auto-extract', f.autoExtract, AUTO_EXTRACT); let redact; if (f.redact) { redact = f.redact.includes('all') || f.redact.includes('true') ? true : f.redact; if (redact !== true) for (const r of redact) if (!REDACT.includes(r)) throw new UsageError(`--redact takes ${REDACT.join(', ')} or all.`); } const renderOpts = compact({ wait_for: f.waitFor, wait_until: f.waitUntil, wait_ms: f.waitMs, scroll: f.scroll, trace: f.trace || undefined, screenshot: f.screenshot || undefined }); if (Object.keys(renderOpts).length && !f.render && !f.renderAuto) throw new UsageError('--wait-for, --wait-until, --wait-ms, --scroll, --trace and --screenshot need --render or --render-auto.'); const format = f.format ?? 'markdown'; const formatOptions = compact({ include_selector: f.includeSelector, exclude_selector: f.excludeSelector, images: f.images, links: f.links, max_pages: f.maxPages }); if (Object.keys(formatOptions).length && format === 'raw') throw new UsageError('--include-selector, --exclude-selector, --no-images, --no-links and --max-pages need --format markdown, text or clean_html.'); const body = compact({ format, main_content: f.mainContent ?? (format === 'raw' ? undefined : true), format_options: formatOptions, render: f.renderAuto ? 'auto' : f.render ? (Object.keys(renderOpts).length ? renderOpts : true) : undefined, render_options: f.renderAuto && Object.keys(renderOpts).length ? renderOpts : undefined, auto_extract: f.autoExtract, redact, parse: f.parse, extract: f.extract, browser: f.browser, locale: f.locale, session: f.session, fresh_ip: f.freshIp, preset: f.preset, max_credits: f.maxCredits, tag: f.tag, }); return { ...body, ...(f.data || {}), url }; } export function buildSearchBody(query, f) { oneOf('engine', f.engine, ENGINES); oneOf('time-range', f.timeRange, TIME_RANGES); oneOf('format', f.format, FORMATS); if ((f.format || f.render || f.renderAuto) && !f.scrape) throw new UsageError('--format, --render and --render-auto only apply with --scrape.'); if (f.render && f.renderAuto) throw new UsageError('Use either --render or --render-auto, not both.'); const scrape = f.scrape ? compact({ format: f.format ?? 'markdown', main_content: (f.format ?? 'markdown') === 'raw' ? undefined : true, render: f.renderAuto ? 'auto' : f.render ? true : undefined }) : undefined; return compact({ query, engine: f.engine, limit: f.limit, language: f.language, country: f.country, time_range: f.timeRange, include_domains: f.includeDomain, exclude_domains: f.excludeDomain, scrape: scrape ? { ...scrape, ...(f.scrapeOptions || {}) } : undefined, max_credits: f.maxCredits, tag: f.tag, }); } // --------------------------------------------------------------------------------------------- // Commands const SCRAPE_FLAGS = { render: 'bool', 'render-auto': 'bool', format: 'str', 'main-content': 'bool', 'auto-extract': 'str', redact: 'list', 'include-selector': 'str', 'exclude-selector': 'str', images: 'bool', links: 'bool', 'max-pages': 'int', 'wait-for': 'str', 'wait-until': 'str', 'wait-ms': 'int', scroll: 'int', trace: 'bool', screenshot: 'bool', parse: 'list', extract: 'json', browser: 'str', locale: 'str', session: 'str', 'fresh-ip': 'bool', preset: 'str', 'max-credits': 'int', tag: 'str', data: 'json', output: 'str', }; function bodyText(r) { if (typeof r.body !== 'string') return ''; return r.body_encoding === 'base64' ? Buffer.from(r.body, 'base64') : r.body; } const COMMANDS = { scrape: { usage: 'vp scrape [options]', summary: 'Fetch one page (default: Markdown of its main content).', flags: SCRAPE_FLAGS, help: `Options: --render Load the page in a browser (adds 9 credits). --render-auto Try without a browser first; use one only if the page needs it. Only the answer you get is charged. --format markdown (default), text, clean_html or raw. --no-main-content Keep the whole page, not only its main content. --auto-extract product, article, job, review_list, recipe, event or organization. --redact email,phone,iban,card,ip or all – blank these out in the answer. --include-selector / --exclude-selector Narrow what is converted. --no-images / --no-links Leave images / links out of Markdown. --max-pages For PDF/Office documents: pages to convert (1–500). --wait-for , --wait-until , --wait-ms , --scroll , --trace, --screenshot Browser options (need --render/--render-auto). --parse e.g. metadata,links,headings (or serp). --extract Extraction rules, e.g. '{"title":"h1"}' or @rules.json. --browser, --locale, --session, --fresh-ip, --preset --max-credits This request never costs more. --tag