Files
image-workbench-desktop/src/image-cache-migrate.js
T

65 lines
3.1 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.
/* image-cache-migrate.js —— {__cache} → {__blob} 一次性物化(2026-11-29)
*
* 为什么:Cache Storage 是**按站点隔离**的。网页版把图写进 https://iwb.maqiart.eu.org 的缓存,
* 桌面端跑在 tauri://localhost,读不到 → 图片变成破图图标(用户实测 146 个节点受影响)。
* 所以只要某个 {__cache} 引用**还能读出来**,就立刻把字节复制进资料目录({__blob} 主通道),
* 从此不再依赖 Cache Storage。
*
* 纪律:
* · 只改「能读到字节」的引用;读不到就原地不动(绝不写坏数据)。
* · 每个画板对象只跑一次(WeakSet),避免反复 hydrate 时重复读盘。
* · 就地改 node.data 里的引用对象(宿主下一次自动保存即落盘)。
*/
;(function (global) {
'use strict'
const done = new WeakSet()
// v3.26.119:读不出来的 {__cache} 键记下来 —— 桌面端没有 Service Worker 直出,
// 这类引用(网页版留下的)**永远**读不到。原来每次加载画板都重试一轮(日志里
// `cache-migrate ok=0 fail=4` 从早刷到晚),纯浪费 I/O,也让人误以为「还在迁移」。
const failedKeys = new Set()
// 收集所有 {__cache} 引用对象(引用本身是可变对象,直接原地改)
function collect (value, out) {
if (!value || typeof value !== 'object') return
if (Array.isArray(value)) { for (const v of value) collect(v, out); return }
if (typeof value.__cache === 'string' && value.__cache) { out.push(value); return }
for (const k of Object.keys(value)) collect(value[k], out)
}
function once (board, deps) {
const d = deps || {}
if (!board || !board.id || done.has(board)) return Promise.resolve({ skipped: true })
if (typeof d.read !== 'function' || typeof d.write !== 'function') return Promise.resolve({ skipped: true })
done.add(board)
const refs = []
collect(board.nodes, refs)
if (!refs.length) return Promise.resolve({ total: 0, ok: 0, fail: 0 })
let ok = 0
let fail = 0
const step = (i) => {
if (i >= refs.length) {
if (ok && typeof d.bump === 'function') { try { d.bump() } catch (e) { /* ignore */ } }
return { total: refs.length, ok: ok, fail: fail }
}
const ref = refs[i]
if (failedKeys.has(ref.__cache)) { fail++; return step(i + 1) }
return Promise.resolve()
.then(() => d.read(ref.__cache))
.then((dataUrl) => (dataUrl ? d.write(dataUrl) : null))
.then((next) => {
if (next && typeof next === 'object' && (next.__blob || next.__cache || next.__file)) {
delete ref.__cache
Object.assign(ref, next)
ok++
} else { failedKeys.add(ref.__cache); fail++ }
})
.catch(() => { failedKeys.add(ref.__cache); fail++ })
.then(() => step(i + 1))
}
return Promise.resolve().then(() => step(0)).catch(() => ({ total: refs.length, ok: ok, fail: fail }))
}
function failedCount () { return failedKeys.size }
global.IWBImageCacheMigrate = { once: once, _collect: collect, failedCount: failedCount }
})(typeof window !== 'undefined' ? window : globalThis)