validate / validate (push) Canceled after 0s
本仓只服务桌面宿主 image-workbench-desktop,与网页端无限画布工具无关。 14 个测试/工具脚本里共 15 处仍把 image-workbench-web 当 playwright/esbuild 的依赖后备目录(含 path.resolve、报错文案、album viewer-e2e 的多余候选), 全部改为 image-workbench-desktop;album 里重复的 web 仓候选直接删掉。 这些常量只用于找 node_modules,不参与任何插件逻辑,行为零变化。 桌面仓已确认有 playwright 1.64.1 / esbuild 0.28.2,改后依赖解析有效。 本轮不动 6 处 test.image-workbench-web.pages.dev 网址(属于网页端 e2e 脚本的废弃处理,另案);插件源码与版本未动,不需要发市场。
229 lines
13 KiB
JavaScript
229 lines
13 KiB
JavaScript
// 真实站点端到端(开发用,不进 CI)—— white-bg-800「白底图」。
|
||
//
|
||
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
|
||
// `connect-src 'self' https: …` 拦掉,因为宿主 CSP 的 `connect-src` 不含 `data:`)
|
||
// 在 mock 下永远绿,只有带真实 KV + 浏览器 SRI + 真实 CSP 的真站能抓出来。
|
||
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)校验 + 真实画布桥。
|
||
//
|
||
// 运行(需要 Playwright):
|
||
// node white-bg-800/tools/e2e-site.mjs # 默认测试站
|
||
// IWB_BASE_URL=https://iwb.maqiart.eu.org node white-bg-800/tools/e2e-site.mjs # 正式站
|
||
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
|
||
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)) // <repo>/white-bg-800/tools
|
||
const REPO = path.resolve(HERE, '../..') // <repo>
|
||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||
|
||
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(' npm i -D playwright # 本仓或宿主仓皆可')
|
||
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node white-bg-800/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, 'white-bg-800/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 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 new Promise((r) => setTimeout(r, 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))
|
||
|
||
// 造一张真实的 96x64 PNG 作为节点图片(故意非正方形,让 800 方画布的等比缩放/居中被真正练到)
|
||
await page.goto('about:blank')
|
||
const PNG = await page.evaluate(() => {
|
||
const c = document.createElement('canvas')
|
||
c.width = 96; c.height = 64
|
||
const x = c.getContext('2d')
|
||
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64)
|
||
x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40)
|
||
return c.toDataURL('image/png')
|
||
})
|
||
|
||
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
|
||
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({ 'white-bg-800': { enabled: true, settings: {}, data: {} } }))
|
||
}, { cfg: CFG, ws: WS, png: PNG })
|
||
|
||
// ---------- 1) 站点可达 ----------
|
||
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
|
||
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
|
||
|
||
// ---------- 2) 宿主就绪 + 真实 KV 加载并启用 ----------
|
||
const hostReady = await poll(async () => page.evaluate(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true), 30000)
|
||
check('window.IWBPluginHost 就绪(initialized)', Boolean(hostReady))
|
||
const active = await poll(async () => page.evaluate(() => {
|
||
const p = window.IWBPluginHost.list().find((x) => x.id === 'white-bg-800')
|
||
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
|
||
}))
|
||
check('从真实 KV 加载并启用(active)', Boolean(active), JSON.stringify(active))
|
||
|
||
// ---------- 3) 版本 ----------
|
||
check('线上版本 = white-bg-800/package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
|
||
|
||
// ---------- 4) SRI ----------
|
||
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) => /plugin-white-bg-800(\.[0-9a-f]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
|
||
|
||
// ---------- 5) 打开工作区 + 种子节点 ----------
|
||
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)
|
||
|
||
// ---------- 6) 入口:节点漂浮菜单(title 是静态字面量「白底图」;回落右键插件命令)----------
|
||
const triggerWhiteBg = async () => {
|
||
await page.locator('.iwb-node[data-node-id="r1"]').click()
|
||
const btn = page.locator('.iwb-node-floatbar button[title="白底图"]')
|
||
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
|
||
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
|
||
await page.locator('.iwb-ctx-item').filter({ hasText: '白底图:选中节点' }).click()
|
||
return '右键命令'
|
||
}
|
||
const entry = await triggerWhiteBg()
|
||
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
|
||
|
||
// ---------- 7) 默认「新建」:恰好 2 个节点、新节点为 src_800x800.png ----------
|
||
const created = await poll(async () => page.evaluate(() => {
|
||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||
const nodes = ws.nodes || []
|
||
if (nodes.length !== 2) return false
|
||
const n = nodes.find((x) => x.id !== 'r1') || nodes[1]
|
||
return { nodes: nodes.length, name: n.data && n.data.name }
|
||
}))
|
||
const wsNodes = created ? created.nodes : await page.evaluate(() => (JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}').nodes || []).length)
|
||
check('默认「新建」:iwb_ws_w1 恰好 2 个节点', wsNodes === 2, 'nodes=' + wsNodes)
|
||
check('新节点 data.name = src_800x800.jpg(默认 format=jpeg)', Boolean(created && /^src_800x800\.jpg$/.test(created.name || '')), created && String(created.name))
|
||
|
||
// ---------- 8) 页内解引用 + 解码新建 JPEG:800x800、左上像素为白色 ----------
|
||
// 宿主「C3」引用模型:localStorage 里只存引用,字节在别处 —— 假设 localStorage 里有 base64 是
|
||
// 不可能的(by design)。两种引用形态都要认:
|
||
// a) { __blob: 'imgblob_<hash>_<len>' } → IndexedDB(src/image-blob-store.js)
|
||
// b) { __cache: '<同源 URL>' } → 宿主把大 dataURL 外置成 /__iwb_cache__/xxx(当前线上形态)
|
||
// 故在页内经 IWBImageBlobStore 解引用或同源 fetch __cache(CSP connect-src 'self' 放行)。
|
||
const resolved = await poll(async () => page.evaluate(async () => {
|
||
// 读节点图(按优先级解引用):a) data: 字符串直用 b) {__blob} 引用解引用 c) 其余形态给诊断失败
|
||
const resolveNodeDataUrl = async (d) => {
|
||
if (typeof d === 'string' && /^data:/.test(d)) return { dataUrl: d, via: 'data:' } // a)
|
||
if (d && typeof d === 'object' && typeof d.__cache === 'string' && d.__cache) { // b2) 宿主把大 dataURL 外置成同源缓存引用
|
||
const toDataUrl = (blob) => new Promise((res) => {
|
||
const fr = new FileReader()
|
||
fr.onload = () => res(String(fr.result || ''))
|
||
fr.onerror = () => res('')
|
||
fr.readAsDataURL(blob)
|
||
})
|
||
try {
|
||
// /__iwb_cache__/<hash> 由 SW 直出;冷启动 SW 未接管时该路径会落到 Pages 404(返回 HTML)。
|
||
// 故优先直接读 Cache Storage,读不到再走 fetch(此时 SW 已接管)。
|
||
const abs = new URL(d.__cache, location.origin).href
|
||
if (typeof caches !== 'undefined') {
|
||
const hit = (await caches.match(abs)) || (await caches.match(d.__cache))
|
||
if (hit) {
|
||
const blob = await hit.blob()
|
||
const u = await toDataUrl(blob)
|
||
return u ? { dataUrl: u, via: '__cache(CS ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
|
||
}
|
||
}
|
||
const resp = await fetch(abs)
|
||
const blob = await resp.blob()
|
||
const u = await toDataUrl(blob)
|
||
return u ? { dataUrl: u, via: '__cache(fetch ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
|
||
} catch (e) {
|
||
return { error: '__cache 抓取抛错: ' + ((e && e.message) || String(e)) }
|
||
}
|
||
}
|
||
if (d && typeof d === 'object' && typeof d.__blob === 'string' && d.__blob) { // b)
|
||
const Lib = window.IWBImageBlobStore
|
||
if (!Lib) return { error: 'window.IWBImageBlobStore 缺失' }
|
||
try {
|
||
let u = ''
|
||
if (typeof Lib.resolveDataUrl === 'function') {
|
||
u = await Lib.resolveDataUrl(d.__blob)
|
||
} else if (typeof Lib.create === 'function') {
|
||
// 与 app.js:730 同一构造:idb 用宿主同一存储运行时(get 直出 Blob)
|
||
const idb = (window.IWBStorageRuntime && window.IWBStorageRuntime.indexedDb) ||
|
||
(window.IWBStorageFallbackIndexeddb && window.IWBStorageContract && window.IWBStorageFallbackIndexeddb.create({ contract: window.IWBStorageContract.indexedDb }))
|
||
if (!idb || typeof idb.get !== 'function') return { error: '取不到宿主 idb(IWBStorageRuntime.indexedDb)' }
|
||
u = await Lib.create({ idb }).resolveDataUrl(d.__blob)
|
||
} else {
|
||
return { error: 'IWBImageBlobStore 无 resolveDataUrl / create' }
|
||
}
|
||
return (typeof u === 'string' && u) ? { dataUrl: u, via: '__blob' } : { error: '解引用未返回字节(' + d.__blob + ')' }
|
||
} catch (e) {
|
||
return { error: '解引用抛错: ' + ((e && e.message) || String(e)) }
|
||
}
|
||
}
|
||
return { error: '未知 data 形态: ' + (d == null ? String(d) : typeof d) + ' keys=' + (d && typeof d === 'object' ? Object.keys(d).join(',') : '-') + ' sample=' + JSON.stringify(d).slice(0, 220) } // c)
|
||
}
|
||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||
const nodes = ws.nodes || []
|
||
const n = nodes.length === 2 ? (nodes.find((x) => x.id !== 'r1') || nodes[1]) : null
|
||
if (!n) return false // 新节点未就绪 → 重试
|
||
const r = await resolveNodeDataUrl(n.data && n.data.data)
|
||
if (r.error) return { error: r.error }
|
||
if (!/^data:image\/jpeg;base64,/.test(r.dataUrl)) return { error: '解引用结果不是 JPEG dataURL(via=' + r.via + '): ' + String(r.dataUrl).slice(0, 40) }
|
||
const img = new Image()
|
||
const ok = await new Promise((res) => { img.onload = () => res(true); img.onerror = () => res(false); img.src = r.dataUrl })
|
||
if (!ok) return { dataOk: true, via: r.via, decodeError: 'Image 解码失败' }
|
||
const c = document.createElement('canvas')
|
||
c.width = img.naturalWidth; c.height = img.naturalHeight
|
||
const x = c.getContext('2d')
|
||
x.drawImage(img, 0, 0)
|
||
const px = x.getImageData(0, 0, 1, 1).data
|
||
return { dataOk: true, via: r.via, w: img.naturalWidth, h: img.naturalHeight, px: [px[0], px[1], px[2], px[3]] }
|
||
}))
|
||
const d = resolved || {}
|
||
const dDiag = d.error || d.decodeError || (resolved ? '' : '轮询超时:新节点未出现')
|
||
check('新节点 data 为 JPEG 字节(引用已解析)', Boolean(d.dataOk), d.dataOk ? d.via : dDiag)
|
||
check('新建 JPEG 解码尺寸 = 800x800', Boolean(d.dataOk && d.w === 800 && d.h === 800), d.dataOk ? d.w + 'x' + d.h : dDiag)
|
||
// jpeg 有损:纯白角落允许 ±5 的压缩抖动,但 alpha 必须不透明
|
||
check('新建 JPEG 左上像素 ≈ 白色且不透明', Boolean(d.dataOk && d.px && d.px[0] >= 250 && d.px[1] >= 250 && d.px[2] >= 250 && d.px[3] === 255), JSON.stringify(d.px) || dDiag)
|
||
|
||
// 透明模式(transparent)不在此二次跑(需改设置再整轮重放,易碎)——由 white-bg-800/tools/harness.mjs 覆盖。
|
||
|
||
// ---------- 9) 无 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(' | '))
|
||
|
||
// ---------- 10) 无页面级运行时错误 ----------
|
||
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
|
||
|
||
await browser.close()
|
||
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
|
||
process.exit(failed ? 1 : 0)
|