Files
iwb-plugins-desktop/batch-export/tools/harness.mjs
T
qiqi 605dc55fc9 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/ 工作目录
2026-10-31 10:29:54 +08:00

401 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 批量出图插件本地端到端(开发用,不进 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)