iploop 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 IPLoop
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,8 +1,11 @@
1
1
  # IPLoop Node.js SDK
2
2
 
3
- Residential proxy SDK — route requests through millions of real devices across 111+ countries.
3
+ Official Node.js SDK for [IPLoop](https://iploop.io) residential proxy service with millions of real IPs worldwide.
4
4
 
5
- ## Install
5
+ [![npm version](https://img.shields.io/npm/v/iploop.svg)](https://www.npmjs.com/package/iploop)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Installation
6
9
 
7
10
  ```bash
8
11
  npm install iploop
@@ -10,66 +13,192 @@ npm install iploop
10
13
 
11
14
  ## Quick Start
12
15
 
13
- ```javascript
14
- const IPLoop = require('iploop');
16
+ ```typescript
17
+ import { IPLoopClient } from 'iploop';
15
18
 
16
- const ip = new IPLoop('your-api-key');
19
+ const client = new IPLoopClient({ apiKey: 'your-api-key' });
20
+ const response = await client.get('https://httpbin.org/ip');
21
+ console.log(response.data);
22
+ ```
17
23
 
18
- // Fetch any URL through a residential proxy
19
- const res = await ip.get('https://httpbin.org/ip');
20
- console.log(res.body);
24
+ ## Features
21
25
 
22
- // Target a specific country
23
- const de = await ip.get('https://example.com', { country: 'DE' });
26
+ - **Residential proxies** millions of real IPs across 195+ countries
27
+ - **Geographic targeting** country and city-level precision
28
+ - **Sticky sessions** — keep the same IP across multiple requests
29
+ - **Auto-retry** — failed requests automatically retry with fresh IPs
30
+ - **Smart headers** — Chrome fingerprint headers matched to target country
31
+ - **HTTP & SOCKS5** — both protocols supported
32
+ - **Concurrent fetching** — batch requests with configurable concurrency
33
+ - **TypeScript** — full type definitions included
24
34
 
25
- // POST request
26
- const post = await ip.post('https://api.example.com/data', {
27
- body: JSON.stringify({ key: 'value' }),
28
- headers: { 'Content-Type': 'application/json' }
35
+ ## Authentication
36
+
37
+ Get your API key from the [IPLoop Dashboard](https://iploop.io/dashboard).
38
+
39
+ ```typescript
40
+ const client = new IPLoopClient({
41
+ apiKey: 'your-api-key',
42
+ country: 'US', // default country for all requests
43
+ debug: true, // enable request logging
29
44
  });
30
45
  ```
31
46
 
47
+ ## Geographic Targeting
48
+
49
+ ```typescript
50
+ // Target a specific country
51
+ const resp = await client.get('https://example.com', { country: 'DE' });
52
+
53
+ // Target a specific city
54
+ const resp = await client.get('https://example.com', { country: 'US', city: 'miami' });
55
+ ```
56
+
32
57
  ## Sticky Sessions
33
58
 
34
- Keep the same IP across multiple requests:
59
+ Keep the same proxy IP across multiple requests:
60
+
61
+ ```typescript
62
+ const session = client.session(undefined, 'US', 'newyork');
35
63
 
36
- ```javascript
37
- const session = ip.session({ country: 'US', city: 'newyork' });
38
64
  const page1 = await session.get('https://site.com/page1'); // same IP
39
65
  const page2 = await session.get('https://site.com/page2'); // same IP
40
66
  ```
41
67
 
42
- ## Geo-Targeting
68
+ ## HTTP Methods
69
+
70
+ ```typescript
71
+ // GET
72
+ const resp = await client.get('https://httpbin.org/get');
73
+
74
+ // POST
75
+ const resp = await client.post('https://httpbin.org/post', { key: 'value' });
76
+
77
+ // PUT
78
+ const resp = await client.put('https://httpbin.org/put', { key: 'value' });
79
+
80
+ // DELETE
81
+ const resp = await client.delete('https://httpbin.org/delete');
82
+ ```
83
+
84
+ ## Concurrent Fetching
85
+
86
+ Fetch multiple URLs in parallel:
43
87
 
44
- ```javascript
45
- const ip = new IPLoop('key', { country: 'JP' }); // All requests through Japan
46
- // Or per-request:
47
- const res = await ip.get('https://example.com', { country: 'GB' });
88
+ ```typescript
89
+ const results = await client.fetchAll([
90
+ 'https://example.com/page1',
91
+ 'https://example.com/page2',
92
+ 'https://example.com/page3',
93
+ ], { country: 'US' }, 10); // 10 concurrent workers
94
+
95
+ console.log(results);
96
+ // [{ url: '...', status: 200, success: true, sizeKb: 42 }, ...]
48
97
  ```
49
98
 
50
- ## TypeScript
99
+ ## SOCKS5 Support
100
+
101
+ ```typescript
102
+ // Use SOCKS5 protocol
103
+ const resp = await client.get('https://example.com', { protocol: 'socks5' });
104
+
105
+ // Get SOCKS5 proxy URL for use with other libraries
106
+ const proxyUrl = client.getProxyUrl({ protocol: 'socks5', country: 'US' });
107
+ ```
108
+
109
+ ## Use with Other Libraries
110
+
111
+ Get the proxy URL or agent for use with Puppeteer, Playwright, Got, etc:
112
+
113
+ ```typescript
114
+ // Get proxy URL string
115
+ const proxyUrl = client.getProxyUrl({ country: 'US', session: 'my-session' });
116
+ // → http://your-api-key:country-us:session-my-session@gateway.iploop.io:8880
117
+
118
+ // Get axios-compatible agent
119
+ const agent = client.getProxyAgent({ country: 'DE' });
120
+
121
+ // Use with Puppeteer
122
+ const browser = await puppeteer.launch({
123
+ args: [`--proxy-server=${client.getProxyUrl({ country: 'US' })}`],
124
+ });
125
+ ```
126
+
127
+ ## Chrome Fingerprinting
128
+
129
+ Every request automatically includes 14 Chrome desktop headers matched to the target country. You can also get them directly:
130
+
131
+ ```typescript
132
+ const headers = client.fingerprint('JP');
133
+ // Full Chrome headers with Japanese locale
134
+ ```
135
+
136
+ ## Request Statistics
137
+
138
+ ```typescript
139
+ // After making requests...
140
+ console.log(client.getStats());
141
+ // { requests: 10, success: 9, errors: 1, totalTime: 23500, avgTime: 2350, successRate: 90.0 }
142
+ ```
143
+
144
+ ## API Methods
145
+
146
+ ```typescript
147
+ // Check bandwidth usage
148
+ const usage = await client.getUsage();
149
+
150
+ // Service status
151
+ const status = await client.getStatus();
152
+
153
+ // Available countries
154
+ const countries = await client.getCountries();
155
+ ```
156
+
157
+ ## Error Handling
158
+
159
+ ```typescript
160
+ import { AuthenticationError, QuotaExceededError, ProxyError, RateLimitError } from 'iploop';
161
+
162
+ try {
163
+ const resp = await client.get('https://example.com');
164
+ } catch (err) {
165
+ if (err instanceof AuthenticationError) {
166
+ console.log('Invalid API key');
167
+ } else if (err instanceof QuotaExceededError) {
168
+ console.log('Upgrade at https://iploop.io/pricing');
169
+ } else if (err instanceof ProxyError) {
170
+ console.log('Proxy connection failed');
171
+ } else if (err instanceof RateLimitError) {
172
+ console.log('Rate limited, retry after:', err.retryAfter);
173
+ }
174
+ }
175
+ ```
51
176
 
52
- Full TypeScript support included:
177
+ ## Debug Mode
53
178
 
54
179
  ```typescript
55
- import IPLoop from 'iploop';
56
- const ip = new IPLoop('your-api-key', { country: 'US' });
180
+ const client = new IPLoopClient({ apiKey: 'your-key', debug: true });
181
+ // Logs: IPLoop: GET https://example.com → 200 (450ms) country=US session=abc123
57
182
  ```
58
183
 
59
- ## API
184
+ ## Configuration
60
185
 
61
- - `ip.get(url, options?)` GET request
62
- - `ip.post(url, options?)` — POST request
63
- - `ip.put(url, options?)` PUT request
64
- - `ip.delete(url, options?)` DELETE request
65
- - `ip.fetch(url, options?)` Custom request
66
- - `ip.session(options?)` Create sticky session
67
- - `ip.countries()` List available countries
186
+ | Option | Default | Description |
187
+ |--------|---------|-------------|
188
+ | `apiKey` | *required* | Your IPLoop API key |
189
+ | `proxyHost` | `gateway.iploop.io` | Proxy gateway hostname |
190
+ | `httpPort` | `8880` | HTTP proxy port |
191
+ | `socksPort` | `1080` | SOCKS5 proxy port |
192
+ | `timeout` | `30000` | Request timeout in ms |
193
+ | `country` | — | Default target country |
194
+ | `city` | — | Default target city |
195
+ | `debug` | `false` | Enable debug logging |
68
196
 
69
197
  ## Links
70
198
 
71
- - Website: [iploop.io](https://iploop.io)
72
- - Twitter: [@iploop_io](https://x.com/iploop_io)
199
+ - **Website**: [iploop.io](https://iploop.io)
200
+ - **Dashboard**: [iploop.io/dashboard](https://iploop.io/dashboard)
201
+ - **Documentation**: [docs.iploop.io](https://docs.iploop.io)
73
202
 
74
203
  ## License
75
204
 
@@ -0,0 +1,155 @@
1
+ /**
2
+ * IPLoop Node.js SDK
3
+ * Official SDK for IPLoop residential proxy service
4
+ * https://iploop.io
5
+ */
6
+ import { AxiosRequestConfig, AxiosResponse } from 'axios';
7
+ import { SocksProxyAgent } from 'socks-proxy-agent';
8
+ import { HttpsProxyAgent } from 'https-proxy-agent';
9
+ export interface IPLoopConfig {
10
+ /** Your IPLoop API key */
11
+ apiKey: string;
12
+ /** Proxy gateway hostname (default: gateway.iploop.io) */
13
+ proxyHost?: string;
14
+ /** HTTP proxy port (default: 8880) */
15
+ httpPort?: number;
16
+ /** SOCKS5 proxy port (default: 1080) */
17
+ socksPort?: number;
18
+ /** Management API URL (default: https://gateway.iploop.io:9443) */
19
+ apiUrl?: string;
20
+ /** Default request timeout in ms (default: 30000) */
21
+ timeout?: number;
22
+ /** Default target country code */
23
+ country?: string;
24
+ /** Default target city */
25
+ city?: string;
26
+ /** Enable debug logging */
27
+ debug?: boolean;
28
+ }
29
+ export interface ProxyOptions {
30
+ /** Target country code (e.g. "US", "DE", "JP") */
31
+ country?: string;
32
+ /** Target city (e.g. "miami", "london") */
33
+ city?: string;
34
+ /** Session ID for sticky sessions (same IP across requests) */
35
+ session?: string;
36
+ /** Proxy protocol (default: "http") */
37
+ protocol?: 'http' | 'socks5';
38
+ /** Enable JavaScript rendering */
39
+ render?: boolean;
40
+ }
41
+ export interface FetchResult {
42
+ url: string;
43
+ status: number;
44
+ success: boolean;
45
+ sizeKb: number;
46
+ error?: string;
47
+ }
48
+ export interface UsageSummary {
49
+ totalBytes: number;
50
+ totalRequests: number;
51
+ planLimitBytes: number;
52
+ usagePercent: number;
53
+ estimatedCost: number;
54
+ }
55
+ export interface DailyUsage {
56
+ date: string;
57
+ bytesTransferred: number;
58
+ requestCount: number;
59
+ successRate: number;
60
+ }
61
+ export declare class IPLoopError extends Error {
62
+ statusCode?: number | undefined;
63
+ response?: any | undefined;
64
+ constructor(message: string, statusCode?: number | undefined, response?: any | undefined);
65
+ }
66
+ export declare class AuthenticationError extends IPLoopError {
67
+ constructor(message?: string);
68
+ }
69
+ export declare class RateLimitError extends IPLoopError {
70
+ retryAfter?: number | undefined;
71
+ constructor(message?: string, retryAfter?: number | undefined);
72
+ }
73
+ export declare class QuotaExceededError extends IPLoopError {
74
+ constructor(message?: string);
75
+ }
76
+ export declare class ProxyError extends IPLoopError {
77
+ constructor(message?: string);
78
+ }
79
+ export declare class StickySession {
80
+ private readonly client;
81
+ readonly sessionId: string;
82
+ readonly country?: string;
83
+ readonly city?: string;
84
+ constructor(client: IPLoopClient, sessionId: string, country?: string, city?: string);
85
+ get<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
86
+ post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
87
+ }
88
+ export declare class IPLoopClient {
89
+ private readonly apiKey;
90
+ private readonly proxyHost;
91
+ private readonly httpPort;
92
+ private readonly socksPort;
93
+ private readonly apiUrl;
94
+ private readonly timeout;
95
+ private readonly defaultCountry?;
96
+ private readonly defaultCity?;
97
+ private readonly debug;
98
+ private readonly apiClient;
99
+ private stats;
100
+ constructor(config: IPLoopConfig);
101
+ private buildAuth;
102
+ /**
103
+ * Get proxy URL for use with other HTTP libraries (e.g. puppeteer, playwright, got).
104
+ */
105
+ getProxyUrl(options?: ProxyOptions): string;
106
+ /**
107
+ * Get an HTTP/SOCKS agent for use with axios or other libraries.
108
+ */
109
+ getProxyAgent(options?: ProxyOptions): HttpsProxyAgent<string> | SocksProxyAgent;
110
+ /**
111
+ * Fetch a URL through the residential proxy with auto-retry and smart headers.
112
+ */
113
+ fetch<T = any>(url: string, options?: ProxyOptions, config?: AxiosRequestConfig, retries?: number): Promise<AxiosResponse<T>>;
114
+ /** GET request through proxy. */
115
+ get<T = any>(url: string, options?: ProxyOptions, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
116
+ /** POST request through proxy. */
117
+ post<T = any>(url: string, data?: any, options?: ProxyOptions, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
118
+ /** PUT request through proxy. */
119
+ put<T = any>(url: string, data?: any, options?: ProxyOptions, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
120
+ /** DELETE request through proxy. */
121
+ delete<T = any>(url: string, options?: ProxyOptions, config?: AxiosRequestConfig): Promise<AxiosResponse<T>>;
122
+ /**
123
+ * Create a sticky session — all requests reuse the same proxy IP.
124
+ */
125
+ session(sessionId?: string, country?: string, city?: string): StickySession;
126
+ /**
127
+ * Fetch multiple URLs concurrently through the proxy.
128
+ */
129
+ fetchAll(urls: string[], options?: ProxyOptions, concurrency?: number): Promise<FetchResult[]>;
130
+ /**
131
+ * Get request statistics.
132
+ */
133
+ getStats(): {
134
+ avgTime: number;
135
+ successRate: number;
136
+ requests: number;
137
+ success: number;
138
+ errors: number;
139
+ totalTime: number;
140
+ };
141
+ /**
142
+ * Get Chrome desktop fingerprint headers for a country.
143
+ */
144
+ fingerprint(country?: string): Record<string, string>;
145
+ /** Check bandwidth usage and quota. */
146
+ getUsage(): Promise<UsageSummary>;
147
+ /** Check service status. */
148
+ getStatus(): Promise<any>;
149
+ /** List available proxy countries. */
150
+ getCountries(): Promise<any>;
151
+ }
152
+ declare const SDK_VERSION = "1.0.1";
153
+ export { SDK_VERSION };
154
+ export default IPLoopClient;
155
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAc,EAAiB,kBAAkB,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKpD,MAAM,WAAW,YAAY;IAC3B,0BAA0B;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,0DAA0D;IAC1D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sCAAsC;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wCAAwC;IACxC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mEAAmE;IACnE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0BAA0B;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,2BAA2B;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IAC3B,kDAAkD;IAClD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2CAA2C;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uCAAuC;IACvC,QAAQ,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC7B,kCAAkC;IAClC,MAAM,CAAC,EAA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W,CAAC,OAAO,SAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAMnD,uCAAuC;IACjC,QAAQ,IAAI,OAAO,CAAC,YAAY,CAAC;IAKvC,4BAA4B;IACtB,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC;IAK/B,sCAAsC;IAChC,YAAY,IAAI,OAAO,CAAC,GAAG,CAAC;CAInC;AAID,QAAA,MAAM,WAAW,UAAU,CAAC;AAsB5B,OAAO,EAAE,WAAW,EAAE,CAAC;AACvB,eAAe,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,320 @@
1
+ "use strict";
2
+ /**
3
+ * IPLoop Node.js SDK
4
+ * Official SDK for IPLoop residential proxy service
5
+ * https://iploop.io
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.SDK_VERSION = exports.IPLoopClient = exports.StickySession = exports.ProxyError = exports.QuotaExceededError = exports.RateLimitError = exports.AuthenticationError = exports.IPLoopError = void 0;
12
+ const axios_1 = __importDefault(require("axios"));
13
+ const socks_proxy_agent_1 = require("socks-proxy-agent");
14
+ const https_proxy_agent_1 = require("https-proxy-agent");
15
+ const crypto_1 = require("crypto");
16
+ // ── Errors ───────────────────────────────────────────────────
17
+ class IPLoopError extends Error {
18
+ constructor(message, statusCode, response) {
19
+ super(message);
20
+ this.statusCode = statusCode;
21
+ this.response = response;
22
+ this.name = 'IPLoopError';
23
+ }
24
+ }
25
+ exports.IPLoopError = IPLoopError;
26
+ class AuthenticationError extends IPLoopError {
27
+ constructor(message = 'Invalid API key') {
28
+ super(message, 401);
29
+ this.name = 'AuthenticationError';
30
+ }
31
+ }
32
+ exports.AuthenticationError = AuthenticationError;
33
+ class RateLimitError extends IPLoopError {
34
+ constructor(message = 'Rate limit exceeded', retryAfter) {
35
+ super(message, 429);
36
+ this.retryAfter = retryAfter;
37
+ this.name = 'RateLimitError';
38
+ }
39
+ }
40
+ exports.RateLimitError = RateLimitError;
41
+ class QuotaExceededError extends IPLoopError {
42
+ constructor(message = 'Quota exceeded. Upgrade at https://iploop.io/pricing') {
43
+ super(message, 402);
44
+ this.name = 'QuotaExceededError';
45
+ }
46
+ }
47
+ exports.QuotaExceededError = QuotaExceededError;
48
+ class ProxyError extends IPLoopError {
49
+ constructor(message = 'Proxy connection failed') {
50
+ super(message);
51
+ this.name = 'ProxyError';
52
+ }
53
+ }
54
+ exports.ProxyError = ProxyError;
55
+ // ── Sticky Session ───────────────────────────────────────────
56
+ class StickySession {
57
+ constructor(client, sessionId, country, city) {
58
+ this.client = client;
59
+ this.sessionId = sessionId;
60
+ this.country = country;
61
+ this.city = city;
62
+ }
63
+ async get(url, config) {
64
+ return this.client.get(url, { country: this.country, city: this.city, session: this.sessionId }, config);
65
+ }
66
+ async post(url, data, config) {
67
+ return this.client.post(url, data, { country: this.country, city: this.city, session: this.sessionId }, config);
68
+ }
69
+ }
70
+ exports.StickySession = StickySession;
71
+ // ── Chrome Fingerprint ───────────────────────────────────────
72
+ const CHROME_VERSIONS = ['120.0.0.0', '121.0.0.0', '122.0.0.0', '123.0.0.0', '124.0.0.0', '125.0.0.0', '126.0.0.0'];
73
+ const LANG_MAP = {
74
+ US: 'en-US,en;q=0.9', GB: 'en-GB,en;q=0.9', DE: 'de-DE,de;q=0.9,en;q=0.8',
75
+ FR: 'fr-FR,fr;q=0.9,en;q=0.8', JP: 'ja-JP,ja;q=0.9,en;q=0.8', BR: 'pt-BR,pt;q=0.9,en;q=0.8',
76
+ KR: 'ko-KR,ko;q=0.9,en;q=0.8', IN: 'en-IN,en;q=0.9,hi;q=0.8', ES: 'es-ES,es;q=0.9,en;q=0.8',
77
+ IT: 'it-IT,it;q=0.9,en;q=0.8', NL: 'nl-NL,nl;q=0.9,en;q=0.8', AU: 'en-AU,en;q=0.9',
78
+ };
79
+ function chromeFingerprint(country = 'US') {
80
+ const ver = CHROME_VERSIONS[Math.floor(Math.random() * CHROME_VERSIONS.length)];
81
+ const major = ver.split('.')[0];
82
+ const lang = LANG_MAP[country.toUpperCase()] || 'en-US,en;q=0.9';
83
+ return {
84
+ 'User-Agent': `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${ver} Safari/537.36`,
85
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
86
+ 'Accept-Language': lang,
87
+ 'Accept-Encoding': 'gzip, deflate, br',
88
+ 'Connection': 'keep-alive',
89
+ 'Upgrade-Insecure-Requests': '1',
90
+ 'Sec-Fetch-Dest': 'document',
91
+ 'Sec-Fetch-Mode': 'navigate',
92
+ 'Sec-Fetch-Site': 'none',
93
+ 'Sec-Fetch-User': '?1',
94
+ 'Sec-Ch-Ua': `"Chromium";v="${major}", "Google Chrome";v="${major}", "Not-A.Brand";v="99"`,
95
+ 'Sec-Ch-Ua-Mobile': '?0',
96
+ 'Sec-Ch-Ua-Platform': '"Windows"',
97
+ 'Cache-Control': 'max-age=0',
98
+ };
99
+ }
100
+ // ── Retryable statuses ───────────────────────────────────────
101
+ const RETRYABLE_STATUSES = new Set([403, 407, 429, 500, 502, 503, 504]);
102
+ function newSessionId() {
103
+ return (0, crypto_1.randomUUID)().replace(/-/g, '').slice(0, 16);
104
+ }
105
+ function sleep(ms) {
106
+ return new Promise(resolve => setTimeout(resolve, ms));
107
+ }
108
+ // ── Main Client ──────────────────────────────────────────────
109
+ class IPLoopClient {
110
+ constructor(config) {
111
+ this.stats = { requests: 0, success: 0, errors: 0, totalTime: 0 };
112
+ if (!config.apiKey)
113
+ throw new AuthenticationError('API key is required');
114
+ this.apiKey = config.apiKey;
115
+ this.proxyHost = config.proxyHost || 'gateway.iploop.io';
116
+ this.httpPort = config.httpPort || 8880;
117
+ this.socksPort = config.socksPort || 1080;
118
+ this.apiUrl = config.apiUrl || 'https://gateway.iploop.io:9443';
119
+ this.timeout = config.timeout || 30000;
120
+ this.defaultCountry = config.country;
121
+ this.defaultCity = config.city;
122
+ this.debug = config.debug || false;
123
+ this.apiClient = axios_1.default.create({
124
+ baseURL: this.apiUrl,
125
+ timeout: this.timeout,
126
+ headers: {
127
+ 'Authorization': `Bearer ${this.apiKey}`,
128
+ 'Content-Type': 'application/json',
129
+ },
130
+ });
131
+ }
132
+ // ── Proxy URL & Auth ────────────────────────────────────
133
+ buildAuth(options = {}) {
134
+ const parts = [this.apiKey];
135
+ const country = options.country || this.defaultCountry;
136
+ const city = options.city || this.defaultCity;
137
+ if (country)
138
+ parts.push(`country-${country.toLowerCase()}`);
139
+ if (city)
140
+ parts.push(`city-${city.toLowerCase()}`);
141
+ if (options.session)
142
+ parts.push(`session-${options.session}`);
143
+ if (options.render)
144
+ parts.push('render-1');
145
+ return parts.join(':');
146
+ }
147
+ /**
148
+ * Get proxy URL for use with other HTTP libraries (e.g. puppeteer, playwright, got).
149
+ */
150
+ getProxyUrl(options = {}) {
151
+ const auth = this.buildAuth(options);
152
+ if (options.protocol === 'socks5') {
153
+ return `socks5://${auth}@${this.proxyHost}:${this.socksPort}`;
154
+ }
155
+ return `http://${auth}@${this.proxyHost}:${this.httpPort}`;
156
+ }
157
+ /**
158
+ * Get an HTTP/SOCKS agent for use with axios or other libraries.
159
+ */
160
+ getProxyAgent(options = {}) {
161
+ const url = this.getProxyUrl(options);
162
+ if (options.protocol === 'socks5')
163
+ return new socks_proxy_agent_1.SocksProxyAgent(url);
164
+ return new https_proxy_agent_1.HttpsProxyAgent(url);
165
+ }
166
+ // ── Request Methods ─────────────────────────────────────
167
+ /**
168
+ * Fetch a URL through the residential proxy with auto-retry and smart headers.
169
+ */
170
+ async fetch(url, options = {}, config = {}, retries = 3) {
171
+ const country = options.country || this.defaultCountry || 'US';
172
+ const headers = { ...chromeFingerprint(country), ...config.headers };
173
+ const agent = this.getProxyAgent(options);
174
+ this.stats.requests++;
175
+ const start = Date.now();
176
+ let lastError;
177
+ for (let attempt = 0; attempt < retries; attempt++) {
178
+ const sid = options.session || newSessionId();
179
+ const proxyOpts = { ...options, session: sid };
180
+ const proxyAgent = options.session ? agent : this.getProxyAgent(proxyOpts);
181
+ try {
182
+ const resp = await (0, axios_1.default)({
183
+ method: config.method || 'GET',
184
+ url,
185
+ ...config,
186
+ headers,
187
+ httpsAgent: proxyAgent,
188
+ httpAgent: proxyAgent,
189
+ timeout: this.timeout,
190
+ });
191
+ const elapsed = Date.now() - start;
192
+ if (this.debug) {
193
+ console.log(`IPLoop: ${config.method || 'GET'} ${url} → ${resp.status} (${elapsed}ms) country=${country} session=${sid}`);
194
+ }
195
+ if (RETRYABLE_STATUSES.has(resp.status) && attempt < retries - 1) {
196
+ await sleep(1000 * (attempt + 1));
197
+ continue;
198
+ }
199
+ this.stats.success++;
200
+ this.stats.totalTime += elapsed;
201
+ return resp;
202
+ }
203
+ catch (err) {
204
+ lastError = err;
205
+ if (attempt < retries - 1) {
206
+ await sleep(1000 * (attempt + 1));
207
+ }
208
+ }
209
+ }
210
+ this.stats.errors++;
211
+ this.stats.totalTime += Date.now() - start;
212
+ if (lastError?.message?.includes('timeout')) {
213
+ throw new IPLoopError(`All ${retries} retries timed out for ${url}`);
214
+ }
215
+ throw new ProxyError(`Proxy connection failed after ${retries} retries: ${lastError?.message}`);
216
+ }
217
+ /** GET request through proxy. */
218
+ async get(url, options = {}, config = {}) {
219
+ return this.fetch(url, options, { ...config, method: 'GET' });
220
+ }
221
+ /** POST request through proxy. */
222
+ async post(url, data, options = {}, config = {}) {
223
+ return this.fetch(url, options, { ...config, method: 'POST', data });
224
+ }
225
+ /** PUT request through proxy. */
226
+ async put(url, data, options = {}, config = {}) {
227
+ return this.fetch(url, options, { ...config, method: 'PUT', data });
228
+ }
229
+ /** DELETE request through proxy. */
230
+ async delete(url, options = {}, config = {}) {
231
+ return this.fetch(url, options, { ...config, method: 'DELETE' });
232
+ }
233
+ // ── Sticky Sessions ─────────────────────────────────────
234
+ /**
235
+ * Create a sticky session — all requests reuse the same proxy IP.
236
+ */
237
+ session(sessionId, country, city) {
238
+ return new StickySession(this, sessionId || newSessionId(), country || this.defaultCountry, city || this.defaultCity);
239
+ }
240
+ // ── Batch / Concurrent ─────────────────────────────────
241
+ /**
242
+ * Fetch multiple URLs concurrently through the proxy.
243
+ */
244
+ async fetchAll(urls, options = {}, concurrency = 10) {
245
+ const results = [];
246
+ const queue = [...urls];
247
+ const worker = async () => {
248
+ while (queue.length > 0) {
249
+ const url = queue.shift();
250
+ try {
251
+ const resp = await this.get(url, options);
252
+ results.push({ url, status: resp.status, success: true, sizeKb: Math.round(JSON.stringify(resp.data).length / 1024) });
253
+ }
254
+ catch (err) {
255
+ results.push({ url, status: 0, success: false, sizeKb: 0, error: err.message });
256
+ }
257
+ }
258
+ };
259
+ await Promise.all(Array.from({ length: Math.min(concurrency, urls.length) }, () => worker()));
260
+ return results;
261
+ }
262
+ // ── Stats ───────────────────────────────────────────────
263
+ /**
264
+ * Get request statistics.
265
+ */
266
+ getStats() {
267
+ const avg = this.stats.requests > 0 ? this.stats.totalTime / this.stats.requests : 0;
268
+ const rate = this.stats.requests > 0 ? (this.stats.success / this.stats.requests) * 100 : 0;
269
+ return { ...this.stats, avgTime: Math.round(avg), successRate: Math.round(rate * 10) / 10 };
270
+ }
271
+ // ── Chrome Fingerprint ──────────────────────────────────
272
+ /**
273
+ * Get Chrome desktop fingerprint headers for a country.
274
+ */
275
+ fingerprint(country = 'US') {
276
+ return chromeFingerprint(country);
277
+ }
278
+ // ── API Methods ─────────────────────────────────────────
279
+ /** Check bandwidth usage and quota. */
280
+ async getUsage() {
281
+ const resp = await this.apiClient.get('/api/support/diagnose');
282
+ return resp.data;
283
+ }
284
+ /** Check service status. */
285
+ async getStatus() {
286
+ const resp = await this.apiClient.get('/api/support/status');
287
+ return resp.data;
288
+ }
289
+ /** List available proxy countries. */
290
+ async getCountries() {
291
+ const resp = await this.apiClient.get('/api/support/countries');
292
+ return resp.data;
293
+ }
294
+ }
295
+ exports.IPLoopClient = IPLoopClient;
296
+ // ── Version Check ────────────────────────────────────────────
297
+ const SDK_VERSION = '1.0.1';
298
+ exports.SDK_VERSION = SDK_VERSION;
299
+ function checkVersion() {
300
+ try {
301
+ const https = require('https');
302
+ https.get('https://registry.npmjs.org/iploop/latest', { timeout: 3000 }, (res) => {
303
+ let data = '';
304
+ res.on('data', (chunk) => { data += chunk; });
305
+ res.on('end', () => {
306
+ try {
307
+ const latest = JSON.parse(data).version;
308
+ if (latest && latest !== SDK_VERSION) {
309
+ console.warn(`\n⚠️ IPLoop v${latest} available (you have ${SDK_VERSION}). Run: npm update iploop\n`);
310
+ }
311
+ }
312
+ catch { }
313
+ });
314
+ }).on('error', () => { });
315
+ }
316
+ catch { }
317
+ }
318
+ checkVersion();
319
+ exports.default = IPLoopClient;
320
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;;;;AAEH,kDAAgF;AAChF,yDAAoD;AACpD,yDAAoD;AACpD,mCAAoC;AA6DpC,gEAAgE;AAEhE,MAAa,WAAY,SAAQ,KAAK;IACpC,YACE,OAAe,EACR,UAAmB,EACnB,QAAc;QAErB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHR,eAAU,GAAV,UAAU,CAAS;QACnB,aAAQ,GAAR,QAAQ,CAAM;QAGrB,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AATD,kCASC;AAED,MAAa,mBAAoB,SAAQ,WAAW;IAClD,YAAY,UAAkB,iBAAiB;QAC7C,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QACpB,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;CACF;AALD,kDAKC;AAED,MAAa,cAAe,SAAQ,WAAW;IAC7C,YACE,UAAkB,qBAAqB,EAChC,UAAmB;QAE1B,KAAK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C;YACZ,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC,CAAA,CAAC;AACZ,CAAC;AAED,YAAY,EAAE,CAAC;AAGf,kBAAe,YAAY,CAAC"}
package/package.json CHANGED
@@ -1,21 +1,53 @@
1
1
  {
2
2
  "name": "iploop",
3
- "version": "1.0.0",
4
- "description": "IPLoop Residential Proxy SDK route requests through millions of real devices",
5
- "main": "index.js",
6
- "types": "index.d.ts",
7
- "keywords": ["proxy", "residential-proxy", "web-scraping", "rotating-proxy", "socks5", "http-proxy", "iploop", "sdk"],
8
- "author": "IPLoop <partners@iploop.io>",
3
+ "version": "1.0.2",
4
+ "description": "Official Node.js SDK for IPLoop residential proxy service",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "prepublishOnly": "npm run build",
13
+ "test": "jest",
14
+ "lint": "eslint src/**/*.ts"
15
+ },
16
+ "keywords": [
17
+ "proxy",
18
+ "residential-proxy",
19
+ "mobile-proxy",
20
+ "web-scraping",
21
+ "iploop",
22
+ "socks5",
23
+ "http-proxy"
24
+ ],
25
+ "author": "IPLoop <support@iploop.io>",
9
26
  "license": "MIT",
10
- "homepage": "https://iploop.io",
11
27
  "repository": {
12
28
  "type": "git",
13
- "url": "https://github.com/iploop/iploop-node"
29
+ "url": "https://github.com/iploop/nodejs-sdk"
30
+ },
31
+ "homepage": "https://iploop.io",
32
+ "bugs": {
33
+ "url": "https://github.com/iploop/nodejs-sdk/issues"
14
34
  },
15
35
  "engines": {
16
- "node": ">=14"
36
+ "node": ">=16.0.0"
17
37
  },
18
38
  "dependencies": {
19
- "node-fetch": "^2.7.0"
39
+ "axios": "^1.6.0",
40
+ "https-proxy-agent": "^7.0.0",
41
+ "socks-proxy-agent": "^8.0.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^20.0.0",
45
+ "typescript": "^5.0.0",
46
+ "jest": "^29.0.0",
47
+ "@types/jest": "^29.0.0",
48
+ "ts-jest": "^29.0.0",
49
+ "eslint": "^8.0.0",
50
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
51
+ "@typescript-eslint/parser": "^6.0.0"
20
52
  }
21
53
  }
package/index.d.ts DELETED
@@ -1,51 +0,0 @@
1
- declare class IPLoop {
2
- constructor(apiKey: string, options?: {
3
- gateway?: string;
4
- port?: number;
5
- country?: string;
6
- city?: string;
7
- timeout?: number;
8
- });
9
-
10
- fetch(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
11
- get(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
12
- post(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
13
- put(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
14
- delete(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
15
- session(options?: SessionOptions): IPLoopSession;
16
- countries(): Promise<string[]>;
17
- }
18
-
19
- interface RequestOptions {
20
- method?: string;
21
- headers?: Record<string, string>;
22
- body?: string | object;
23
- country?: string;
24
- city?: string;
25
- session?: string;
26
- timeout?: number;
27
- }
28
-
29
- interface SessionOptions {
30
- country?: string;
31
- city?: string;
32
- session?: string;
33
- }
34
-
35
- interface IPLoopResponse {
36
- status: number;
37
- statusCode: number;
38
- headers: Record<string, string>;
39
- body: string;
40
- text(): Promise<string>;
41
- json(): Promise<any>;
42
- }
43
-
44
- declare class IPLoopSession {
45
- fetch(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
46
- get(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
47
- post(url: string, options?: RequestOptions): Promise<IPLoopResponse>;
48
- }
49
-
50
- export = IPLoop;
51
- export { IPLoop, IPLoopSession, RequestOptions, SessionOptions, IPLoopResponse };
package/index.js DELETED
@@ -1,152 +0,0 @@
1
- const http = require('http');
2
- const https = require('https');
3
- const { URL } = require('url');
4
-
5
- class IPLoop {
6
- constructor(apiKey, options = {}) {
7
- this.apiKey = apiKey;
8
- this.gateway = options.gateway || 'gateway.iploop.io';
9
- this.port = options.port || 8880;
10
- this.country = options.country || null;
11
- this.city = options.city || null;
12
- this.timeout = options.timeout || 30000;
13
- }
14
-
15
- _buildAuth(options = {}) {
16
- const parts = [this.apiKey];
17
- const country = options.country || this.country;
18
- const city = options.city || this.city;
19
- const session = options.session || null;
20
-
21
- if (country) parts.push(`country-${country}`);
22
- if (city) parts.push(`city-${city}`);
23
- if (session) parts.push(`session-${session}`);
24
-
25
- return `user:${parts.join('-')}`;
26
- }
27
-
28
- fetch(url, options = {}) {
29
- return new Promise((resolve, reject) => {
30
- const target = new URL(url);
31
- const auth = this._buildAuth(options);
32
-
33
- const proxyOptions = {
34
- hostname: this.gateway,
35
- port: this.port,
36
- path: url,
37
- method: options.method || 'GET',
38
- headers: {
39
- ...this._defaultHeaders(target, options),
40
- ...(options.headers || {}),
41
- 'Proxy-Authorization': 'Basic ' + Buffer.from(auth).toString('base64'),
42
- 'Host': target.hostname,
43
- },
44
- timeout: options.timeout || this.timeout,
45
- };
46
-
47
- const req = http.request(proxyOptions, (res) => {
48
- let data = '';
49
- res.on('data', chunk => data += chunk);
50
- res.on('end', () => {
51
- resolve({
52
- status: res.statusCode,
53
- statusCode: res.statusCode,
54
- headers: res.headers,
55
- text: () => Promise.resolve(data),
56
- json: () => Promise.resolve(JSON.parse(data)),
57
- body: data,
58
- });
59
- });
60
- });
61
-
62
- req.on('error', reject);
63
- req.on('timeout', () => {
64
- req.destroy();
65
- reject(new Error('Request timeout'));
66
- });
67
-
68
- if (options.body) {
69
- req.write(typeof options.body === 'string' ? options.body : JSON.stringify(options.body));
70
- }
71
- req.end();
72
- });
73
- }
74
-
75
- get(url, options = {}) {
76
- return this.fetch(url, { ...options, method: 'GET' });
77
- }
78
-
79
- post(url, options = {}) {
80
- return this.fetch(url, { ...options, method: 'POST' });
81
- }
82
-
83
- put(url, options = {}) {
84
- return this.fetch(url, { ...options, method: 'PUT' });
85
- }
86
-
87
- delete(url, options = {}) {
88
- return this.fetch(url, { ...options, method: 'DELETE' });
89
- }
90
-
91
- session(options = {}) {
92
- const sessionId = options.session || `sess-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
93
- return new IPLoopSession(this, { ...options, session: sessionId });
94
- }
95
-
96
- _defaultHeaders(target, options = {}) {
97
- const country = options.country || this.country || 'US';
98
- const langs = {
99
- US: 'en-US,en;q=0.9',
100
- GB: 'en-GB,en;q=0.9',
101
- DE: 'de-DE,de;q=0.9,en;q=0.8',
102
- FR: 'fr-FR,fr;q=0.9,en;q=0.8',
103
- JP: 'ja-JP,ja;q=0.9,en;q=0.8',
104
- BR: 'pt-BR,pt;q=0.9,en;q=0.8',
105
- IL: 'he-IL,he;q=0.9,en;q=0.8',
106
- };
107
-
108
- return {
109
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
110
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
111
- 'Accept-Language': langs[country] || langs.US,
112
- 'Accept-Encoding': 'gzip, deflate, br',
113
- 'Cache-Control': 'no-cache',
114
- 'Sec-Fetch-Dest': 'document',
115
- 'Sec-Fetch-Mode': 'navigate',
116
- 'Sec-Fetch-Site': 'none',
117
- 'Sec-Ch-Ua': '"Chromium";v="122", "Not(A:Brand";v="24"',
118
- 'Sec-Ch-Ua-Mobile': '?0',
119
- 'Sec-Ch-Ua-Platform': '"Windows"',
120
- 'Upgrade-Insecure-Requests': '1',
121
- };
122
- }
123
-
124
- async countries() {
125
- return ['US', 'GB', 'DE', 'FR', 'JP', 'BR', 'IN', 'AU', 'CA', 'IL',
126
- 'KR', 'SG', 'NL', 'SE', 'CH', 'ES', 'IT', 'PL', 'TR', 'ZA',
127
- 'NG', 'PH', 'MX', 'AR', 'CL', 'CO', 'EG', 'KE', 'TH', 'VN'];
128
- }
129
- }
130
-
131
- class IPLoopSession {
132
- constructor(client, options) {
133
- this.client = client;
134
- this.options = options;
135
- }
136
-
137
- fetch(url, options = {}) {
138
- return this.client.fetch(url, { ...this.options, ...options });
139
- }
140
-
141
- get(url, options = {}) {
142
- return this.fetch(url, { ...options, method: 'GET' });
143
- }
144
-
145
- post(url, options = {}) {
146
- return this.fetch(url, { ...options, method: 'POST' });
147
- }
148
- }
149
-
150
- module.exports = IPLoop;
151
- module.exports.IPLoop = IPLoop;
152
- module.exports.default = IPLoop;