Files
iwb-plugins-desktop/image-vectorize/tools/e2e-site.mjs
T

229 lines
12 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)。
//
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 ——
// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。
// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能
// 悄悄把 'wasm-unsafe-eval' 加回去。
//
// 运行:
// node image-vectorize/tools/e2e-site.mjs
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-vectorize/tools/e2e-site.mjs
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
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')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const PLUGIN_ID = 'image-vectorize'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-vectorize/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const poll = async (fn, timeout = 25000, step = 250) => {
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 sleep(step)
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
// 剪贴板要显式授权(真站是 https,安全上下文成立;本地 file/about:blank 测不到这条)
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
try {
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(BASE).origin })
} catch (error) {
console.log('(剪贴板授权失败,相关断言会跳过:' + (error && error.message) + ')')
}
const page = await context.newPage()
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 320; c.height = 320
const g = c.getContext('2d')
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 320, 320)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(96, 96, 58, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(170, 130, 120, 84, 12); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 38px "PingFang SC", sans-serif'; g.fillText('菜单', 96, 250)
return c.toDataURL('image/png')
})
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
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({ [d.id]: { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG, id: PLUGIN_ID })
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 1) 真实 KV 加载 + SRI ----------
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
const active = await poll(async () => page.evaluate((id) => {
const p = window.IWBPluginHost.list().find((x) => x.id === id)
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}, PLUGIN_ID))
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
check('插件脚本用 SRI(sha256) 加载',
scripts.some((s) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)),
JSON.stringify(scripts.map((s) => s.src)))
// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ----------
const cspProbe = await page.evaluate(async () => {
try {
const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0))
await WebAssembly.instantiate(b)
return 'ok'
} catch (e) { return 'blocked: ' + e.message }
})
check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120))
// ---------- 3) 打开工作区 ----------
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('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 4) 入口 → 模态 ----------
await page.locator('.iwb-node[data-node-id="r1"]').click()
const floatBtn = page.locator('.iwb-node-floatbar button[title="位图转矢量"]')
let entry = ''
if (await floatBtn.count()) {
await floatBtn.click()
entry = '漂浮菜单'
} else {
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '位图转矢量' }).first().click()
entry = '右键命令'
}
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 30000 })
check('节点入口可触发(' + entry + ')', true)
check('样式注入生效(CSP unsafe-inline)', await page.evaluate(() => {
const s = document.getElementById('iwb-vectorize-style')
return Boolean(s && s.textContent.indexOf('.vz-') >= 0)
}))
// ---------- 5) 真站 CSP 下引擎能跑 ----------
const paths = await poll(async () => {
// 统计项是「元素」,合并模式下会带后缀「(N 孤岛合并)」,只取前面的数字
const t = await page.locator('[data-stat="elements"]').textContent()
const m = /^\s*(\d+)/.exec(t || '')
return m && Number(m[1]) > 0 ? m[1] : false
}, 30000)
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), '元素=' + paths)
check('默认按孤岛拆分(元素数 > 层数)', Number(paths) > 3, '元素=' + paths)
check('预览为 blob: SVG', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
}))
const stats = await page.evaluate(() => ({
levels: Number(document.querySelector('[data-stat="levels"]').textContent),
bytes: document.querySelector('[data-stat="bytes"]').textContent,
ms: document.querySelector('[data-stat="ms"]').textContent,
}))
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
// ---------- 5.5) 面板形态:高级默认打开 + 精度默认精细 ----------
check('高级参数默认展开', await page.evaluate(() => {
const box = document.querySelector('[data-adv]')
return Boolean(box && !box.hidden)
}))
check('精度默认「精细」', await page.evaluate(() => {
const a = document.querySelector('[data-seg-group="precision"] button.active')
return Boolean(a && a.dataset.value === 'fine')
}))
// v0.3.1:预览白底 + 填充/背景并排(真站 CSP 下 CSS 得真生效,不能只信本地)
check('预览区白底、无棋盘格', await page.evaluate(() => {
const cs = getComputedStyle(document.querySelector('.vz-preview'))
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(cs.backgroundColor)
return Boolean(m) && Number(m[1]) > 240 && cs.backgroundImage === 'none'
}))
check('「填充 / 背景」两个色块并排在同一行', await page.evaluate(() => {
const a = document.querySelector('[data-color="color"]')
const b = document.querySelector('[data-color="bg"]')
if (!a || !b) return false
const ra = a.getBoundingClientRect()
const rb = b.getBoundingClientRect()
return Math.abs(ra.top - rb.top) < 2 && rb.left > ra.right - 1
}))
// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ----------
await page.locator('[data-act="copy"]').click()
await sleep(400)
const clip = await page.evaluate(async () => {
try {
const items = await navigator.clipboard.read()
const types = items[0] ? items[0].types : []
let svg = ''
if (types.indexOf('image/svg+xml') >= 0) svg = await (await items[0].getType('image/svg+xml')).text()
return { types, svg, status: (document.querySelector('[data-status-text]') || {}).textContent || '' }
} catch (e) { return { error: String(e && e.message) } }
})
if (clip.error) {
check('复制 SVG 写入剪贴板', false, clip.error)
} else {
check('复制 SVG:剪贴板含 image/svg+xml(Figma 按矢量粘贴)',
clip.types.indexOf('image/svg+xml') >= 0 && clip.svg.indexOf('<svg') === 0 && clip.svg.indexOf('<path') > 0,
clip.types.join(',') + ' / ' + clip.svg.length + 'B')
check('复制后给了反馈', /已复制/.test(clip.status), clip.status)
// 拆分是这个版本的核心诉求:粘到 Figma 必须是多个可单独选中的图层,而不是一个整体
const pathCount = (clip.svg.match(/<path/g) || []).length
check('剪贴板里是多个独立 path(Figma 可单独选中,不是一个整体)', pathCount >= 5 && !/<g\b/.test(clip.svg), 'path 元素=' + pathCount)
}
// ---------- 6) 保存为节点(真实画布桥) ----------
await page.locator('[data-act="save"]').click()
const saved = await poll(async () => (await page.locator('.iwb-node').count()) >= 2, 25000)
check('保存为节点:画布新增一个图片节点', Boolean(saved), 'nodes=' + await page.locator('.iwb-node').count())
check('模态已关闭', (await page.locator('.vz-root').count()) === 0)
const fatal = consoleErrors.filter((e) => /Content Security Policy|Refused to|SRI|integrity/i.test(e))
check('无 CSP / SRI 报错', fatal.length === 0, fatal.slice(0, 2).join(' | '))
if (consoleErrors.length) {
console.log('')
console.log('控制台错误(' + consoleErrors.length + ' 条,前 5 条):')
for (const e of consoleErrors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
}
console.log('')
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
await browser.close()
process.exit(failed ? 1 : 0)