Files

212 lines
12 KiB
JavaScript
Raw Permalink 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.
// v3.0.x §13.34.7 第 2 条落地:**新写入**主通道 = IDB Blob(`{__blob: 'imgblob_…'}`),Cache Storage(`{__cache}`)退居兜底。
// 契约①(新写入):新保存的图片引用形态必须是 `{__blob}`,且 IDB 里该键存的是 **Blob**(不是 base64 字符串)。
// A/B(可回退开关):`localStorage['iwb_img_write'] = 'cache'` ⇒ 新写入回到 `{__cache}`;A/B 两态都要求
// 刷新后「画布 base64 = 0 字节」且图片全部正常解码显示(省内存不得牺牲功能)。
// 契约②(兼容守护):存量 `{__cache}` 引用仍能正常显示 —— 只改新写入,**绝不**做存量批量迁移、也绝不误删。
// 运行:npm run build && IWB_E2E_SPECS=tests/iwb-blob-write.spec.js node scripts/serve-test.js
const { test, expect } = require('./_pw-coverage')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1500, height: 1000 } })
const BOARD_KEY = 'iwb_ws_w1'
const BOARD = {
id: 'w1', name: 'BLOB', edges: [], groups: [],
nodes: [{ id: 'r1', type: 'ref', x: 120, y: 140, data: { url: '', data: '', name: 'big.png', localName: null } }],
}
// 只在**首次导航**种数据;reload 必须保留真实存储(否则会把刚保存的引用冲掉,也测不了跨刷新的开关)。
// sessionStorage 在同一标签内跨 reload 保留,因此这里用它当「已种过」的标记。
function seedOnce(page, board) {
return page.addInitScript((b) => {
window.__IWB_E2E__ = true
try {
if (sessionStorage.getItem('iwb_e2e_seeded') === '1') return
sessionStorage.setItem('iwb_e2e_seeded', '1')
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], outputsRetention: { enabled: true, maxFiles: 500, maxDays: 15 }, canvas: {} }))
localStorage.setItem('iwb_web_workspaces', JSON.stringify({ workspaces: [b], activeId: 'w1', rev: 1 }))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(b))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
} catch (e) { /* ignore */ }
}, board)
}
// 首屏在「我的画布」列表 → 双击进画布;后续 reload 会恢复上次视图(可能已是画布)。两种情况都要能进。
async function ensureCanvas(page) {
await page.waitForTimeout(700)
const card = page.locator('.iwb-home-card:not(.iwb-home-new)').first()
if ((await card.count()) > 0 && await card.isVisible().catch(() => false)) await card.dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible({ timeout: 20000 })
}
// 把一张 MB 级原图 base64 注入内存中的参考图节点(绕开 localStorage 配额,正是真实「上传原图」现场)。
// seed 不同 ⇒ 内容不同 ⇒ 哈希不同(A/B 两组各用一张,避免互相命中同一 key)。
async function injectBigImage(page, seed) {
return page.evaluate((s) => {
const c = document.createElement('canvas')
c.width = 1200; c.height = 900
const x = c.getContext('2d')
for (let i = 0; i < 1200; i++) {
const h = (((i + s) * 2654435761) >>> 0) % 0xffffff
x.fillStyle = '#' + h.toString(16).padStart(6, '0')
x.fillRect((i * (37 + s)) % 1160, (i * (91 + s)) % 870, 40, 30)
}
const dataUrl = c.toDataURL('image/jpeg', 0.95)
const ok = window.__IWB_E2E_SETREF__('r1', dataUrl)
return { len: dataUrl.length, ok: !!ok }
}, Number(seed) || 0)
}
// 读盘上(localStorage)的节点图形态:引用 kind / key、是否残留 base64。
const storedState = (page, key) => page.evaluate((k) => {
const raw = localStorage.getItem(k) || ''
let o = null
try { o = JSON.parse(raw) } catch (e) { o = null }
const nodes = (o && (o.nodes || (o.workspaces && o.workspaces[0] && o.workspaces[0].nodes))) || []
const n = nodes.find((x) => x && x.id === 'r1') || {}
const d = (n.data || {}).data
return {
rawLen: raw.length,
hasBase64: raw.indexOf('data:image/') >= 0,
kind: typeof d === 'string' ? ('string:' + d.length) : ((d && Object.keys(d)[0]) || 'none'),
key: (d && typeof d === 'object' && (d.__blob || d.__cache)) || '',
}
}, key)
// IDB 里该 key 存的是 Blob 还是字符串(契约①的硬判据)
const idbKind = (page, key) => page.evaluate(async (k) => {
if (!k) return 'n/a'
const db = await new Promise((res) => {
const r = indexedDB.open('iwb_web', 3)
r.onsuccess = () => res(r.result)
r.onerror = () => res(null)
r.onupgradeneeded = () => { const d = r.result; for (const s of ['images', 'logs', 'kv']) if (!d.objectStoreNames.contains(s)) d.createObjectStore(s) }
})
if (!db) return 'no-db'
return await new Promise((res) => {
const t = db.transaction('images', 'readonly')
const g = t.objectStore('images').get(k)
g.onsuccess = () => res(g.result ? (g.result instanceof Blob ? 'Blob' : typeof g.result) : 'MISS')
g.onerror = () => res('ERR')
})
}, key)
// 刷新后的画布指标:画布节点里的 base64 字节数(目标 0)+ 引用形态 + 图片是否真解码(naturalWidth > 0)
const canvasMetrics = (page) => page.evaluate(() => {
const nodes = (typeof window.__IWB_E2E_CANVAS__ === 'function') ? window.__IWB_E2E_CANVAS__() : []
let base64 = 0
const kinds = {}
for (const n of nodes) {
const d = (n && n.data) || {}
for (const f of ['data', 'url']) {
const v = d[f]
if (typeof v === 'string' && v.indexOf('data:') === 0) base64 += v.length
else if (v && typeof v === 'object') { const k = Object.keys(v)[0] || 'obj'; kinds[k] = (kinds[k] || 0) + 1 }
}
}
const imgs = Array.from(document.querySelectorAll('[data-node-id="r1"] .iwb-ref-single'))
return {
base64, kinds, imgCount: imgs.length,
decoded: imgs.filter((i) => i.naturalWidth > 0).length,
nw: imgs.length ? imgs[0].naturalWidth : -1,
}
})
test('契约①新写入:{__blob} + IDB 内为 Blob;A/B 开关关闭回 {__cache};两态画布 base64 均为 0 且图片正常显示', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
await seedOnce(page, BOARD)
await page.goto('/', { waitUntil: 'domcontentloaded' })
await ensureCanvas(page)
// ---- A 组:默认开关(新通道 = IDB Blob)----
const injA = await injectBigImage(page, 1)
expect(injA.ok, '应能把 MB 级原图注入内存中的节点').toBe(true)
expect(injA.len).toBeGreaterThan(3000)
await expect.poll(async () => (await storedState(page, BOARD_KEY)).kind, { timeout: 25000 }).toBe('__blob')
const a = await storedState(page, BOARD_KEY)
const aIdb = await idbKind(page, a.key)
console.log('[A/blob] ' + JSON.stringify({ stored: a, idb: aIdb, injected: injA.len }))
expect(a.key.indexOf('imgblob_'), 'Blob 键应带 imgblob_ 前缀(GC 依赖该前缀)').toBe(0)
expect(aIdb, 'IDB 里该键必须是 Blob(不是 base64 字符串)').toBe('Blob')
expect(a.hasBase64, '保存后 localStorage 不得残留图片 base64').toBe(false)
// 刷新 → 引用直出:画布 base64 必须为 0,且图真能解码显示
await page.reload({ waitUntil: 'domcontentloaded' })
await ensureCanvas(page)
await expect.poll(() => page.evaluate(() => { const i = document.querySelector('[data-node-id="r1"] .iwb-ref-single'); return i ? i.naturalWidth : 0 }), { timeout: 20000 }).toBeGreaterThan(0)
const aAfter = await canvasMetrics(page)
console.log('[A/after-reload] ' + JSON.stringify(aAfter))
expect(aAfter.base64, '刷新后画布 base64 必须为 0 字节').toBe(0)
expect(aAfter.kinds.__blob || 0, '刷新后画布上的图应是 {__blob} 引用').toBeGreaterThan(0)
expect(aAfter.decoded, '所有图片都必须在画布上正常解码显示').toBe(aAfter.imgCount)
expect(aAfter.imgCount).toBeGreaterThan(0)
// ---- B 组:运行期回退开关 → 新写入必须回到 {__cache}(一条改动可回退)----
await page.evaluate(() => localStorage.setItem('iwb_img_write', 'cache'))
await page.reload({ waitUntil: 'domcontentloaded' })
await ensureCanvas(page)
const injB = await injectBigImage(page, 7)
expect(injB.ok).toBe(true)
await expect.poll(async () => (await storedState(page, BOARD_KEY)).kind, { timeout: 25000 }).toBe('__cache')
const b = await storedState(page, BOARD_KEY)
console.log('[B/cache] ' + JSON.stringify({ stored: b, injected: injB.len }))
expect(b.key.indexOf('/__iwb_cache__/') > 0, '开关关闭后新写入必须回到 Cache Storage 虚拟路径').toBe(true)
expect(b.hasBase64).toBe(false)
await page.reload({ waitUntil: 'domcontentloaded' })
await ensureCanvas(page)
await expect.poll(() => page.evaluate(() => { const i = document.querySelector('[data-node-id="r1"] .iwb-ref-single'); return i ? i.naturalWidth : 0 }), { timeout: 20000 }).toBeGreaterThan(0)
const bAfter = await canvasMetrics(page)
console.log('[B/after-reload] ' + JSON.stringify(bAfter))
expect(bAfter.base64, 'B 组刷新后画布 base64 也必须为 0 字节').toBe(0)
expect(bAfter.kinds.__cache || 0).toBeGreaterThan(0)
expect(bAfter.decoded).toBe(bAfter.imgCount)
expect(errors).toEqual([])
})
test('契约②兼容守护:存量 {__cache} 引用仍能正常显示(不迁移成 {__blob}、不被清理)', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
await seedOnce(page, BOARD)
await page.goto('/', { waitUntil: 'domcontentloaded' })
// 首页阶段:把「历史 {__cache} 指向的字节」写进 Cache Storage(模拟存量数据),并把节点数据换成存量引用形态
const seeded = await page.evaluate(async () => {
const c = document.createElement('canvas')
c.width = 640; c.height = 480
const x = c.getContext('2d')
for (let i = 0; i < 640; i++) {
const h = ((i * 2654435761) >>> 0) % 0xffffff
x.fillStyle = '#' + h.toString(16).padStart(6, '0')
x.fillRect((i * 37) % 600, (i * 91) % 440, 40, 30)
}
const dataUrl = c.toDataURL('image/png')
const bin = atob(dataUrl.split(',')[1])
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
const url = new URL('/__iwb_cache__/legacy_cache_ref_test', location.origin).href
const cache = await caches.open('iwb-images-local')
await cache.put(url, new Response(new Blob([bytes], { type: 'image/png' }), { headers: { 'Content-Type': 'image/png' } }))
const board = { id: 'w1', name: 'LEGACY', edges: [], groups: [], nodes: [{ id: 'r1', type: 'ref', x: 120, y: 140, data: { url: '', data: { __cache: url }, name: 'legacy.png', localName: null } }] }
localStorage.setItem('iwb_ws_w1', JSON.stringify(board))
localStorage.setItem('iwb_web_workspaces', JSON.stringify({ workspaces: [board], activeId: 'w1', rev: 1 }))
return { len: dataUrl.length, url }
})
expect(seeded.len).toBeGreaterThan(3000)
await page.reload({ waitUntil: 'domcontentloaded' })
await ensureCanvas(page)
await expect.poll(() => page.evaluate(() => { const i = document.querySelector('[data-node-id="r1"] .iwb-ref-single'); return i ? i.naturalWidth : 0 }), { timeout: 20000 }).toBeGreaterThan(0)
const st = await storedState(page, BOARD_KEY)
const live = await canvasMetrics(page)
console.log('[legacy/cache] ' + JSON.stringify({ stored: st, live: live, seededLen: seeded.len }))
expect(st.kind, '存量形态必须仍是 {__cache}(不迁移成 {__blob})').toBe('__cache')
expect(st.key.indexOf('/__iwb_cache__/') > 0).toBe(true)
expect(st.hasBase64, 'localStorage 不得残留图片 base64').toBe(false)
expect(live.base64, '画布 base64 必须为 0 字节').toBe(0)
expect(live.kinds.__cache || 0).toBeGreaterThan(0)
expect(live.decoded, '存量 {__cache} 的图必须正常解码显示').toBe(live.imgCount)
expect(live.imgCount).toBeGreaterThan(0)
expect(errors).toEqual([])
})