// 真实站点端到端(开发用,不进 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)) // /batch-export/tools const REPO = path.resolve(HERE, '../..') // 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)) // ---------- 4.5) 行内单张下载(1.2.0):不依赖 ZIP,产物在内存里直接落盘 ---------- const dlState = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-dl')).map((b) => ({ text: b.textContent, disabled: b.disabled, title: b.title, }))) check('行内下载:每行 JPG / PNG 各一个(2 行 = 4 个)', dlState.length === 4 && dlState[0].text === 'JPG' && dlState[1].text === 'PNG', JSON.stringify(dlState.map((b) => b.text))) check('行内下载:双版本跑完后全部可点', dlState.every((b) => b.disabled === false), JSON.stringify(dlState.map((b) => b.disabled))) const [jpgDl] = await Promise.all([ page.waitForEvent('download', { timeout: 30000 }), page.locator('.iwb-bx-item').first().locator('.iwb-bx-dl').first().click(), ]) check('行内下载:点 JPG 直接下载单张(不必先导出 ZIP)', /\.jpg$/.test(jpgDl.suggestedFilename()), jpgDl.suggestedFilename()) 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)