用户裁定「只要单色/灰度就够」后重做:VTracer(彩色分层 wasm)换成 potrace (纯 JS,Inkscape 同款内核)。文字笔画完整、turdSize 去掉毛刺、灰度层数 2–5。 - 纯 JS ⇒ 不需要宿主放宽 CSP;插件 238KB → 116KB - 自带 potrace 移植(GPL-2.0,去 jimp 依赖,改吃 ImageData),License 随目录 - 灰度阈值自己按等像素量分位算(上游 steps:5 要 28s,这里几十 ms), 并处理「主背景峰要排除」「切点必须严格递增」两个坑 - 新增 tools/trace-cli.mjs:拿真实素材直接跑参数、出对比图 - harness 重写 32 项(含「无 wasm-unsafe-eval 的 CSP 下跑通」反向锁);真站 e2e 13 项
171 lines
8.5 KiB
JavaScript
171 lines
8.5 KiB
JavaScript
// 真实站点端到端(开发用,不进 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()
|
||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
|
||
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 () => {
|
||
const t = await page.locator('[data-stat="paths"]').textContent()
|
||
return t && t !== '–' && Number(t) > 0 ? t : false
|
||
}, 30000)
|
||
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), 'paths=' + 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))
|
||
|
||
// ---------- 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)
|