@aomex-contrib/playwright 0.0.0-next-20261126082202

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/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # @aomex-contrib/playwright
2
+
3
+ ## 0.0.0-next-20261126082202
4
+
5
+ ### Minor Changes
6
+
7
+ - [`e99f20f`](https://github.com/aomex/aomex-contrib/commit/e99f20fae0eed3544433a312993023258aebaed4) Thanks [@geekact](https://github.com/geekact)! - 包名由 `@aomex-contrib/playwright-service` 更名为 `@aomex-contrib/playwright`
8
+
9
+ ## 0.2.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [`0d8018b`](https://github.com/aomex/aomex-contrib/commit/0d8018b156edece0ea04774955c7e0d381d2d235) Thanks [@geekact](https://github.com/geekact)! - 新增 `@aomex-contrib/playwright-service`:基于 Playwright 的 Browser Service
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-2024 geekact
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 ADDED
@@ -0,0 +1,253 @@
1
+ # @aomex-contrib/playwright
2
+
3
+ 基于 [Playwright](https://playwright.dev) 的 aomex **Browser Service**:`onInit` 启动唯一 Chromium,每次任务用独立 `BrowserContext` 注入代理。默认经 [playwright-extra](https://github.com/berstend/puppeteer-extra/tree/master/packages/playwright-extra) + [puppeteer-extra-plugin-stealth](https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin-stealth) 做反自动化。
4
+
5
+ 适合:业务里多处要开浏览器、按账号/任务换代理、retry 时复用同一 Browser。
6
+
7
+ ---
8
+
9
+ ## 安装浏览器
10
+
11
+ `pnpm add` 只装 npm 包,不会下载 Chromium。把下面两段 script 加到**业务项目**的 `package.json`:
12
+
13
+ ```json
14
+ {
15
+ "scripts": {
16
+ "postinstall": "playwright install chromium",
17
+ "install:browser:deps": "playwright install --with-deps chromium"
18
+ }
19
+ }
20
+ ```
21
+
22
+ `postinstall` 会在每次 `pnpm install` 时下载 Chromium 二进制,本地和线上安装依赖都会执行。它不装系统库,macOS 上可以直接跑。
23
+
24
+ `install:browser:deps` 还会走 apt 安装系统库,需要 root,只在 Docker 镜像构建时执行。
25
+
26
+ 本包运行时要求 **Node >= 24**。`playwright` 版本必须和项目依赖一致,否则找不到浏览器可执行文件。
27
+
28
+ ### 本地
29
+
30
+ ```bash
31
+ pnpm add @aomex-contrib/playwright playwright
32
+ ```
33
+
34
+ ### Docker:官方 Node 镜像
35
+
36
+ 生产 / CI 用 Docker Hub 官方 [`node`](https://hub.docker.com/_/node) 镜像(`node:24`),在**镜像构建**时安装 Chromium 和系统库。Playwright 文档也支持这种做法(见 [Build your own image](https://playwright.dev/docs/docker#build-your-own-image))。
37
+
38
+ 镜像里的 `pnpm install` 会跑 `postinstall`,只下载浏览器。系统库用 `pnpm install:browser:deps` 补上。
39
+
40
+ ```dockerfile
41
+ FROM node:24
42
+
43
+ WORKDIR /app
44
+
45
+ RUN pnpm install:browser:deps
46
+
47
+ CMD ["node", "dist/index.js"]
48
+ ```
49
+
50
+ 要点:
51
+
52
+ - 基础镜像用官方默认 tag `node:24`(当前是 Debian);Alpine / musl **不支持** Playwright 的 Firefox/WebKit 构建,本包默认 Chromium 也请避开 Alpine
53
+ - 镜像内以 `root` 跑时 Chromium sandbox 常被关掉;爬不受信站点时建议另建非 root 用户,并参考 Playwright 的 [seccomp](https://playwright.dev/docs/docker) 说明
54
+ - 也可用 Microsoft 预装镜像 `mcr.microsoft.com/playwright:v<与依赖相同的版本>-jammy`(或 `-noble`),但仍需自行安装 `playwright` npm 包,且 tag 版本必须对齐
55
+
56
+ Docker 默认把容器里的 `/dev/shm` 限制在 64MB。Chromium 每个页面是独立进程,渲染数据走这块共享内存,空间不够时页面会崩。加大空间是**启动容器**的参数,写不进 Dockerfile。
57
+
58
+ ```bash
59
+ docker run --shm-size=1g your-image
60
+ ```
61
+
62
+ Compose 写在服务上:
63
+
64
+ ```yaml
65
+ services:
66
+ app:
67
+ shm_size: 1g
68
+ ```
69
+
70
+ ### 有界面(`headless: false`)时加 Xvfb
71
+
72
+ 默认 `headless: true` 即可。若必须有头模式,在 **Linux 无 `DISPLAY`** 时本会自动拉起 `Xvfb :99`,但镜像里要先有 `Xvfb` 命令:
73
+
74
+ ```dockerfile
75
+ FROM node:24
76
+
77
+ RUN apt-get update \
78
+ && apt-get install -y --no-install-recommends xvfb \
79
+ && rm -rf /var/lib/apt/lists/*
80
+
81
+ WORKDIR /app
82
+
83
+ RUN pnpm install:browser:deps
84
+
85
+ CMD ["node", "dist/index.js"]
86
+ ```
87
+
88
+ ```ts
89
+ createPlaywrightService({ logger, headless: false });
90
+ ```
91
+
92
+ - 已设置有效 `DISPLAY` 时不会再起 Xvfb
93
+ - macOS / Windows 本机有显示子系统,不走这套逻辑
94
+
95
+ ---
96
+
97
+ ## 注册
98
+
99
+ ```ts
100
+ // src/services/browser.service.ts
101
+ import { createPlaywrightService } from '@aomex-contrib/playwright';
102
+ import { Logger } from '@aomex/logger';
103
+
104
+ export default createPlaywrightService({
105
+ logger: new Logger(), // 或项目里已有的 Logger 实例
106
+ // headless: false, // 有界面;Linux 无 DISPLAY 时镜像需已装 xvfb(见上文)
107
+ // stealth: false,
108
+ // idleTimeout: '5 minutes',
109
+ // maxConcurrent: 3,
110
+ // recaptcha: {
111
+ // provider: { id: '2captcha', token: process.env.TWOCAPTCHA_TOKEN! },
112
+ // },
113
+ });
114
+
115
+ // src/services/index.ts
116
+ export const services = await combineServices({
117
+ browser: () => import('./browser.service.js'),
118
+ // ...
119
+ });
120
+ ```
121
+
122
+ 不要在 `services/index` 里直接 `import` 并内联 `createPlaywrightService(...)`:
123
+
124
+ ```ts
125
+ // ❌ 入口一加载就会拉起 Playwright / stealth 等依赖,进程一开始就多占内存
126
+ import { createPlaywrightService } from '@aomex-contrib/playwright';
127
+ browser: async () => createPlaywrightService({ logger, headless: true }),
128
+ ```
129
+
130
+ 应像上文一样 `() => import('./browser.service.js')`,等第一次用到 browser 再加载。
131
+
132
+ ### 继承扩展方法
133
+
134
+ `createPlaywrightService` 返回的是 class,可 `extends` 后加业务方法(内部继续调 `withPage`):
135
+
136
+ ```ts
137
+ // src/services/browser.service.ts
138
+ import { createPlaywrightService, type WithPageOptions } from '@aomex-contrib/playwright';
139
+ import { Logger } from '@aomex/logger';
140
+ import type { BrowserContext, Page } from 'playwright';
141
+
142
+ const PlaywrightService = createPlaywrightService({
143
+ logger: new Logger(),
144
+ });
145
+
146
+ export default class BrowserService extends PlaywrightService {
147
+ /** 失败时截图后原样抛出;各业务 Service 复用,不要把站点流程写进来 */
148
+ async withPageOrScreenshot<T>(
149
+ opts: WithPageOptions,
150
+ onHandle: (page: Page, context: BrowserContext) => Promise<T>,
151
+ ): Promise<T> {
152
+ return this.withPage(opts, async (page, context) => {
153
+ try {
154
+ return await onHandle(page, context);
155
+ } catch (error) {
156
+ await page.screenshot({ path: `failed-${Date.now()}.png`, fullPage: true });
157
+ throw error;
158
+ }
159
+ });
160
+ }
161
+
162
+ /** 打开 URL 并返回页面 HTML */
163
+ async getHtml(url: string, opts: WithPageOptions = {}) {
164
+ return this.withPage(opts, async (page) => {
165
+ await page.goto(url);
166
+ return page.content();
167
+ });
168
+ }
169
+ }
170
+ ```
171
+
172
+ 公开 API:`withPage`、`getStats`。继承类**只放通用、可跨业务复用的方法**;具体站点点击流、账号流程仍放在各自业务 Service。
173
+
174
+ ---
175
+
176
+ ## 用法
177
+
178
+ ```ts
179
+ const proxy = {
180
+ host: '1.2.3.4',
181
+ port: 8080,
182
+ username: 'u',
183
+ password: 'p',
184
+ };
185
+
186
+ const cookies = await services.browser.withPage(
187
+ {
188
+ proxy,
189
+ cookies: savedCookies,
190
+ // storageState / extraHTTPHeaders / userAgent / geolocation / permissions ...
191
+ },
192
+ async (page, context) => {
193
+ await page.goto('https://example.com/login');
194
+ // 若配置了 recaptcha:
195
+ // await page.solveRecaptchas();
196
+ return context.cookies();
197
+ },
198
+ );
199
+ ```
200
+
201
+ `WithPageOptions`:`proxy`(本包简化结构)、`cookies`(创建后再 `addCookies`),以及 Playwright `BrowserContextOptions` 其余字段(会覆盖 Service 级 `viewport` / `locale` 等默认)。
202
+
203
+ ### 行为说明
204
+
205
+ | API | 作用 |
206
+ | --------------- | ------------------------------------------------------------- |
207
+ | `onInit` | 首次用到 Service 时 `chromium.launch` |
208
+ | `withPage` | `newContext({ proxy })` → `newPage` → 回调 → **关闭 Context** |
209
+ | `getStats` | `{ active, waiting, connected }` 并发与连接状态 |
210
+ | `idleTimeout` | 空闲回收 Browser(省内存);下次 `withPage` 自动再启 |
211
+ | `maxConcurrent` | 同时 `withPage` 上限;超出排队 |
212
+ | `onDestroy` | 关 Browser;超时强杀进程 |
213
+
214
+ 代理:`proxy.server` 或 `proxy.host` + `proxy.port`;账密写在 `proxy.username` / `proxy.password`。
215
+
216
+ ---
217
+
218
+ ## 配置项
219
+
220
+ `createPlaywrightService({ ... })`:
221
+
222
+ | 字段 | 说明 | 默认 |
223
+ | ---------------- | --------------------------------------------------------------- | ------------------------------ |
224
+ | `headless` | 是否无头;`false` 时 Linux 无 DISPLAY 会自动起 Xvfb(需已安装) | `true` |
225
+ | `stealth` | 是否挂载 `puppeteer-extra-plugin-stealth` | `true` |
226
+ | `recaptcha` | 挂载 `puppeteer-extra-plugin-recaptcha` 的选项 | —(不传则不挂) |
227
+ | `viewport` | 视口 | `{ width: 1400, height: 800 }` |
228
+ | `timezoneId` | Context 时区 | `'America/New_York'` |
229
+ | `locale` | Context 语言 | `'en-US'` |
230
+ | `defaultTimeout` | Context 默认超时(`DurationInput`) | `'2 minutes'` |
231
+ | `closeTimeout` | 关闭 Browser/Context 等待上限 | `'10 seconds'` |
232
+ | `idleTimeout` | 空闲回收 Browser(省内存);再有任务会自动 launch | — |
233
+ | `maxConcurrent` | 同时 `withPage` 上限;超出排队;不传则不限制 | — |
234
+ | `launch` | `chromium.launch` 选项;`args` 追加在默认列表后 | — |
235
+ | `logger` | **必填**,`Logger` 实例(如项目共用 logger) | — |
236
+ | `userAgent` | 自定义 UA | 按 Chromium 版本拼 Chrome UA |
237
+
238
+ ### reCAPTCHA / hCaptcha
239
+
240
+ 配置 `recaptcha` 后,`withPage` 的 `page` 类型会带上 `solveRecaptchas` 等方法(未配置则没有)。打码平台 token、何时解题仍由业务决定:
241
+
242
+ ```ts
243
+ await services.browser.withPage({}, async (page) => {
244
+ await page.goto('https://www.google.com/recaptcha/api2/demo');
245
+ await page.solveRecaptchas();
246
+ });
247
+ ```
248
+
249
+ 站点专用点击流放在**业务 Service**。
250
+
251
+ ---
252
+
253
+ 通用能力见:https://aomex.js.org