feat(batch-export): 新增批量出图插件 1.1.0(本地抠图 + 白底/透明 + 双版本 + ZIP)

- 资源中心面板:参数区 + 待处理节点列表(30px 缩略图)+ 进度条 + 开始出图 + 导出 ZIP
- 串行跑节点,可选走本机抠图服务(默认 http://localhost:30092/rmbg)
- 每个节点白底/透明合成后按格式/质量/体积上限编码,双版本时输出两个文件
- 自写 STORE 模式 ZIP(流式 CRC32 + UTF-8 文件名 bit 11),不依赖外部库以符合 CSP
- 修复:布尔属性走 property 赋值为准(setAttribute('checked','false') 仍算勾选)
- 修复:MutationObserver 监测宿主容器,切 tab 时自动摘除面板,避免串页
- 修复:mount 时给宿主容器补 inline 宽度,面板撑满半屏
- 修复:makeSrcThumb/fillSrcThumbs 移入 setup(ctx) 作用域(原先访问到未定义的 ctx 被 catch 吞掉)
- .gitignore 忽略 .workbuddy/ 工作目录
This commit is contained in:
qiqi committed 2026-10-31 10:29:54 +08:00
1 parent a4701746e1
commit 605dc55fc9
6 files changed
+1814

No files matched your search

+1
View File
@@ -3,3 +3,4 @@ dist/
.DS_Store
*.log
.omo/
.workbuddy/
+127
View File
@@ -0,0 +1,127 @@
# 批量出图(插件)
在资源中心新增一个「批量出图」面板:勾选画布上的 `ref` 节点,串行跑
**(可选)本机抠图 → 白底/透明合成 → 单版或双版本编码(≤ 上限自动降质)**,
全部跑完打包成一个 ZIP 下载。
**不往画布写节点** —— 20 张 × 双版本 = 40 个节点会把画布铺满,批量的产物本来就该是文件。
## 与 `white-bg-800` 的关系
合成几何(`fitRect`)与编码/降质逻辑**与 `white-bg-800` 同源**,两边各带一份:
- 宿主硬约束是**插件彼此独立**(不得依赖加载顺序,不得调其它插件),所以 `batch-export` 不能 import `white-bg-800`。
- 抠图也没「调用 xianyi-cutout 插件」—— 它是直接 `POST {apiUrl}/rmbg?crop=true` 打本机服务(同一个契约),
跟那个插件存不存在无关。
- ⚠️ **改一边要同步另一边**,尤其是 `fitRect`、体积上限二分、`TYPE_EXT` 命名规则。
## 入口
宿主「资源中心」侧栏 →「批量出图」tab(由 `panels` 能力注入,宿主在首次显示时调用 `mount`)。
## 面板字段
| 字段 | 默认 | 说明 |
|---|---|---|
| 尺寸 | 800 | 800 / 1000 / 1200 / 1600 / 2000,正方形边长 |
| 版本 | 双版本 PNG + JPG | 双版本 / 仅白底 JPG / 仅透明 PNG |
| 内容占比 % | 80 | 内容等比缩放后占边长百分比(80 = 640/800),10–100 |
| 体积上限 KB | 500 | 0 = 不限;有损格式超限自动降质(下限质量 20),仍超则**该行失败**而不是缩尺寸 |
| 文件名前缀 | 空 | 如 `DQ_` → `DQ_菜单A_800x800.jpg` |
| 走本地鲜艺抠图 | 关 | 勾上则每张先过 `localhost:30092/rmbg`;已抠好的图别勾(二次抠图会伤边缘且慢一倍) |
面板参数存 `ctx.storage.namespace('opts').panel`,刷新/切 tab 后保留。
抠图服务地址与超时在宿主「设置 → 插件 → 批量出图」里(环境配置不放面板)。
**列表区**:配置区与列表之间是一条灰底小节头(「待处理节点 共 N 个」+ 全选 / 清空 / 刷新),
明细行是 `勾选 · 30px 缩略图 · 文件名 · 状态`。缩略图未跑时显示源图、跑完换成产物(绿框),
点任意缩略图可放大;缩略图在页内缩到 64px 长边再存 dataURL,几十张也不会把内存顶起来。
## 队列行为
- **串行**:一次一张,避免几十张大图同时解码爆内存。800×800 单张约 50–150ms。
- **单张失败不中断**:该行标红并显示原因,后续继续;行尾出现「重试」,只重跑这一张(不影响其它已完成项)。
- 进度条按「已结算 / 勾选总数」走,`done` 与 `fail` 都算结算。
- 生产产出的 `files` 挂在内存里,**改参数重跑会覆盖**;「导出 ZIP」总是打包当前所有 `done` 行。
- **产物只进 ZIP,不写入画布**(20 张 × 2 版本 = 40 个节点会把画布铺满)。跑完每行会显示
**产物缩略图**(点击放大预览)、列表下方出现绿色提示条「已生成 N 个文件 · X KB,点「导出 ZIP」下载到本机(不写入画布)」,
并把「导出 ZIP」按钮转成绿色主按钮;导出后提示条改为「已下载 batch_xxx.zip」。
—— 这三处都是 1.0.2 补的:第一版只有一行「2 个文件 · 22KB」,用户跑完以为没产出。
- **面板打开期间会自己跟进画布**:每 2s 比对一次节点签名(id + 文件名),有新拖入的 `ref` 就刷新列表;运行中不打断。
宿主没有画布变更事件,`ctx.canvas` 也只能读,所以只能这样轮询(成本是内存数组比较)。
## ZIP 实现
自写 STORE(无压缩)写入器,零依赖:
- **为什么不用 JSZip**:宿主 CSP 是 `script-src 'self'`,CDN 动态插 script 会被拦死(宿主 `storage-zip.js` 记着这条教训)。
- **为什么 STORE**:图片本身已是 PNG/JPEG,DEFLATE 几乎不减体积,还白花 CPU。
- **文件名 UTF-8**:写 general purpose bit 11(`0x0800`),中文名在 Windows 资源管理器 / macOS 归档实用工具里正常。
⚠️ **macOS 命令行 `unzip`(Info-ZIP 6.0)不认这个标志位**,会解成乱码并报 `Illegal byte sequence` —— 是那个老工具的锅,
用 `python3 -m zipfile -e`、`bsdtar`、或双击归档实用工具都正常。
- **CRC 流式算**:分 1MB 片读 blob 算 CRC,图片字节始终留在浏览器 blob 存储里,不进 JS 堆(20 张大图也不会顶爆内存)。
## CSP / 权限
- 只声明 `panels` + `canvas`(只读),**不要 `canvasWrite`** —— 本插件不写画布。
- 抠图请求打到 `apiUrl`,CSP 只放行 `127.0.0.1` / `localhost` 的 `30092`;改别的地址会被浏览器拦。
- `createObjectURL` 下载走 `a.click()`;`img-src` 放行 `blob:`,解码用 blob URL 并即时释放。
## 验证(开发用)
```bash
node batch-export/tools/harness.mjs
```
mock 宿主 + 真实 Chromium,覆盖:manifest / 面板注册与挂载 / 列表过滤(只 `ref` 且有图)/ 默认参数 /
队列跑通 / **ZIP 用系统 `unzip -t` 验结构与 CRC + python3 zipfile 验中文名与 8 个条目 + PNG/JPEG magic** /
抠图分支(mock `/rmbg`)/ 失败行内提示 / 参数持久化 / 静态检查(无 eval、无 `fetch(data:)`)。
需要 Playwright(可从宿主仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)+ 系统 `unzip`、`python3`,不进 CI。
**发布后必须再跑一次真站**(mock 抓不到宿主 CSS / 真实 CSP / 真实面板挂载):
```bash
node batch-export/tools/e2e-site.mjs # 测试站
IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站
```
覆盖:真实 KV 加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 +
**勾选框与文字同行(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)** +
队列跑通 + 下载 ZIP + python3 校验 4 条目 / CRC / PNG·JPEG magic / UTF-8 名。
## 发布
```bash
cd /Users/qiqi/open/github/image-workbench-web
cp /Users/qiqi/open/github/iwb-plugins/batch-export/src/index.js /tmp/plugin-batch-export.js
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建 plugins/index.json,不做合并
cp /Users/qiqi/open/github/iwb-plugins/white-bg-800/src/index.js /tmp/plugin-white-bg-800.js
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
cp /Users/qiqi/open/github/iwb-plugins/blank-canvas/src/index.js /tmp/plugin-blank-canvas.js
node scripts/plugins-publish.mjs /tmp/plugin-batch-export.js /tmp/plugin-white-bg-800.js \
/tmp/plugin-xianyi-cutout.js /tmp/plugin-image-annotate.js /tmp/plugin-blank-canvas.js \
--version batch-export=1.1.0 # 默认 dry-run,检查 diff 后再加 --upload
```
发布后刷新即生效;新插件在「设置 → 插件」里**默认未启用**,需手动勾选。
⚠️ `--upload` 时脚本按清单顺序逐个 put,最后才 put `index.json`。代理抖动会让它在半路 `fetch failed` 退出,
此时**清单可能已经指向还没上传成功的文件**(1.0.1 发布时踩过)⇒ 线上 fail-closed 直接不加载。
稳妥做法:先把插件字节 put 上去,`curl` 确认 200 且大小对,再 put `index.json`。
## 版本记录
- **1.1.0**:交互与布局 ——
抠图开关文案改为「走本地鲜艺抠图(localhost:30092)」;配置区下方加灰底小节头(「待处理节点 共 N 个」+
全选/清空/刷新),隔断明显、操作按钮归位到列表区;
列表行常驻 **30px 缩略图**(未跑显示原图、跑完换产物并描绿框,点击放大,页内缩到 64px 长边存储);
**修「清空」不生效**:`el()` 用 `setAttribute('checked','false')` 处理布尔属性,属性有值即视为勾选,
改为走 property;**修切到「图库 / 节点组」时面板串页**:宿主复用同一 div 渲染其它 tab,插件用
MutationObserver 监听容器,一旦容器不再归属插件或混入别人的子节点就自行摘除(切回来自动重新挂载)。
- **1.0.3**:修 `.iwb-bx-btn-hot` 被后定义的 `.iwb-bx-btn` 覆盖(同特异性)导致导出按钮不高亮;改用双类选择器。
- **1.0.2**:产物可见性 —— 行内缩略图(点击放大)、绿色完成提示条、导出按钮高亮、导出后显示文件名;
面板每 2s 同步新拖入的节点;空列表文案改为「把图片拖进画布后点刷新」。
- **1.0.1**:修 `.iwb-bx-f input{width:100%}` 把抠图勾选框撑满整行、标签被挤到最右。
- **1.0.0**:首个版本(面板 + 串行队列 + 双版本 + ZIP)。
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/batch-export",
"private": true,
"version": "1.1.0",
"description": "批量出图:资源中心面板里勾选 ref 节点,串行跑(可选本机抠图)→ 白底/透明合成 → 双版本编码 → 打包 ZIP 下载",
"ibwPlugin": {
"id": "batch-export",
"entry": "src/index.js",
"apiVersion": 1
}
}
File diff suppressed because it is too large. Load diff
+267
View File
@@ -0,0 +1,267 @@
// 真实站点端到端(开发用,不进 CI)—— batch-export「批量出图」。
//
// 为什么需要它:harness.mjs 用的是 mock 宿主,面板样式与真实宿主 CSS 变量、真实 CSP、真实
// 画布桥都不会被执行到。发布后跑一遍这个脚本,能抓到 mock 里永远绿的问题 ——
// 例如 `.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行、把标签挤到面板最右(1.0.0 首次发布即中招)。
//
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)+ 真实资源中心面板挂载。
//
// 运行(需要 Playwright + python3):
// node batch-export/tools/e2e-site.mjs # 默认测试站
// IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
import { createRequire } from 'node:module'
import { execFileSync } from 'node:child_process'
import { readFileSync, existsSync, statSync } from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/e2e-site.mjs')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'batch-export/package.json'), 'utf8')).version
const ZIP_OUT = path.join(os.tmpdir(), 'iwb-batch-e2e.zip')
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
// 造两张 200×120 的参考图(非正方形,等比缩放/居中被真正练到)
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 200; c.height = 120
const x = c.getContext('2d')
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 200, 120)
return c.toDataURL('image/png')
})
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: {} }))
const ws = {
workspaces: [{
id: 'w1', name: 'W',
nodes: [
{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: '菜单A.png', localName: null } },
{ id: 'r2', type: 'ref', x: 460, y: 140, data: { url: '', data: d.png, name: '菜单B.png', localName: null } },
],
edges: [], groups: [],
}],
activeId: 'w1', rev: 1,
}
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ 'batch-export': { enabled: true, settings: {}, data: {} } }))
}, { png: PNG })
// ---------- 1) 站点可达 ----------
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 2) 真实 KV 加载 + 启用 ----------
await page.waitForFunction(() => window.IWBPluginHost && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
await page.waitForFunction(() => window.IWBPluginHost.list().some((x) => x.id === 'batch-export'), null, { timeout: 20000 })
const info = await page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'batch-export')
return p ? { version: p.version, enabled: p.enabled, active: p.active, capabilities: p.capabilities, error: p.error } : null
})
check('从真实 KV 加载并启用(active)', Boolean(info && info.active && info.enabled && !info.error), JSON.stringify(info))
check('线上版本 = batch-export/package.json(' + WANT_VERSION + ')', Boolean(info && info.version === WANT_VERSION), info && info.version)
// ---------- 3) 面板 tab ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('画布打开、2 个 ref 节点', (await page.locator('.iwb-node[data-node-id^="r"]').count()) === 2)
await page.locator('button[title^="资源中心"]').first().click()
const tab = page.locator('.iwb-res-tab', { hasText: '批量出图' })
check('资源中心出现「批量出图」tab', (await tab.count()) >= 1)
await tab.first().click()
await page.waitForTimeout(1200)
const mounted = await page.locator('.iwb-full-panel-plugin').count()
check('面板已挂载(真实宿主容器)', mounted >= 1)
// 宿主 .iwb-full-main 是 flex 行容器,只给图库/节点组容器 width:100%;插件容器不撑满就会按内容收缩
const widthInfo = await page.evaluate(() => {
const main = document.querySelector('.iwb-full-main')
const box = document.querySelector('.iwb-bx')
return {
main: main ? Math.round(main.clientWidth) : 0,
box: box ? Math.round(box.clientWidth) : 0,
}
})
check('面板撑满内容区宽度(不按内容收缩)',
widthInfo.main > 0 && widthInfo.box >= widthInfo.main - 2, JSON.stringify(widthInfo))
const rows = await page.locator('.iwb-bx-item').count()
check('面板列出 2 个 ref 节点', rows === 2, 'rows=' + rows)
// 1.0.0 首发的真实 bug:checkbox 被 .iwb-bx-f input{width:100%} 撑满整行,标签被挤到最右
const chk = await page.evaluate(() => {
const lab = document.querySelector('.iwb-bx-rowchk')
if (!lab) return null
const input = lab.querySelector('input[type=checkbox]')
const span = lab.querySelector('span')
if (!input || !span) return null
const a = input.getBoundingClientRect()
const b = span.getBoundingClientRect()
return { gap: Math.round(b.left - a.right), sameLine: Math.abs(a.top - b.top) < 12, inputW: Math.round(a.width) }
})
check('「走本地鲜艺抠图」勾选框与文字同行且紧邻', Boolean(chk && chk.sameLine && chk.gap >= 0 && chk.gap <= 12 && chk.inputW <= 24), JSON.stringify(chk))
const cutLabel = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-rowchk span')
return s ? s.textContent.trim() : ''
})
check('抠图开关文案写明「本地鲜艺抠图」+ 端口', /鲜艺/.test(cutLabel) && /30092/.test(cutLabel), cutLabel)
// 1.1.0:配置区与列表之间要有明显的隔断(灰底小节头),操作按钮归到列表区
const sec = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-sec')
if (!s) return null
const bar = document.querySelector('.iwb-bx-bar')
const a = s.getBoundingClientRect()
const b = bar.getBoundingClientRect()
return {
text: (s.textContent || '').trim().slice(0, 24),
btns: Array.from(s.querySelectorAll('button')).map((x) => x.textContent.trim()),
bg: getComputedStyle(s).backgroundColor,
belowConfig: a.top >= b.bottom - 1,
}
})
check('隔断:「待处理节点」小节头在配置区正下方,带灰底 + 全选/清空/刷新',
Boolean(sec && sec.belowConfig && sec.text.indexOf('待处理节点') === 0 &&
JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']) && sec.bg !== 'rgba(0, 0, 0, 0)'),
JSON.stringify(sec))
// 1.1.0:缩略图必须**跑之前**就在(30px 显示 / 64px 源图)
if (rows) {
const preThumb = await page.evaluate(() => {
const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb'))
return { n: imgs.length, w: imgs[0] ? imgs[0].naturalWidth : 0, cssW: imgs[0] ? Math.round(imgs[0].getBoundingClientRect().width) : 0 }
})
check('列表行首常驻源图缩略图(2 张、64px 位图 / 30px 显示)',
preThumb.n === 2 && preThumb.w === 64 && preThumb.cssW === 30, JSON.stringify(preThumb))
// 1.1.0 的 bug:「清空」后勾选框视觉上仍勾着(el() 用 setAttribute('checked','false'))
await page.getByRole('button', { name: '清空', exact: true }).click()
const cleared = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
check('「清空」真的取消勾选', cleared.length === 2 && cleared.every((v) => v === false), JSON.stringify(cleared))
await page.getByRole('button', { name: '全选', exact: true }).click()
}
// ---------- 4) 跑队列 ----------
if (!rows) {
console.log('\n' + (await page.locator('.iwb-full-panel-plugin').first().innerText()))
} else {
await page.getByRole('button', { name: '全选', exact: true }).click()
await page.getByRole('button', { name: '开始出图', exact: true }).click()
await page.waitForFunction(() => {
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
return b && !b.disabled
}, null, { timeout: 120000 })
const fails = await page.locator('.iwb-bx-item', { hasText: '失败' }).count()
check('队列跑完、无失败项', fails === 0, 'fail=' + fails)
// 跑完必须「看得见图」:行内缩略图 + 一条说明产物在哪的提示条(1.0.1 之前只有一行文字,用户以为没产出)
const thumbs = await page.locator('.iwb-bx-thumb').count()
check('行内显示产物缩略图(2 张)', thumbs === 2, 'thumbs=' + thumbs)
const thumbOk = thumbs ? await page.evaluate(() => {
const im = document.querySelector('.iwb-bx-thumb')
return { src: String(im.getAttribute('src') || '').slice(0, 5), w: im.naturalWidth, h: im.naturalHeight }
}) : null
check('缩略图是真解码出来的位图(800×800)', Boolean(thumbOk && thumbOk.src === 'blob:' && thumbOk.w === 800 && thumbOk.h === 800), JSON.stringify(thumbOk))
const doneText = await page.locator('.iwb-bx-done').first().innerText()
check('完成提示条说明「已生成 → 点导出 ZIP」(不写入画布)', /已生成 4 个文件/.test(doneText) && /导出 ZIP/.test(doneText) && /不写入画布/.test(doneText), doneText)
// 1.0.2 的坑:.iwb-bx-btn-hot 与 .iwb-bx-btn 同特异性且定义在前,背景被覆盖 → 高亮没生效
const zipBg = await page.evaluate(() => {
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
return b ? getComputedStyle(b).backgroundColor : ''
})
check('导出按钮转为高亮(rgb(29,158,117))', zipBg === 'rgb(29, 158, 117)', zipBg)
// ---------- 5) 导出 ZIP 并用 python3 校验(系统 unzip 对 UTF-8 名会乱码,见 README) ----------
const [download] = await Promise.all([
page.waitForEvent('download', { timeout: 60000 }),
page.getByRole('button', { name: '导出 ZIP', exact: true }).click(),
])
await download.saveAs(ZIP_OUT)
check('ZIP 已下载', existsSync(ZIP_OUT), existsSync(ZIP_OUT) ? statSync(ZIP_OUT).size + ' bytes' : '缺失')
const doneAfter = await page.locator('.iwb-bx-done').first().innerText()
check('导出后提示条显示已下载的文件名', /已下载 batch_.*\.zip/.test(doneAfter), doneAfter)
try {
const report = execFileSync('python3', ['-c', `
import zipfile, sys
z = zipfile.ZipFile(sys.argv[1])
assert z.testzip() is None, 'CRC 损坏'
for i in z.infolist():
b = z.read(i.filename)
ext = i.filename.rsplit('.', 1)[-1]
ok = b[:4] == b'\\x89PNG' if ext == 'png' else b[:3] == b'\\xff\\xd8\\xff'
print('%-28s %7dB %s %s' % (i.filename, i.file_size, '格式OK' if ok else '格式BAD', 'utf8' if i.flag_bits & 0x800 else 'nomb'))
`, ZIP_OUT], { encoding: 'utf8' })
console.log(report.trim())
const lines = report.trim().split('\n').filter(Boolean)
check('ZIP 4 个条目(2 张 × 双版本)', lines.length === 4, 'entries=' + lines.length)
check('ZIP 条目格式与 UTF-8 文件名标记正确', lines.every((l) => /格式OK/.test(l) && /utf8/.test(l)))
check('双版本命名 <原名>_800x800.png/.jpg', lines.some((l) => /菜单A_800x800\.png/.test(l)) && lines.some((l) => /菜单A_800x800\.jpg/.test(l)))
} catch (e) {
check('ZIP 结构校验(python3)', false, String((e && e.stdout) || (e && e.message)).slice(0, 200))
}
}
// ---------- 6) 切到「图库 / 节点组」时不得串页(1.1.0) ----------
// 真机现象:切到「图库」后批量面板还压在图片上方 —— 宿主两端都渲染成 div 且无 key,
// React 复用同一 DOM 节点,只清理自己管理的子节点,插件 mount 进去的根节点留在原地。
const clickedGallery = await page.evaluate(() => {
const t = Array.from(document.querySelectorAll('.iwb-res-tab')).find((x) => /图库/.test(x.textContent))
if (t) t.click()
return Boolean(t)
})
await page.waitForTimeout(1200)
const gallery = await page.evaluate(() => ({
historyMounted: document.querySelectorAll('.iwb-history-embedded').length,
panelsInDom: document.querySelectorAll('.iwb-bx').length,
panelInsideHistory: Boolean(document.querySelector('.iwb-history-embedded .iwb-bx')),
}))
check('切到「图库」:批量面板自动摘除,图库内不再混入插件 DOM',
clickedGallery && gallery.historyMounted >= 1 && gallery.panelsInDom === 0 && gallery.panelInsideHistory === false,
JSON.stringify(gallery))
await page.locator('.iwb-res-tab', { hasText: '批量出图' }).first().click()
await page.waitForTimeout(1500)
const backRows = await page.locator('.iwb-bx-item').count()
const backThumbs = await page.locator('.iwb-bx-item img.iwb-bx-thumb').count()
check('切回「批量出图」:面板自动重新挂载、列表与缩略图仍在',
backRows === 2 && backThumbs === 2, 'rows=' + backRows + ' thumbs=' + backThumbs)
// ---------- 7) 无 CSP / SRI 拦截、无页面错误 ----------
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+400
View File
@@ -0,0 +1,400 @@
// 批量出图插件本地端到端(开发用,不进 CI)。
//
// 为什么需要它:面板 UI + 串行队列 + Canvas 编码 + ZIP 打包都是浏览器行为,node 侧测不了。
// 这里装一个合成宿主(可注入的 ctx + panels 容器),addScriptTag 加载插件源码本体,在真实 Chromium 里验证
// 注册 / 面板挂载 / 节点过滤 / 队列 / 双版本出图 / ZIP 结构与系统可解压性 / 抠图分支 / 失败行内提示 / 参数持久化。
//
// 运行:
// node batch-export/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)+ 系统 unzip(校验 ZIP)
import { createRequire } from 'node:module'
import { writeFileSync, mkdtempSync } from 'node:fs'
import { execFileSync } from 'node:child_process'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/harness.mjs')
process.exit(2)
}
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 30000, step = 100) => {
const end = Date.now() + timeout
for (;;) {
let v
try { v = await fn() } catch { v = false }
if (v) return v
if (Date.now() > end) return false
await new Promise((r) => setTimeout(r, step))
}
}
// ---------- 页内环境:合成宿主 + 记录器(__H__)+ 源图 ----------
const HOST_SETUP = () => {
const H = {
manifest: null,
panels: [],
nodes: [],
images: {},
settings: {},
defaults: {},
storage: {},
logs: [],
rmbgCalls: 0,
zip: null,
}
const ctx = {
ui: { registerPanel: (p) => { H.panels.push(p); return true } },
canvas: {
getNodes: () => H.nodes,
listNodeTypes: () => [],
getSelectedNode: () => null,
getNodeImage: async (id) => H.images[id] || null,
},
settings: { get: (k) => (Object.prototype.hasOwnProperty.call(H.settings, k) ? H.settings[k] : H.defaults[k]) },
storage: {
namespace: (ns) => {
const key = String(ns === undefined || ns === null ? '' : ns)
if (!H.storage[key]) H.storage[key] = {}
return {
get: (k) => H.storage[key][String(k)],
set: (k, v) => { H.storage[key][String(k)] = v },
remove: (k) => { delete H.storage[key][String(k)] },
keys: () => Object.keys(H.storage[key]),
}
},
},
log: Object.assign(function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) }, {
info: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
warn: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
error: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
}),
events: { on() {}, off() {}, emit() {} },
}
window.IWBPluginHost = {
register(manifest, factory) {
H.manifest = manifest
H.defaults = {}
for (const k of Object.keys(manifest.settings || {})) H.defaults[k] = manifest.settings[k].default
factory(ctx)
},
}
window.__H__ = H
// 拦下 createObjectURL 拿 ZIP(about:blank 下不依赖真实下载事件)
const origCreate = URL.createObjectURL.bind(URL)
URL.createObjectURL = function (blob) {
if (blob && String(blob.type) === 'application/zip') H.zip = blob
return origCreate(blob)
}
}
console.log('目标:本地 mock 页(about:blank)+ 插件源码 ' + PLUGIN_ENTRY)
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
await page.addInitScript(HOST_SETUP)
await page.goto('about:blank')
await page.addScriptTag({ path: PLUGIN_ENTRY })
// ---------- 源图与假节点 ----------
await page.evaluate(async () => {
const H = window.__H__
const make = (w, h, color) => {
const c = document.createElement('canvas')
c.width = w; c.height = h
const x = c.getContext('2d')
x.fillStyle = color; x.fillRect(0, 0, w, h)
return c.toDataURL('image/png')
}
const makeBlob = (w, h, color) => new Promise((resolve) => {
const c = document.createElement('canvas')
c.width = w; c.height = h
const x = c.getContext('2d')
x.fillStyle = color; x.fillRect(0, 0, w, h)
c.toBlob(resolve, 'image/png')
})
const rect = make(400, 200, '#2f6fed')
const square = make(300, 300, '#e8a13c')
const noise = (() => {
const c = document.createElement('canvas')
c.width = 800; c.height = 800
const x = c.getContext('2d')
const img = x.createImageData(800, 800)
for (let i = 0; i < img.data.length; i += 4) {
img.data[i] = (Math.random() * 256) | 0
img.data[i + 1] = (Math.random() * 256) | 0
img.data[i + 2] = (Math.random() * 256) | 0
img.data[i + 3] = 255
}
x.putImageData(img, 0, 0)
return c.toDataURL('image/png')
})()
H.nodes = [
{ id: 'n1', type: 'ref', x: 0, y: 0, data: { name: '菜单A.png', data: rect } },
{ id: 'n2', type: 'ref', x: 0, y: 0, data: { name: '菜单B.png', data: square } },
{ id: 'n3', type: 'ref', x: 0, y: 0, data: { name: 'DQ_主图.png', data: rect } },
{ id: 'n4', type: 'ref', x: 0, y: 0, data: { name: '空节点', data: '' } },
{ id: 'n5', type: 'gen', x: 0, y: 0, data: { name: '生图结果', data: rect } },
{ id: 'n6', type: 'ref', x: 0, y: 0, data: { name: '噪声图.png', data: noise } },
]
H.images = {
n1: { dataUrl: rect },
n2: { dataUrl: square },
n3: { dataUrl: rect },
n6: { dataUrl: noise },
}
// rmbg mock:返回一张 200×100 的 PNG 字节(抠图服务契约:二进制进、PNG 字节出)
window.__RMBG_BLOB__ = await makeBlob(200, 100, '#2fbf71')
const origFetch = window.fetch
window.fetch = function (url) {
if (String(url).indexOf('/rmbg') >= 0) {
H.rmbgCalls++
return Promise.resolve(new Response(window.__RMBG_BLOB__, { status: 200, headers: { 'Content-Type': 'image/png' } }))
}
return origFetch.apply(this, arguments)
}
})
// ---------- 1) manifest / 注册 ----------
const m = await page.evaluate(() => window.__H__.manifest)
check('manifest:id = batch-export', m && m.id === 'batch-export', String(m && m.id))
check('manifest:name = 批量出图', m && m.name === '批量出图', String(m && m.name))
check('manifest:version = 1.1.0', m && m.version === '1.1.0', String(m && m.version))
check('manifest:apiVersion = 1', m && m.apiVersion === 1, String(m && m.apiVersion))
check('manifest:capabilities = [panels, canvas](只读画布,不写节点)',
m && JSON.stringify(m.capabilities) === JSON.stringify(['panels', 'canvas']), JSON.stringify(m && m.capabilities))
check('manifest:settings = apiUrl / timeoutMs',
m && JSON.stringify(Object.keys(m.settings || {}).sort()) === JSON.stringify(['apiUrl', 'timeoutMs']),
JSON.stringify(Object.keys(m.settings || {})))
const panels = await page.evaluate(() => window.__H__.panels.map((p) => ({ id: p.id, title: p.title, hasMount: typeof p.mount === 'function' })))
check('面板:恰好注册 1 个(batch-panel / 批量出图 / 有 mount)',
panels.length === 1 && panels[0].id === 'batch-panel' && panels[0].title === '批量出图' && panels[0].hasMount,
JSON.stringify(panels))
// ---------- 2) 挂载 + 列表 ----------
await page.evaluate(() => {
const host = document.createElement('div')
host.className = 'iwb-full-panel-plugin'
host.style.height = '700px'
document.body.appendChild(host)
window.__PANEL__ = host
window.__H__.panels[0].mount(host)
})
check('挂载:面板根节点已注入(.iwb-bx)', await page.evaluate(() => Boolean(document.querySelector('.iwb-bx'))))
const rows = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item')).map((r) => r.querySelector('.iwb-bx-name').textContent))
const rowCount = await page.evaluate(() => document.querySelectorAll('.iwb-bx-item').length)
check('列表:只列 ref 且有图的节点(4 行:过滤空 ref 与 gen)', rowCount === 4, String(rowCount))
check('列表:顺序与节点一致', JSON.stringify(await rows()) === JSON.stringify(['菜单A.png', '菜单B.png', 'DQ_主图.png', '噪声图.png']),
JSON.stringify(await rows()))
// ---------- 2b) 隔断 / 缩略图 / 全选清空 ----------
const sec = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-sec')
if (!s) return null
return { text: (s.textContent || '').trim(), btns: Array.from(s.querySelectorAll('button')).map((b) => b.textContent.trim()) }
})
check('隔断:配置区下方有「待处理节点」小节头,操作按钮归到列表区',
Boolean(sec) && sec.text.indexOf('待处理节点') === 0 && JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']),
JSON.stringify(sec))
const thumbInfo = await poll(() => page.evaluate(() => {
const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb'))
return imgs.length === 4 && imgs.every((i) => i.complete && i.naturalWidth > 0)
? { n: imgs.length, w: imgs[0].naturalWidth, h: imgs[0].naturalHeight }
: false
}))
check('缩略图:每行都有源图缩略图且已解码(缩到 64px 长边)',
Boolean(thumbInfo) && thumbInfo.w === 64, JSON.stringify(thumbInfo))
// 清空必须真的取消勾选:1.1.0 前 el() 用 setAttribute('checked','false'),属性有值 ⇒ 视觉上仍勾着
await page.getByRole('button', { name: '清空', exact: true }).click()
const afterClear = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
check('清空:点击后勾选框全部取消(checked 属性为 false)', afterClear.every((v) => v === false), JSON.stringify(afterClear))
await page.getByRole('button', { name: '全选', exact: true }).click()
const afterAll = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
check('全选:点击后勾选框全部勾上', afterAll.length === 4 && afterAll.every((v) => v === true), JSON.stringify(afterAll))
const dflt = await page.evaluate(() => ({
size: document.querySelectorAll('.iwb-bx-bar select')[0].value,
mode: document.querySelectorAll('.iwb-bx-bar select')[1].value,
ratio: document.querySelector('.iwb-bx-bar input[type=number]').value,
max: document.querySelectorAll('.iwb-bx-bar input[type=number]')[1].value,
cutout: document.querySelector('.iwb-bx-bar input[type=checkbox]').checked,
}))
check('默认参数:800 / dual / 80% / 500KB / 抠图未勾',
dflt.size === '800' && dflt.mode === 'dual' && dflt.ratio === '80' && dflt.max === '500' && dflt.cutout === false,
JSON.stringify(dflt))
// ---------- 3) 跑队列 ----------
const clickBtn = (text) => page.evaluate((t) => {
const btn = Array.from(document.querySelectorAll('.iwb-bx-foot button')).find((b) => b.textContent === t)
if (btn) btn.click()
return Boolean(btn)
}, text)
check('队列:找到「开始出图」按钮', await clickBtn('开始出图'))
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
const afterRun = await page.evaluate(() => ({
progress: document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent,
tags: Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent),
}))
check('队列:进度 4/4', afterRun.progress === '4/4', afterRun.progress)
check('队列:每行「2 个文件」(双版本)', afterRun.tags.every((t) => t.indexOf('2 个文件') === 0), JSON.stringify(afterRun.tags))
// ---------- 4) ZIP ----------
check('ZIP:找到「导出 ZIP」按钮', await clickBtn('导出 ZIP'))
await poll(() => page.evaluate(() => Boolean(window.__H__.zip)))
const zipB64 = await page.evaluate(async () => {
const buf = await window.__H__.zip.arrayBuffer()
const u8 = new Uint8Array(buf)
let bin = ''
for (let i = 0; i < u8.length; i += 0x8000) bin += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000))
return btoa(bin)
})
const tmp = mkdtempSync(path.join(tmpdir(), 'iwb-batch-'))
const zipPath = path.join(tmp, 'out.zip')
writeFileSync(zipPath, Buffer.from(zipB64, 'base64'))
check('ZIP:非空', Buffer.from(zipB64, 'base64').length > 1000, Buffer.from(zipB64, 'base64').length + ' bytes')
let zipTest = ''
try {
zipTest = execFileSync('unzip', ['-t', zipPath], { encoding: 'utf8' })
} catch (error) {
zipTest = String(error.stdout || error.message)
}
check('ZIP:系统 unzip -t 校验通过(结构与 CRC 合法)', /No errors detected/.test(zipTest), zipTest.trim().split('\n').pop())
// 命名与条目内容用 python3 的 zipfile 验 —— macOS 自带的 Info-ZIP 6.0 不认 ZIP 的 UTF-8 标志位(bit 11),
// 会把中文名按本地编码解成乱码并报 "Illegal byte sequence";那是验证工具的锅,不是 ZIP 的。
// python3 zipfile / Windows 资源管理器 / macOS 归档实用工具(libarchive)都正确支持 bit 11。
const pythonProbe = `
import sys, zipfile
z = zipfile.ZipFile(sys.argv[1])
for n in z.namelist():
print("ENTRY|" + n + "|" + z.read(n)[:4].hex())
`
let probeOut = ''
try {
probeOut = execFileSync('python3', ['-c', pythonProbe, zipPath], { encoding: 'utf8' })
} catch (error) {
probeOut = 'PROBE_FAILED ' + String(error.stdout || error.message)
}
const entries = probeOut.split('\n').filter((l) => l.startsWith('ENTRY|')).map((l) => {
const [, name, magic] = l.split('|')
return { name, magic }
})
const wantNames = ['菜单A_800x800.png', '菜单A_800x800.jpg', '菜单B_800x800.png', '菜单B_800x800.jpg', 'DQ_主图_800x800.png', 'DQ_主图_800x800.jpg', '噪声图_800x800.png', '噪声图_800x800.jpg']
const matched = wantNames.filter((n) => entries.some((e) => e.name === n))
check('ZIP:8 个条目、中文名与双版本命名正确', matched.length === 8 && entries.length === 8,
entries.map((e) => e.name).join(' / ') || probeOut.slice(0, 120))
const pngOk = entries.filter((e) => e.name.endsWith('.png')).every((e) => e.magic === '89504e47')
const jpgOk = entries.filter((e) => e.name.endsWith('.jpg')).every((e) => /^ffd8ff/.test(e.magic))
check('ZIP:解出的 .png 都是 PNG 头(89504e47)、.jpg 都是 JPEG 头(ffd8ff)', pngOk && jpgOk,
entries.map((e) => e.name.split('.').pop() + '=' + e.magic).join(' '))
// ---------- 6) 抠图分支 ----------
await page.evaluate(() => {
const chk = document.querySelector('.iwb-bx-bar input[type=checkbox]')
chk.checked = true
chk.dispatchEvent(new Event('change'))
})
await clickBtn('开始出图')
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
const cutStats = await page.evaluate(() => ({ calls: window.__H__.rmbgCalls, tags: Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent) }))
check('抠图:勾选后每张都走 rmbg(4 次)', cutStats.calls === 4, String(cutStats.calls))
check('抠图:走完仍全部成功(2 个文件/行)', cutStats.tags.every((t) => t.indexOf('2 个文件') === 0), JSON.stringify(cutStats.tags))
// ---------- 7) 体积上限失败行内提示 ----------
await page.evaluate(() => {
const chk = document.querySelector('.iwb-bx-bar input[type=checkbox]')
chk.checked = false
chk.dispatchEvent(new Event('change'))
const max = document.querySelectorAll('.iwb-bx-bar input[type=number]')[1]
max.value = '1'
max.dispatchEvent(new Event('change'))
})
await clickBtn('开始出图')
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
const failTags = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent))
check('失败:maxKB=1 时行内显示失败原因(含「已压到质量 20」)',
failTags.every((t) => t.indexOf('失败 · 已压到质量 20') === 0), JSON.stringify(failTags.slice(0, 2)))
check('失败:出现「重试」按钮', await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item button')).some((b) => b.textContent === '重试')))
// ---------- 8) 参数持久化(此时已改过 cutout / maxKB,应该有落盘记录) ----------
const saved = await page.evaluate(() => (window.__H__.storage.opts ? window.__H__.storage.opts.panel : null))
check('持久化:参数写入 storage(namespace=opts),含改过的 cutout / maxKB',
Boolean(saved) && saved.cutout === false && saved.maxKB === 1 && saved.size === 800 && saved.mode === 'dual',
JSON.stringify(saved))
// ---------- 8) 静态检查 ----------
const offenders = []
const src = (await import('node:fs')).readFileSync(PLUGIN_ENTRY, 'utf8')
for (const [i, line] of src.split('\n').entries()) {
const n = i + 1
if (/fetch\(\s*(['"])data:/.test(line)) offenders.push(n + ': fetch(data:)')
if (/\beval\s*\(/.test(line)) offenders.push(n + ': eval')
if (/new\s+Function\s*\(/.test(line)) offenders.push(n + ': new Function')
if (/\bimport\b/.test(line)) offenders.push(n + ': import')
if (/\brequire\s*\(/.test(line)) offenders.push(n + ': require')
}
check('静态检查:无 fetch(data:) / eval / new Function / import / require', offenders.length === 0, offenders.slice(0, 3).join(' | '))
check('静态检查:ZIP 文件名 UTF-8 标志位(bit 11 = 0x0800)已写', /setUint16\(6,\s*0x0800/.test(src))
// ---------- 12) 宿主复用容器(切到图库/节点组)时必须自行摘除 ----------
// 真机现象:切到「图库」后批量面板仍留在上方,因为宿主两端都渲染成 div 且无 key,React 复用同一节点,
// 只清它自己管理的子节点,插件 append 的根节点留在原地。这里模拟宿主复用行为。
const switchAway = await page.evaluate(async () => {
const host = window.__PANEL__
host.className = 'iwb-history-embedded'
host.appendChild(document.createElement('div')) // 宿主渲染的图库内容
await new Promise((r) => setTimeout(r, 60))
return { hasPanel: Boolean(document.querySelector('.iwb-bx')), hostKids: host.children.length }
})
check('切换 tab:容器被复用给图库后,插件根节点自动摘除(不串页)',
switchAway.hasPanel === false, JSON.stringify(switchAway))
const switchBack = await page.evaluate(async () => {
const host = window.__PANEL__
host.className = 'iwb-full-panel-plugin'
host.textContent = '' // 宿主先卸掉图库内容,再挂载插件
await new Promise((r) => setTimeout(r, 60))
return { hasPanel: Boolean(document.querySelector('.iwb-bx')), rows: document.querySelectorAll('.iwb-bx-item').length }
})
check('切回插件 tab:面板自动重新挂载、节点列表仍在',
switchBack.hasPanel === true && switchBack.rows > 0, JSON.stringify(switchBack))
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)