feat(plugin): 新增 white-bg-800 白底图插件(移植自 iwb-cutout-extension)
把选中节点的图等比缩放居中合成到正方形画布(白底/透明底),输出 <name>_<size>x<size>.png。 入口:节点漂浮菜单「白底图」(ref/out/gen)+ 右键命令「白底图:选中节点」。 设置:bgSize(800)/ratioPct(85)/transparent/replace。 有意不移植:上游 autoWhiteBg(入口即功能,不做抠图后自动转白底)、批量处理 / 下载 / 剪贴板。 修正上游 bug:上游文件名硬编码 _800x800,此处按夹取后的真实边长命名。 验证:tools/harness.mjs 40/40(本地 mock 端到端)+ tools/e2e-site.mjs 14/14 (带 CSP 的真实站点端到端,测试站与正式站均通过)。
This commit is contained in:
1 parent
320cd6e4d0
commit
d41e85e288
6 files changed
+797
No files matched your search
@@ -96,6 +96,7 @@ npm run validate # 契约:ibwPlugin 字段、entry 语法、entry 内 mani
|
||||
```
|
||||
template/ # 最小可运行插件(复制它开始;手写单文件)
|
||||
xianyi-cutout/ # 真实插件:鲜艺抠图(A2 运行时插件,已发布到宿主 KV;手写单文件)
|
||||
white-bg-800/ # 真实插件:白底图(移植自 iwb-cutout-extension;已发布到宿主 KV;手写单文件)
|
||||
image-annotate/ # 真实插件:标注 / 修图(编辑器移植自 iwb-plaus;需要构建,见下节)
|
||||
scripts/ # validate.mjs(CI 必跑)+ build-plugin.mjs(仅需构建的插件用)
|
||||
```
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# 白底图(插件)
|
||||
|
||||
把选中节点的图**等比缩放、居中**合成到一张正方形大图上(白底或透明底),输出 `<name>_<size>x<size>.png`。
|
||||
典型用途:透明底抠图 → 电商主图白底大图(如 800×800)。
|
||||
|
||||
**移植自** `iwb-plaus` 仓库的 `iwb-cutout-extension`:
|
||||
- 源:`src/shared/image-math.js` 的 `fitRect`(等比缩放居中几何)+ `src/content.js` 的 `makeWhiteBgImage` / `performWhiteBg`(合成与写回流程)。
|
||||
- 只有宿主胶水(`IWBPluginHost` 注册 / `ctx` 调用)是新写的;几何与合成算法逐字对齐上游。
|
||||
|
||||
### 移植差异(有意为之)
|
||||
- **文件名用真实边长**:`<name>_<size>x<size>.png`(如 `photo_800x800.png`)。上游 `autoWhiteBg` 分支硬编码 `_800x800`,`bgSize` 改成别的也照样叫 800 —— 这是上游 bug,这里按夹取后的实际边长命名。
|
||||
- **不移植 `autoWhiteBg`**(抠图后自动转白底):本插件只做白底图这一件事,入口即功能。
|
||||
- **底色模式在设置里选**(`transparent` 开关),不是上游那种每次点击弹选择。
|
||||
- 上游的批量处理 / 下载 / 剪贴板等能力不在本插件范围。
|
||||
|
||||
## 入口
|
||||
- **节点漂浮菜单**「白底图」(`ref` / `out` / `gen` 节点)
|
||||
- 右键菜单「插件命令 → 白底图:选中节点」
|
||||
|
||||
## 设置
|
||||
| 键 | 类型 | 默认 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `bgSize` | number | 800 | 大图边长(像素);允许 64–4096,越界自动夹取 |
|
||||
| `ratioPct` | number | 85 | 内容等比缩放后占边长的百分比;允许 10–100 |
|
||||
| `transparent` | boolean | false | 关闭=填白底;开启=保留透明通道 |
|
||||
| `replace` | boolean | false | 关闭=新建参考图节点;开启=覆盖当前节点 |
|
||||
|
||||
## 远程图片
|
||||
`getNodeImage` 返回 `{ dataUrl }` 时直接赋给 `img.src`(`img-src` 放行 `data:`,不污染画布);
|
||||
**绝不对 `data:` URL 发网络请求**(宿主 CSP `connect-src` 不含 `data:`,必被拦 —— 姊妹插件 image-annotate 踩过并修掉的坑)。
|
||||
返回 `{ url }`(远程 http(s))时插件会尝试 `fetch` 并转成 blob: URL 再解码;失败(含跨域/鉴权拦截、非 2xx、解码失败)会提示
|
||||
「远程图片无法读取(可能被跨域限制):请先转存为本地位图」。
|
||||
|
||||
## 发布
|
||||
```bash
|
||||
cd /Users/qiqi/open/github/image-workbench-web
|
||||
cp /Users/qiqi/open/github/iwb-plugins/white-bg-800/src/index.js /tmp/plugin-white-bg-800.js
|
||||
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建 plugins/index.json,不做合并。
|
||||
# 只传自己 → 别的插件会从清单里消失(image-annotate 已实测踩到)。
|
||||
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
|
||||
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
|
||||
node scripts/plugins-publish.mjs /tmp/plugin-white-bg-800.js /tmp/plugin-xianyi-cutout.js /tmp/plugin-image-annotate.js \
|
||||
--version white-bg-800=1.0.0 # 默认 dry-run,检查 diff 后再加 --upload
|
||||
```
|
||||
|
||||
## 验证(开发用)
|
||||
- `tools/harness.mjs`:本地 mock 端到端 —— 合成宿主 + `addScriptTag` 加载插件源码本体,在真实 Chromium 里验证
|
||||
manifest / 注册 / `appliesTo` / 白底与透明底 / `fitRect` 居中 / 夹取 / 命名 / 写回 / 错误提示。需要 Playwright
|
||||
(可从宿主仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定),不进 CI。
|
||||
|
||||
```bash
|
||||
node white-bg-800/tools/harness.mjs
|
||||
```
|
||||
- `tools/e2e-site.mjs`:带 CSP 的真实站点端到端(真 KV + SRI + 漂浮菜单 → 新建节点),透明底等设置类用例由 harness 覆盖。
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/white-bg-800",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"description": "白底图:把节点图等比缩放居中合成到正方形画布(白底/透明底),输出 <name>_<size>x<size>.png",
|
||||
"ibwPlugin": { "id": "white-bg-800", "entry": "src/index.js", "apiVersion": 1 }
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// iwb-plugin: 白底图 —— 把选中节点的图等比缩放、居中合成到正方形画布(白底或透明底),输出 <name>_<size>x<size>.png。
|
||||
// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/shared/image-math.js 的 fitRect + src/content.js 的 makeWhiteBgImage / performWhiteBg;
|
||||
// 几何与合成算法逐字对齐上游,只有宿主胶水(IWBPluginHost 注册 / ctx 调用)是新写的。
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
// 上游 shared/image-math.js 的 clamp
|
||||
function clamp(v, min, max) {
|
||||
return Math.max(min, Math.min(max, v))
|
||||
}
|
||||
|
||||
// 上游 shared/image-math.js 的 fitRect:内容最长边 = min(boxW, boxH) * ratio,等比缩放并居中(不裁剪)
|
||||
function fitRect(srcW, srcH, boxW, boxH, ratio) {
|
||||
if (!(srcW > 0) || !(srcH > 0) || !(boxW > 0) || !(boxH > 0)) {
|
||||
return { x: 0, y: 0, w: 0, h: 0, scale: 0 }
|
||||
}
|
||||
var r = Math.max(0.01, Math.min(1, ratio))
|
||||
var maxLen = Math.min(boxW, boxH) * r
|
||||
var scale = Math.min(maxLen / srcW, maxLen / srcH)
|
||||
var w = srcW * scale
|
||||
var h = srcH * scale
|
||||
return { x: (boxW - w) / 2, y: (boxH - h) / 2, w: w, h: h, scale: scale }
|
||||
}
|
||||
|
||||
function loadImage(src) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var img = new Image()
|
||||
img.onload = function () { resolve(img) }
|
||||
img.onerror = function () { reject(new Error('图片解码失败')) }
|
||||
img.src = src
|
||||
})
|
||||
}
|
||||
|
||||
global.IWBPluginHost.register({
|
||||
id: 'white-bg-800',
|
||||
name: '白底图',
|
||||
version: '1.0.0',
|
||||
apiVersion: 1,
|
||||
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
|
||||
settings: {
|
||||
bgSize: { type: 'number', label: '大图边长(像素)', desc: '默认 800;允许 64–4096,越界自动夹取。', default: 800 },
|
||||
ratioPct: { type: 'number', label: '内容占比(%)', desc: '图片等比缩放后占边长的百分比,默认 85;允许 10–100。', default: 85 },
|
||||
transparent: { type: 'boolean', label: '透明底', desc: '关闭(默认)=填白底;开启=保留透明通道。', default: false },
|
||||
replace: { type: 'boolean', label: '覆盖原节点', desc: '关闭(默认)=新建参考图节点;开启=覆盖当前节点。', default: false },
|
||||
},
|
||||
}, function (ctx) {
|
||||
const NO_IMAGE = '该节点没有可编码的图片(请选中带图的参考图或输出节点)'
|
||||
const REMOTE_FAIL = '远程图片无法读取(可能被跨域限制):请先转存为本地位图'
|
||||
|
||||
async function runOne(nodeId, nodeName) {
|
||||
const image = await ctx.canvas.getNodeImage(nodeId)
|
||||
if (!image) throw new Error(NO_IMAGE)
|
||||
|
||||
// 解析可绘制的图源:dataUrl 直接赋给 img.src(img-src 放行 data:,不污染画布);
|
||||
// 绝不对 data: URL 发网络请求 —— 宿主 CSP connect-src 不含 data:,必被拦(姊妹插件 image-annotate 踩过并修掉的坑)。
|
||||
// 远程 url 才走 fetch,转成 blob: URL 再解码(blob: 同样不污染画布)。
|
||||
let img
|
||||
if (image.dataUrl) {
|
||||
img = await loadImage(image.dataUrl)
|
||||
} else if (image.url) {
|
||||
let resp
|
||||
try {
|
||||
resp = await global.fetch(image.url)
|
||||
} catch (e) {
|
||||
throw new Error(REMOTE_FAIL)
|
||||
}
|
||||
if (!resp.ok) throw new Error(REMOTE_FAIL)
|
||||
const objUrl = URL.createObjectURL(await resp.blob())
|
||||
try {
|
||||
img = await loadImage(objUrl)
|
||||
} catch (e) {
|
||||
throw new Error(REMOTE_FAIL)
|
||||
} finally {
|
||||
URL.revokeObjectURL(objUrl)
|
||||
}
|
||||
} else {
|
||||
throw new Error(NO_IMAGE)
|
||||
}
|
||||
|
||||
// 宿主可能把数值设置存成字符串,统一强转再夹取
|
||||
const size = clamp(Math.round(Number(ctx.settings.get('bgSize')) || 800), 64, 4096)
|
||||
const ratio = clamp(Number(ctx.settings.get('ratioPct')) || 85, 10, 100) / 100
|
||||
const transparent = Boolean(ctx.settings.get('transparent'))
|
||||
const replace = Boolean(ctx.settings.get('replace'))
|
||||
|
||||
// 合成(对齐上游 makeWhiteBgImage):正方形画布,白底或透明底,fitRect 等比缩放居中、不裁剪
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = size
|
||||
canvas.height = size
|
||||
const ctx2d = canvas.getContext('2d')
|
||||
if (!transparent) {
|
||||
ctx2d.fillStyle = '#ffffff'
|
||||
ctx2d.fillRect(0, 0, size, size)
|
||||
}
|
||||
const rect = fitRect(img.naturalWidth || img.width, img.naturalHeight || img.height, size, size, ratio)
|
||||
ctx2d.drawImage(img, rect.x, rect.y, rect.w, rect.h)
|
||||
const out = canvas.toDataURL('image/png')
|
||||
|
||||
// 命名用真实边长(上游 autoWhiteBg 分支硬编码 _800x800 是 bug,这里按夹取后的实际边长命名)
|
||||
const base = String(nodeName || 'image').replace(/\.[^.]+$/, '') || 'image'
|
||||
const name = base + '_' + size + 'x' + size + '.png'
|
||||
|
||||
if (replace) {
|
||||
const ok = ctx.canvas.setNodeImage(nodeId, out)
|
||||
if (!ok) throw new Error('写回画布失败')
|
||||
return true
|
||||
}
|
||||
const created = ctx.canvas.createImageNode({ dataUrl: out, name: name })
|
||||
if (!created) throw new Error('写回画布失败')
|
||||
return created
|
||||
}
|
||||
|
||||
ctx.nodeActions.register({
|
||||
id: 'white-bg-node',
|
||||
title: '白底图',
|
||||
icon: 'fit',
|
||||
appliesTo: function (node) { return Boolean(node) && (node.type === 'ref' || node.type === 'out' || node.type === 'gen') },
|
||||
run: function (node) { return runOne(node.id, node.name) },
|
||||
})
|
||||
|
||||
ctx.commands.register({
|
||||
id: 'white-bg-selected',
|
||||
title: '白底图:选中节点',
|
||||
icon: 'fit',
|
||||
run: function () {
|
||||
const selected = ctx.canvas.getSelectedNode()
|
||||
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
|
||||
return runOne(selected.id, selected.name)
|
||||
},
|
||||
})
|
||||
|
||||
return {}
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,199 @@
|
||||
// 真实站点端到端(开发用,不进 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-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(' 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\.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.png', Boolean(created && /^src_800x800\.png$/.test(created.name || '')), created && String(created.name))
|
||||
|
||||
// ---------- 8) 页内解引用 + 解码新建 PNG:800x800、左上像素为白色 ----------
|
||||
// 宿主「C3」引用模型:localStorage 里只存 { __blob: 'imgblob_<hash>_<len>' } 引用,字节在 IndexedDB
|
||||
//(src/image-blob-store.js / app.js「不把 base64 写进 localStorage」)—— 假设 localStorage 里有 base64 是
|
||||
// 不可能的(by design)。故在页内经 IWBImageBlobStore 解引用:resolveDataUrl 挂在 create() 实例上
|
||||
//(image-blob-store.js:140-142,冻结对象只暴露 create 等),与 app.js:730 同构:Lib.create({ idb: … })。
|
||||
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.__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) } // 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\/png;base64,/.test(r.dataUrl)) return { error: '解引用结果不是 PNG dataURL', head: 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 为 PNG 字节(blob 引用已解析)', Boolean(d.dataOk), d.dataOk ? d.via : dDiag)
|
||||
check('新建 PNG 解码尺寸 = 800x800', Boolean(d.dataOk && d.w === 800 && d.h === 800), d.dataOk ? d.w + 'x' + d.h : dDiag)
|
||||
check('新建 PNG 解码后左上像素 = 白色(255,255,255,255)', Boolean(d.dataOk && d.px && d.px[0] === 255 && d.px[1] === 255 && d.px[2] === 255 && 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)
|
||||
@@ -0,0 +1,402 @@
|
||||
// 白底图插件本地 mock 端到端(开发用,不进 CI)。
|
||||
//
|
||||
// 为什么需要它:合成链路(Image 解码 → Canvas 2D drawImage → toDataURL)只有真浏览器有 canvas,
|
||||
// node 侧测不了;这里用 addInitScript 装一个合成 window.IWBPluginHost(可注入的 ctx),
|
||||
// 再用 addScriptTag 加载插件源码本体(无构建、无 CSP 依赖),在真实 Chromium 里验证
|
||||
// manifest / 注册 / appliesTo / 白底与透明底 / fitRect 居中 / 夹取 / 命名 / 写回 / 错误提示。
|
||||
//
|
||||
// 运行:
|
||||
// node white-bg-800/tools/harness.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-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(' npm i -D playwright # 本仓或宿主仓皆可')
|
||||
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node white-bg-800/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 = 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))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 页内环境:合成宿主 + 记录器(__H__)+ 测量器(__M__) ----------
|
||||
const HOST_SETUP = () => {
|
||||
const H = {
|
||||
manifest: null,
|
||||
nodeActions: [],
|
||||
commands: [],
|
||||
calls: { setNodeImage: [], createImageNode: [] },
|
||||
inject: { image: null, selected: null, settings: {} },
|
||||
defaults: {},
|
||||
lastRun: null,
|
||||
}
|
||||
H.run = (actionId, node) => {
|
||||
const a = H.nodeActions.find((x) => x.id === actionId)
|
||||
if (a) return a.run(node || { id: 'n1', type: 'ref', name: 'photo.png' })
|
||||
const c = H.commands.find((x) => x.id === actionId)
|
||||
if (c) return c.run()
|
||||
return Promise.reject(new Error('unknown action: ' + actionId))
|
||||
}
|
||||
// 触发一次 run:清空调用记录,落账后 lastRun = { ok, value } | { ok: false, error }
|
||||
H.fire = (actionId, node) => {
|
||||
H.lastRun = null
|
||||
H.calls.setNodeImage.length = 0
|
||||
H.calls.createImageNode.length = 0
|
||||
H.run(actionId, node).then(
|
||||
(v) => { H.lastRun = { ok: true, value: v } },
|
||||
(e) => { H.lastRun = { ok: false, error: String(e && e.message) } }
|
||||
)
|
||||
return true
|
||||
}
|
||||
const ctx = {
|
||||
nodeActions: { register: (a) => { H.nodeActions.push(a) } },
|
||||
commands: { register: (c) => { H.commands.push(c) } },
|
||||
canvas: {
|
||||
getNodeImage: async () => H.inject.image,
|
||||
setNodeImage: (id, dataUrl) => { H.calls.setNodeImage.push({ id, dataUrl }); return true },
|
||||
createImageNode: (opts) => { H.calls.createImageNode.push({ dataUrl: opts && opts.dataUrl, name: opts && opts.name }); return 'new-node-' + (H.calls.createImageNode.length) },
|
||||
getSelectedNode: () => H.inject.selected,
|
||||
},
|
||||
settings: { get: (k) => (Object.prototype.hasOwnProperty.call(H.inject.settings, k) ? H.inject.settings[k] : H.defaults[k]) },
|
||||
log: { info() {}, warn() {}, error() {} },
|
||||
events: { on() {}, off() {}, emit() {} },
|
||||
storage: { get() { return undefined }, set() {}, remove() {} },
|
||||
}
|
||||
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
|
||||
// 测量:解码输出 → 尺寸 / 四角 / 内容 bbox(白底=非白像素,透明底=alpha>0)
|
||||
window.__M__ = async (dataUrl, mode, withBbox) => {
|
||||
const img = await new Promise((resolve, reject) => {
|
||||
const i = new Image()
|
||||
i.onload = () => resolve(i)
|
||||
i.onerror = () => reject(new Error('decode failed'))
|
||||
i.src = dataUrl
|
||||
})
|
||||
const c = document.createElement('canvas')
|
||||
c.width = img.naturalWidth || img.width
|
||||
c.height = img.naturalHeight || img.height
|
||||
const x = c.getContext('2d')
|
||||
x.drawImage(img, 0, 0)
|
||||
const d = x.getImageData(0, 0, c.width, c.height).data
|
||||
const at = (px, py) => { const o = (py * c.width + px) * 4; return [d[o], d[o + 1], d[o + 2], d[o + 3]] }
|
||||
const corners = [at(0, 0), at(c.width - 1, 0), at(0, c.height - 1), at(c.width - 1, c.height - 1)]
|
||||
let bbox = null
|
||||
if (withBbox) {
|
||||
let minX = Infinity, minY = Infinity, maxX = -1, maxY = -1
|
||||
for (let py = 0; py < c.height; py++) {
|
||||
for (let px = 0; px < c.width; px++) {
|
||||
const [r, g, b, a] = at(px, py)
|
||||
const isContent = mode === 'transparent' ? a > 0 : !(r === 255 && g === 255 && b === 255)
|
||||
if (isContent) {
|
||||
if (px < minX) minX = px
|
||||
if (px > maxX) maxX = px
|
||||
if (py < minY) minY = py
|
||||
if (py > maxY) maxY = py
|
||||
}
|
||||
}
|
||||
}
|
||||
if (maxX >= 0) bbox = { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 }
|
||||
}
|
||||
return { width: c.width, height: c.height, corners, bbox }
|
||||
}
|
||||
}
|
||||
|
||||
console.log('目标:本地 mock 页(about:blank)+ 插件源码 ' + PLUGIN_ENTRY)
|
||||
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))
|
||||
|
||||
await page.addInitScript(HOST_SETUP)
|
||||
await page.goto('about:blank')
|
||||
check('合成宿主已注入(__H__ / IWBPluginHost)', await page.evaluate(() => Boolean(window.__H__ && window.IWBPluginHost)))
|
||||
|
||||
await page.addScriptTag({ path: PLUGIN_ENTRY })
|
||||
check('插件已加载并完成注册', await page.evaluate(() => Boolean(window.__H__ && window.__H__.manifest)))
|
||||
|
||||
// ---------- 1) manifest ----------
|
||||
const m = await page.evaluate(() => window.__H__.manifest)
|
||||
check('manifest:id = white-bg-800', m.id === 'white-bg-800', String(m.id))
|
||||
check('manifest:name = 白底图', m.name === '白底图', String(m.name))
|
||||
check('manifest:version = 1.0.0', m.version === '1.0.0', String(m.version))
|
||||
check('manifest:apiVersion = 1', m.apiVersion === 1, String(m.apiVersion))
|
||||
check('manifest:capabilities = [commands, canvas, canvasWrite, nodeActions]',
|
||||
JSON.stringify(m.capabilities) === JSON.stringify(['commands', 'canvas', 'canvasWrite', 'nodeActions']), JSON.stringify(m.capabilities))
|
||||
const wantSettings = {
|
||||
bgSize: { type: 'number', default: 800 },
|
||||
ratioPct: { type: 'number', default: 85 },
|
||||
transparent: { type: 'boolean', default: false },
|
||||
replace: { type: 'boolean', default: false },
|
||||
}
|
||||
check('manifest:settings 恰好 4 键(bgSize/ratioPct/transparent/replace)',
|
||||
JSON.stringify(Object.keys(m.settings || {}).sort()) === JSON.stringify(Object.keys(wantSettings).sort()),
|
||||
JSON.stringify(Object.keys(m.settings || {})))
|
||||
for (const [k, want] of Object.entries(wantSettings)) {
|
||||
const s = (m.settings || {})[k]
|
||||
check('manifest:settings.' + k + '(type=' + want.type + ', default=' + want.default + ')',
|
||||
Boolean(s) && s.type === want.type && s.default === want.default,
|
||||
s ? (s.type + ' / ' + String(s.default)) : '缺失')
|
||||
}
|
||||
|
||||
// ---------- 2) 注册 ----------
|
||||
const reg = await page.evaluate(() => ({
|
||||
nodeActions: window.__H__.nodeActions.map((a) => ({ id: a.id, title: a.title, icon: a.icon })),
|
||||
commands: window.__H__.commands.map((c) => ({ id: c.id, title: c.title, icon: c.icon })),
|
||||
}))
|
||||
check('恰好 1 个 nodeAction:white-bg-node / 白底图 / icon=fit',
|
||||
reg.nodeActions.length === 1 && reg.nodeActions[0].id === 'white-bg-node' && reg.nodeActions[0].title === '白底图' && reg.nodeActions[0].icon === 'fit',
|
||||
JSON.stringify(reg.nodeActions))
|
||||
check('恰好 1 个 command:white-bg-selected',
|
||||
reg.commands.length === 1 && reg.commands[0].id === 'white-bg-selected',
|
||||
JSON.stringify(reg.commands))
|
||||
|
||||
// ---------- 3) appliesTo ----------
|
||||
const applies = await page.evaluate(() => {
|
||||
const a = window.__H__.nodeActions[0]
|
||||
return ['ref', 'out', 'gen', 'prompt'].map((t) => ({ type: t, ok: a.appliesTo({ id: 'n1', type: t }) }))
|
||||
})
|
||||
for (const r of applies) {
|
||||
const want = r.type !== 'prompt'
|
||||
check('appliesTo:type=' + r.type + ' → ' + want, r.ok === want, String(r.ok))
|
||||
}
|
||||
|
||||
// ---------- 源图(纯色 PNG,bbox 即绘制矩形) ----------
|
||||
await page.evaluate(() => {
|
||||
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')
|
||||
}
|
||||
window.__SRC__ = { rect: make(400, 200, '#2f6fed'), square: make(300, 300, '#e8a13c') }
|
||||
})
|
||||
|
||||
// 触发一次 run 并等落账;返回紧凑结果(成功含调用摘要,失败含错误信息)
|
||||
const fire = async (setup) => {
|
||||
await page.evaluate(setup)
|
||||
await poll(() => page.evaluate(() => Boolean(window.__H__.lastRun)))
|
||||
return page.evaluate(() => {
|
||||
const H = window.__H__
|
||||
if (!H.lastRun) return { ok: false, error: '(超时未完成)' }
|
||||
const png = (s) => /^data:image\/png/.test(String(s))
|
||||
return {
|
||||
ok: H.lastRun.ok,
|
||||
error: H.lastRun.ok ? null : H.lastRun.error,
|
||||
setNodeImage: H.calls.setNodeImage.map((c) => ({ id: c.id, isPng: png(c.dataUrl) })),
|
||||
createImageNode: H.calls.createImageNode.map((c) => ({ name: c.name, isPng: png(c.dataUrl) })),
|
||||
}
|
||||
})
|
||||
}
|
||||
// 解码测量最近一次新建节点的输出
|
||||
const measure = async (mode, withBbox = true) => {
|
||||
const dataUrl = await page.evaluate(() => (window.__H__.calls.createImageNode.length ? window.__H__.calls.createImageNode[0].dataUrl : null))
|
||||
return dataUrl ? page.evaluate(({ d, md, bb }) => window.__M__(d, md, bb), { d: dataUrl, md: mode, bb: withBbox }) : null
|
||||
}
|
||||
|
||||
// ---------- 4) 白底模式(默认设置) ----------
|
||||
const r4 = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = {}
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
|
||||
})
|
||||
check('白底模式:run 成功、恰好新建 1 个 data:image/png 节点',
|
||||
r4.ok && r4.createImageNode.length === 1 && r4.createImageNode[0].isPng, r4.ok ? '' : String(r4.error))
|
||||
const m4 = await measure('white')
|
||||
check('白底模式:输出 800×800', Boolean(m4) && m4.width === 800 && m4.height === 800, m4 ? (m4.width + '×' + m4.height) : '未取得输出')
|
||||
check('白底模式:四角 #ffffff',
|
||||
Boolean(m4) && m4.corners.every((p) => p[0] === 255 && p[1] === 255 && p[2] === 255), m4 ? JSON.stringify(m4.corners) : '')
|
||||
check('白底模式:内容 bbox 680×340 居中(±2px)',
|
||||
Boolean(m4) && m4.bbox && Math.abs(m4.bbox.w - 680) <= 2 && Math.abs(m4.bbox.h - 340) <= 2 && Math.abs(m4.bbox.x - 60) <= 2 && Math.abs(m4.bbox.y - 230) <= 2,
|
||||
m4 && m4.bbox ? JSON.stringify(m4.bbox) : '')
|
||||
|
||||
// ---------- 5) 透明底模式 ----------
|
||||
const r5 = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = { transparent: true }
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
|
||||
})
|
||||
check('透明底模式:run 成功、恰好新建 1 个节点', r5.ok && r5.createImageNode.length === 1, r5.ok ? '' : String(r5.error))
|
||||
const m5 = await measure('transparent')
|
||||
check('透明底模式:四角 alpha = 0',
|
||||
Boolean(m5) && m5.corners.every((p) => p[3] === 0), m5 ? JSON.stringify(m5.corners) : '')
|
||||
|
||||
// ---------- 6) 方图 ----------
|
||||
const r6 = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.square }
|
||||
window.__H__.inject.settings = {}
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'square.png' })
|
||||
})
|
||||
check('方图 300×300:run 成功、恰好新建 1 个节点', r6.ok && r6.createImageNode.length === 1, r6.ok ? '' : String(r6.error))
|
||||
const m6 = await measure('white')
|
||||
check('方图 300×300:内容 bbox 680×680 居中(±2px)',
|
||||
Boolean(m6) && m6.bbox && Math.abs(m6.bbox.w - 680) <= 2 && Math.abs(m6.bbox.h - 680) <= 2 && Math.abs(m6.bbox.x - 60) <= 2 && Math.abs(m6.bbox.y - 60) <= 2,
|
||||
m6 && m6.bbox ? JSON.stringify(m6.bbox) : '')
|
||||
|
||||
// ---------- 7) 夹取 ----------
|
||||
const r7a = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = { bgSize: 10 }
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'a.png' })
|
||||
})
|
||||
const m7a = await measure('white', false)
|
||||
check('夹取:bgSize=10 → 输出 64×64', r7a.ok && Boolean(m7a) && m7a.width === 64 && m7a.height === 64, m7a ? (m7a.width + '×' + m7a.height) : String(r7a.error))
|
||||
|
||||
const r7b = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = { bgSize: 99999 }
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'b.png' })
|
||||
})
|
||||
const m7b = await measure('white', false)
|
||||
check('夹取:bgSize=99999 → 输出 4096×4096', r7b.ok && Boolean(m7b) && m7b.width === 4096 && m7b.height === 4096, m7b ? (m7b.width + '×' + m7b.height) : String(r7b.error))
|
||||
|
||||
const r7c = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = { ratioPct: 200 }
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'c.png' })
|
||||
})
|
||||
const m7c = await measure('white')
|
||||
check('夹取:ratioPct=200 → 内容 bbox 宽 = 整边(800)',
|
||||
r7c.ok && Boolean(m7c) && m7c.bbox && m7c.bbox.w === 800, m7c && m7c.bbox ? JSON.stringify(m7c.bbox) : String(r7c.error))
|
||||
|
||||
const r7d = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = { ratioPct: 1 }
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'd.png' })
|
||||
})
|
||||
const m7d = await measure('white')
|
||||
check('夹取:ratioPct=1 → 内容 bbox 宽 = 10% 边长(80)',
|
||||
r7d.ok && Boolean(m7d) && m7d.bbox && m7d.bbox.w === 80, m7d && m7d.bbox ? JSON.stringify(m7d.bbox) : String(r7d.error))
|
||||
|
||||
// ---------- 8) 命名 ----------
|
||||
const r8a = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = {}
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
|
||||
})
|
||||
check('命名:photo.png → photo_800x800.png',
|
||||
r8a.ok && r8a.createImageNode.length === 1 && r8a.createImageNode[0].name === 'photo_800x800.png',
|
||||
r8a.createImageNode.length ? String(r8a.createImageNode[0].name) : String(r8a.error))
|
||||
|
||||
const r8b = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = {}
|
||||
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: '' })
|
||||
})
|
||||
check('命名:空名 → image_800x800.png',
|
||||
r8b.ok && r8b.createImageNode.length === 1 && r8b.createImageNode[0].name === 'image_800x800.png',
|
||||
r8b.createImageNode.length ? String(r8b.createImageNode[0].name) : String(r8b.error))
|
||||
|
||||
// ---------- 9) replace=true ----------
|
||||
const r9 = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = { replace: true }
|
||||
window.__H__.fire('white-bg-node', { id: 'n9', type: 'ref', name: 'photo.png' })
|
||||
})
|
||||
check('replace=true:setNodeImage 恰好 1 次、data:image/png、id 正确',
|
||||
r9.ok && r9.setNodeImage.length === 1 && r9.setNodeImage[0].isPng && r9.setNodeImage[0].id === 'n9',
|
||||
r9.ok ? JSON.stringify(r9.setNodeImage) : String(r9.error))
|
||||
check('replace=true:createImageNode 未被调用', r9.ok && r9.createImageNode.length === 0, String(r9.createImageNode.length))
|
||||
|
||||
// ---------- 10) replace=false ----------
|
||||
const r10 = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = {}
|
||||
window.__H__.fire('white-bg-node', { id: 'n10', type: 'ref', name: 'photo.png' })
|
||||
})
|
||||
check('replace=false:createImageNode 恰好 1 次(dataUrl + name)',
|
||||
r10.ok && r10.createImageNode.length === 1 && r10.createImageNode[0].isPng && r10.createImageNode[0].name === 'photo_800x800.png',
|
||||
r10.ok ? JSON.stringify(r10.createImageNode) : String(r10.error))
|
||||
|
||||
// ---------- 11) 无图 ----------
|
||||
const r11 = await fire(() => {
|
||||
window.__H__.inject.image = null
|
||||
window.__H__.inject.settings = {}
|
||||
window.__H__.fire('white-bg-node', { id: 'n11', type: 'ref', name: 'photo.png' })
|
||||
})
|
||||
check('无图:拒绝「该节点没有可编码的图片(请选中带图的参考图或输出节点)」',
|
||||
!r11.ok && r11.error === '该节点没有可编码的图片(请选中带图的参考图或输出节点)', String(r11.error))
|
||||
|
||||
// ---------- 12) 远程图 fetch 失败 ----------
|
||||
const r12 = await fire(() => {
|
||||
window.__H__.inject.image = { url: 'https://example.com/x.png' }
|
||||
window.__H__.inject.settings = {}
|
||||
if (!window.__ORIG_FETCH__) window.__ORIG_FETCH__ = window.fetch
|
||||
window.fetch = function () { return Promise.reject(new Error('blocked')) }
|
||||
window.__H__.fire('white-bg-node', { id: 'n12', type: 'ref', name: 'photo.png' })
|
||||
})
|
||||
await page.evaluate(() => { if (window.__ORIG_FETCH__) { window.fetch = window.__ORIG_FETCH__; window.__ORIG_FETCH__ = null } })
|
||||
check('远程图 fetch 失败:拒绝「远程图片无法读取(可能被跨域限制):请先转存为本地位图」',
|
||||
!r12.ok && r12.error === '远程图片无法读取(可能被跨域限制):请先转存为本地位图', String(r12.error))
|
||||
|
||||
// ---------- 命令入口(getSelectedNode 注入) ----------
|
||||
const c1 = await fire(() => {
|
||||
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
|
||||
window.__H__.inject.settings = {}
|
||||
window.__H__.inject.selected = { id: 'sel1', type: 'ref', name: 'picked.jpg' }
|
||||
window.__H__.fire('white-bg-selected')
|
||||
})
|
||||
check('命令入口:选中 picked.jpg → picked_800x800.png',
|
||||
c1.ok && c1.createImageNode.length === 1 && c1.createImageNode[0].name === 'picked_800x800.png',
|
||||
c1.createImageNode.length ? String(c1.createImageNode[0].name) : String(c1.error))
|
||||
|
||||
const c2 = await fire(() => {
|
||||
window.__H__.inject.selected = null
|
||||
window.__H__.fire('white-bg-selected')
|
||||
})
|
||||
check('命令入口:未选中 → 拒绝「请先选中一个带图的节点」',
|
||||
!c2.ok && c2.error === '请先选中一个带图的节点', String(c2.error))
|
||||
|
||||
// ---------- 13) 静态检查(node 侧读源码) ----------
|
||||
const offenders = []
|
||||
for (const [i, line] of readFileSync(PLUGIN_ENTRY, 'utf8').split('\n').entries()) {
|
||||
const n = i + 1
|
||||
if (/fetch\(\s*(['"])data:/.test(line)) offenders.push(n + ': fetch(data:) → ' + line.trim())
|
||||
if (/fetch\(\s*[\w.$]*[Dd]ataUrl\b/.test(line)) offenders.push(n + ': fetch(*dataUrl) → ' + line.trim())
|
||||
if (/\beval\s*\(/.test(line)) offenders.push(n + ': eval → ' + line.trim())
|
||||
if (/new\s+Function\s*\(/.test(line)) offenders.push(n + ': new Function → ' + line.trim())
|
||||
if (/\bimport\b/.test(line)) offenders.push(n + ': import → ' + line.trim())
|
||||
if (/\brequire\s*\(/.test(line)) offenders.push(n + ': require → ' + line.trim())
|
||||
}
|
||||
check('静态检查:无 fetch(data:) / eval / new Function / import / require', offenders.length === 0, offenders.slice(0, 3).join(' | '))
|
||||
|
||||
// ---------- 收尾 ----------
|
||||
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
|
||||
|
||||
await browser.close()
|
||||
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
|
||||
process.exit(failed ? 1 : 0)
|
||||
Reference in new issue
Block a user