/* plugin-data.js —— 插件数据层(v3.25.42 / M2) * * 目标:给插件一块**属于自己的、容量够用的**结构化存储。 * · 桌面:<资料目录>/plugin-data/.json(原子写:tmp + rename) * · 非桌面(jsdom / playwright 测试):localStorage,再兜底为内存 * · 同一插件的写入串行排队,避免「读-改-写」互相覆盖 * · 单文件上限 maxBytes(默认 2MiB,最多 16MiB),超限抛错、不静默截断 * * 旧数据迁移: * 老版本把所有插件数据塞在 localStorage['iwb_plugins'][id].data 里。 * stripLegacy() 在启动时把它们搬到 iwb_plugin_data_legacy 暂存(同步、不动磁盘), * read() 首次命中时再落到 plugin-data/.json 并清掉暂存 —— 避免启动期等 IO。 */ ;(function (global) { 'use strict' const DEFAULT_MAX = 2 * 1024 * 1024 const HARD_MAX = 16 * 1024 * 1024 const LEGACY_KEY = 'iwb_plugin_data_legacy' const mem = new Map() // 无 localStorage / 无 Tauri 时的最后兜底 const known = new Set() // 本次会话写过的 id(用于备份枚举;持久枚举靠文件 list / localStorage 前缀) const queues = new Map() function stateStore () { const S = global.IWBStorageLocal return (S && typeof S.getStore === 'function') ? S.getStore() : null } // 统一走 IWBStorageLocal 门面(src 内不得直调 localStorage;存储收敛守门会拦) function lsGetRaw (key) { try { const st = stateStore() if (!st) return null const v = st.rawGet(key, null) if (v == null) return null if (typeof v !== 'string') return v try { return JSON.parse(v) } catch (e) { return v } } catch (e) { return null } } function lsSetRaw (key, value) { try { const st = stateStore() if (!st) return false return !!st.rawSet(key, typeof value === 'string' ? value : JSON.stringify(value)) } catch (e) { return false } } function lsDelRaw (key) { try { const st = stateStore(); return !!(st && st.remove && st.remove(key)) } catch (e) { return false } } function fileBackend () { const F = global.IWBStorageFile if (!F || typeof F.enabled !== 'function' || !F.enabled()) return null // 非桌面(测试/浏览器)没有真实 FS const d = F.pluginData return (d && typeof d.read === 'function') ? d : null } function bytesOf (text) { try { return new global.TextEncoder().encode(String(text)).length } catch (e) { return String(text).length } } function base64Ids (id) { return 'iwb_plugin_data_' + id } async function readRaw (id, backend) { known.add(id) const b = backend || fileBackend() if (b) { try { const t = await b.read(id); if (t != null) return String(t) } catch (e) { /* 落到下一层 */ } } const v = lsGetRaw(base64Ids(id)) if (v != null) return typeof v === 'string' ? v : JSON.stringify(v) return mem.has(id) ? mem.get(id) : null } async function writeRaw (id, text, backend) { known.add(id) const b = backend || fileBackend() if (b) { try { await b.write(id, text); return true } catch (e) { if (backend) throw e /* 显式注入的后端:失败要暴露;桌面 FS 失败则退回门面 */ } } if (lsSetRaw(base64Ids(id), text)) return true mem.set(id, text) return true } async function removeRaw (id, backend) { const b = backend || fileBackend() if (b) { try { await b.remove(id) } catch (e) { /* ignore */ } } lsDelRaw(base64Ids(id)) mem.delete(id) return true } // 同一插件的写/读串行化:patch 的「读-改-写」不会被并发写覆盖 function enqueue (id, task) { const prev = queues.get(id) || Promise.resolve() const next = prev.then(task, task) queues.set(id, next.then(function () {}, function () {})) return next } function create (id, options) { const opt = options || {} const backend = opt.backend || null // 测试注入 const maxBytes = Math.min(HARD_MAX, Math.max(1024, Number(opt.maxBytes) || DEFAULT_MAX)) const schemaVersion = Number(opt.schemaVersion) || 1 async function load () { const raw = await readRaw(id, backend) if (!raw) { // 懒迁移:首次读取时把暂存的旧数据落盘 const legacy = lsGetRaw(LEGACY_KEY) if (legacy && typeof legacy === 'object' && legacy[id] && typeof legacy[id] === 'object') { const obj = legacy[id] await writeRaw(id, JSON.stringify(obj), backend) try { const left = Object.assign({}, legacy) delete left[id] lsSetRaw(LEGACY_KEY, left) } catch (e) { /* ignore */ } return { obj: obj, raw: JSON.stringify(obj) } } return { obj: {}, raw: '' } } try { return { obj: JSON.parse(raw), raw: raw } } catch (e) { return { obj: {}, raw: raw } } } return { id: id, schemaVersion: schemaVersion, read: function () { return enqueue(id, function () { return load().then(function (r) { return r.obj }) }) }, write: function (obj) { return enqueue(id, function () { const text = JSON.stringify(obj == null ? {} : obj) const n = bytesOf(text) if (n > maxBytes) { const err = new Error('插件数据超出上限(' + Math.round(n / 1024) + 'KB > ' + Math.round(maxBytes / 1024) + 'KB)') err.code = 'plugin-data-too-large' throw err } return writeRaw(id, text, backend).then(function () { return true }) }) }, patch: function (fnOrObj) { return enqueue(id, function () { return load().then(function (r) { const next = (typeof fnOrObj === 'function') ? fnOrObj(r.obj) : Object.assign({}, r.obj, fnOrObj) const text = JSON.stringify(next == null ? {} : next) const n = bytesOf(text) if (n > maxBytes) { const err = new Error('插件数据超出上限(' + Math.round(n / 1024) + 'KB > ' + Math.round(maxBytes / 1024) + 'KB)') err.code = 'plugin-data-too-large' throw err } return writeRaw(id, text, backend).then(function () { return next }) }) }) }, remove: function () { return enqueue(id, function () { return removeRaw(id, backend) }) }, size: function () { return enqueue(id, function () { return readRaw(id, backend).then(function (t) { return t ? bytesOf(t) : 0 }) }) }, } } // 启动期:把 iwb_plugins[id].data 搬到暂存(同步,不等 IO)。返回搬走的条目数。 function stripLegacy () { let state = null try { state = lsGetRaw('iwb_plugins') } catch (e) { state = null } if (!state || typeof state !== 'object') return 0 let legacy = null try { legacy = lsGetRaw(LEGACY_KEY) } catch (e) { legacy = null } if (!legacy || typeof legacy !== 'object') legacy = {} let moved = 0 for (const id of Object.keys(state)) { const rec = state[id] if (!rec || typeof rec !== 'object' || !rec.data || typeof rec.data !== 'object') continue if (Object.keys(rec.data).length) { legacy[id] = rec.data; moved++ } delete rec.data rec.migratedAt = Date.now() } if (moved) { try { lsSetRaw(LEGACY_KEY, legacy) } catch (e) { /* ignore */ } } try { lsSetRaw('iwb_plugins', state) } catch (e) { /* ignore */ } return moved } // 备份用:列出所有插件数据({id, data}) async function collectAll () { const b = fileBackend() const ids = new Set() if (b && typeof b.list === 'function') { try { for (const it of await b.list()) ids.add(String(it && it.id)) } catch (e) { /* ignore */ } } for (const id of mem.keys()) ids.add(id) for (const id of known) ids.add(id) try { const st = stateStore() if (st && typeof st.keys === 'function') { for (const k of st.keys()) if (String(k).indexOf('iwb_plugin_data_') === 0) ids.add(String(k).slice('iwb_plugin_data_'.length)) } } catch (e) { /* ignore */ } const legacy = lsGetRaw(LEGACY_KEY) if (legacy && typeof legacy === 'object') for (const id of Object.keys(legacy)) ids.add(id) const out = [] for (const id of ids) { if (!id) continue const raw = await readRaw(id, null) if (raw == null) continue try { out.push({ id: id, data: JSON.parse(raw) }) } catch (e) { /* 坏文件跳过 */ } } return out } async function restoreAll (list) { if (!Array.isArray(list)) return 0 let n = 0 for (const it of list) { if (!it || !it.id) continue try { await writeRaw(String(it.id), JSON.stringify(it.data == null ? {} : it.data), null) n++ } catch (e) { /* 单个失败不影响其它 */ } } return n } async function totalSize () { const all = await collectAll() let n = 0 for (const it of all) n += bytesOf(JSON.stringify(it.data)) return { bytes: n, count: all.length } } // ---- 插件文件(plugin-data//files/,v3.26.59)---- // 为什么放在这层:备份/还原只认 IWBPluginData 一个入口。此前只备份 JSON, // 于是「提示词封面」这类图片文件换机后全丢(标题栏说"已恢复",打开却是灰块)。 // 内存纪律:清单(id/name/size)一次性给出;字节**逐条读**(调用方写完即放手), // 不做"全部读进数组再写包"——插件文件单插件上限 64MB,攒起来会 OOM。 function pluginFilesFacade () { const F = global.IWBStorageFile const pf = F && F.pluginFiles return (pf && typeof pf.listAll === 'function') ? pf : null } async function listFiles () { const pf = pluginFilesFacade() if (!pf) return [] let groups = [] try { groups = await pf.listAll() } catch (e) { groups = [] } const out = [] for (const g of (Array.isArray(groups) ? groups : [])) { if (!g || !g.id) continue for (const f of (g.files || [])) { if (!f || !f.name) continue out.push({ id: String(g.id), name: String(f.name), size: Number(f.size) || 0 }) } } return out } async function readFile (id, name) { const pf = pluginFilesFacade() if (!pf || typeof pf.readBytes !== 'function') return null try { return await pf.readBytes(String(id), String(name)) } catch (e) { return null } } // list = [{ id, name, data: dataURL }],单条失败不影响其它 async function restoreFiles (list) { const F = global.IWBStorageFile const pf = F && F.pluginFiles if (!pf || typeof pf.put !== 'function') return 0 let n = 0 for (const it of (Array.isArray(list) ? list : [])) { if (!it || !it.id || !it.name || !it.data) continue try { const r = await pf.put(String(it.id), String(it.name), String(it.data)) if (r && r.ok) n++ } catch (e) { /* 单个失败不影响其它 */ } } return n } global.IWBPluginData = { create: create, stripLegacy: stripLegacy, collectAll: collectAll, restoreAll: restoreAll, totalSize: totalSize, listFiles: listFiles, readFile: readFile, restoreFiles: restoreFiles, _bytesOf: bytesOf, } })(typeof window !== 'undefined' ? window : globalThis)