feat(plugin): 插件数据层 M2 —— ctx.data(原子写 + 串行队列 + 旧数据迁移)v3.25.42

- 新增 src/plugin-data.js:read/write/patch/remove/size;桌面落 plugin-data/<id>.json(tmp+rename),
  同一插件读写串行排队,maxBytes 上限(默认 2MiB/最高 16MiB)超限抛错且不破坏已有数据
- storage-file 增加 pluginData 命名空间(read/write/remove/list)
- stripLegacy:宿主 init 前同步暂存 iwb_plugins[id].data,插件首次 read 时落盘并清暂存
- 备份携带 items.pluginData 并支持恢复;存储体检显示「插件数据 N 个 / X KB」
- 非桌面环境走 IWBStorageLocal 门面 → 内存兜底(仅测试)
- 新增 tests/plugin-data-test.js(串行/上限/迁移/备份)
This commit is contained in:
qiqi committed 2026-11-20 09:27:53 +08:00
1 parent 07d1715993
commit 7b1164febb
18 files changed
+424 -15

No files matched your search

+11
View File
@@ -14,6 +14,17 @@
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
## v3.25.42(2026-11-20)插件数据层 M2:ctx.data(原子写 + 串行队列 + 旧数据迁移)
- 新增 `src/plugin-data.js`,插件拿到异步数据 API:`ctx.data.read/write/patch/remove/size`。
- 桌面落 `<资料目录>/plugin-data/<id>.json`(写 `.tmp` 再 rename,避免半截 JSON);与插件代码目录分离,卸载默认保留数据。
- 同一插件的读写**串行排队**,`patch` 的「读-改-写」不会被并发覆盖。
- 单文件上限 `maxBytes`(默认 2MiB,最高 16MiB),超限抛 `plugin-data-too-large` 且**不破坏已有数据**。
- 旧数据迁移:`stripLegacy()` 在宿主 init 前同步把 `iwb_plugins[id].data` 暂存,插件首次 `read()` 时才落盘并清暂存(启动不等 IO)。
- 备份包含插件数据(`items.pluginData`),恢复时写回;存储体检新增「插件数据 N 个 / X KB」。
- 非桌面环境(jsdom / playwright)走 `IWBStorageLocal` 门面 → 内存兜底,仅供测试。
- 新增 `tests/plugin-data-test.js`(串行队列 / 上限 / 迁移 / 备份 4 组断言)。
## v3.25.41(2026-11-20)插件目录化 M1:目录插件加载 + 兼容旧单文件
- 插件支持**目录形态**:`<plugins>/<id>/{manifest.json,main.js[,styles.css]}`;内置 `image-annotate` 转为目录做试点,其余 7 个仍是单文件(双轨兼容)。
+1 -1
View File
@@ -41,7 +41,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序
node --check app.js 与 dist/app.js 语法
check-dist.js 产物体检
lint ESLint(src/ + app.js,正确性规则)
test:unit 101 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test:unit 102 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test relay-task-graph-fixture + iwb-v32-web-test
test:facts 事实基线守门(见 §5)
typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js)
+3 -1
View File
@@ -2691,7 +2691,9 @@
let idbKeys = []
try { idbKeys = await IDB.keys() } catch (e) { idbKeys = [] }
const outputs = lsGet(OUT_KEY, [])
return StorageHealth.audit({ idbKeys, outputsIndex: Array.isArray(outputs) ? outputs : [], prefixes: { blob: IMG_BLOB_PREFIX, ref: IDB_REF_PREFIX, out: IDB_OUT_PREFIX, orig: IDB_ORIG_PREFIX } })
const res = StorageHealth.audit({ idbKeys, outputsIndex: Array.isArray(outputs) ? outputs : [], prefixes: { blob: IMG_BLOB_PREFIX, ref: IDB_REF_PREFIX, out: IDB_OUT_PREFIX, orig: IDB_ORIG_PREFIX } })
try { const PD = window.IWBPluginData; if (PD && PD.totalSize) { const t = await PD.totalSize(); res.pluginDataBytes = t.bytes; res.pluginDataCount = t.count } } catch (e) { /* M2:插件数据纳入体检 */ }
return res
}
// 一键安全回收:复用保存路径的 wCleanIdb(带活引用 keep-set),绕过 30s 节流手动触发一次。
// 哨兵:读不到画布数据就中止 —— 否则 keep-set 为空会把所有图片字节当孤儿删掉。
+4 -4
View File
@@ -22,7 +22,7 @@
- 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob_<hash>_<len>`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。
- 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。
- 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。
- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **91** 个模块 / 14,607 行,`sourceModules` 91 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **92** 个模块 / 14,607 行,`sourceModules` 92 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
- 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。
## 2. 门禁与环境现状
@@ -167,7 +167,7 @@
- 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。
- **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。
- **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A)
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**91 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**92 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。)
- **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。
- **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。
@@ -183,7 +183,7 @@
| `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 |
| `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 |
| `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) |
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**76** 项)与 `sourceModules` 顺序(**91** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**77** 项)与 `sourceModules` 顺序(**92** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
## 12. 易踩的坑
@@ -254,7 +254,7 @@
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**76** 项)与 `sourceModules` 顺序(**91** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**77** 项)与 `sourceModules` 顺序(**92** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
**关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "image-workbench-web",
"private": true,
"version": "3.25.41",
"version": "3.25.42",
"description": "Browser-based node canvas image workbench",
"scripts": {
"build": "node scripts/build.js && node scripts/copy-plugins.js",
@@ -10,7 +10,7 @@
"app:build": "tauri build",
"lint": "eslint src app.js",
"test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js",
"test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
"test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
"test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js",
"test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js",
"plugins:gc": "node scripts/plugins-publish.mjs --gc",
+1
View File
@@ -77,6 +77,7 @@ const sourceModules = [
'gallery-query.js',
'gallery-hydration.js',
'ui-components.js',
'plugin-data.js',
'plugin-host.js',
'image-compress.js',
'storage-fallback-indexeddb.js',
+1 -1
View File
@@ -1983,7 +1983,7 @@ dependencies = [
[[package]]
name = "image-workbench"
version = "3.25.41"
version = "3.25.42"
dependencies = [
"arboard",
"base64 0.22.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "image-workbench"
version = "3.25.41"
version = "3.25.42"
description = "无限画布 · 生图工作台桌面版"
authors = ["malongan"]
license = ""
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "image-workbench",
"version": "3.25.41",
"version": "3.25.42",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
+241
View File
@@ -0,0 +1,241 @@
/* plugin-data.js —— 插件数据层(v3.25.42 / M2)
*
* 目标:给插件一块**属于自己的、容量够用的**结构化存储。
* · 桌面:<资料目录>/plugin-data/<id>.json(原子写:tmp + rename)
* · 非桌面(jsdom / playwright 测试):localStorage,再兜底为内存
* · 同一插件的写入串行排队,避免「读-改-写」互相覆盖
* · 单文件上限 maxBytes(默认 2MiB,最多 16MiB),超限抛错、不静默截断
*
* 旧数据迁移:
* 老版本把所有插件数据塞在 localStorage['iwb_plugins'][id].data 里。
* stripLegacy() 在启动时把它们搬到 iwb_plugin_data_legacy 暂存(同步、不动磁盘),
* read() 首次命中时再落到 plugin-data/<id>.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 }
}
global.IWBPluginData = {
create: create,
stripLegacy: stripLegacy,
collectAll: collectAll,
restoreAll: restoreAll,
totalSize: totalSize,
_bytesOf: bytesOf,
}
})(typeof window !== 'undefined' ? window : globalThis)
+7
View File
@@ -166,6 +166,11 @@
storage,
events
}
// v3.25.42:插件数据层(异步、独立文件)。插件用 ctx.data 存结构化数据,容量远大于 ctx.storage。
const dataFactory = (deps && typeof deps.data === 'function') ? deps.data : ((global.IWBPluginData && typeof global.IWBPluginData.create === 'function') ? function (pid, meta) { return global.IWBPluginData.create(pid, meta) } : null)
if (dataFactory) {
try { const d = dataFactory(id, manifest.data || {}); if (d) ctx.data = d } catch (error) { noteError(id, error) }
}
const granted = deps && deps.capabilities && typeof deps.capabilities === 'object' ? deps.capabilities : {}
for (const name of manifest.capabilities) {
const apiKey = CAPABILITY_API_KEYS[name]
@@ -245,6 +250,8 @@
function init(nextDeps) {
deps = nextDeps && typeof nextDeps === 'object' ? nextDeps : {}
// v3.25.42:读宿主状态**之前**把旧的插件数据(iwb_plugins[id].data)暂存出去,避免双份真源
try { if (global.IWBPluginData && typeof global.IWBPluginData.stripLegacy === 'function') global.IWBPluginData.stripLegacy() } catch (error) { /* ignore */ }
state = readState()
const activated = []
for (const id of Array.from(plugins.keys())) {
+38
View File
@@ -522,6 +522,43 @@
return true
}
// ---- 插件数据(v3.25.42 / M2):<资料目录>/plugin-data/<id>.json ----
// 与插件**代码目录**分离:卸载插件默认保留数据;写入用 tmp + rename,避免半截 JSON。
const PDATA_DIR = 'plugin-data'
async function pluginDataDir() {
const p = await join(dir, PDATA_DIR)
try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ }
return p
}
function safePluginId(id) {
const s0 = String(id || '')
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(s0)) throw new Error('非法插件 id')
return s0
}
async function pluginDataRead(id) {
try { return await fs().readTextFile(await join(await pluginDataDir(), safePluginId(id) + '.json')) } catch (e) { return null }
}
async function pluginDataWrite(id, text) {
const dir0 = await pluginDataDir()
const target = await join(dir0, safePluginId(id) + '.json')
const tmp = await join(dir0, safePluginId(id) + '.json.tmp')
await fs().writeTextFile(tmp, String(text))
try { await fs().rename(tmp, target) } catch (e) {
try { await fs().remove(target) } catch (e2) { /* 不存在 */ }
await fs().rename(tmp, target)
}
return true
}
async function pluginDataRemove(id) {
try { await fs().remove(await join(await pluginDataDir(), safePluginId(id) + '.json')); return true } catch (e) { return false }
}
async function pluginDataList() {
try {
const entries = await fs().readDir(await pluginDataDir())
return entries.filter((e) => e && !e.isDirectory && /\.json$/.test(e.name)).map((e) => ({ id: e.name.replace(/\.json$/, '') }))
} catch (e) { return [] }
}
async function loadInto() {
// data.json 不存在 ⇒ 把当前 WebView 里的数据迁过去(只做一次)
const target = await join(dir, DATA_FILE)
@@ -958,6 +995,7 @@
global.IWBStorageFile = {
enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages, rotateTrash, galleryThumb, readDisplayThumb, writeDisplayThumb,
plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal, listDirs: pluginListDirs, readFile: pluginReadFile, writeFile: pluginWriteFile, writeBinary: pluginWriteBinary, mkdir: pluginMkdir, removeDir: pluginRemoveDir },
pluginData: { read: pluginDataRead, write: pluginDataWrite, remove: pluginDataRemove, list: pluginDataList },
storage: () => storage,
kv: () => kv,
dir: () => dir,
+5
View File
@@ -171,6 +171,8 @@ function BackupModal(props) {
await Promise.all(jobs)
// 插件(清单 + 源码)随备份走:换机器恢复后不用重装
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.collect) { const ps = await pb.collect(); if (ps && ps.length) items.plugins = ps } } catch (e) { /* 插件快照失败不影响主备份 */ }
// v3.25.42:插件数据(plugin-data/<id>.json)一并备份,换机后插件配置不丢
try { const pd = (typeof window !== 'undefined') ? window.IWBPluginData : null; if (pd && pd.collectAll) { const pl = await pd.collectAll(); if (pl && pl.length) items.pluginData = pl } } catch (e) { /* 插件数据快照失败不影响主备份 */ }
// 收集图片(画布引用大图 + 勾选的图库缩略图/原图)并读取数据
const refMeta = await collectBackupImages()
const galleryMeta = (bk.outputs && items.outputs) ? (await collectBackupOutputImages(items.outputs)) : []
@@ -369,6 +371,9 @@ function BackupModal(props) {
if (items.plugins && items.plugins.length) {
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.restore) await pb.restore(items.plugins) } catch (e) { /* 插件还原失败不阻塞其它项 */ }
}
if (items.pluginData && items.pluginData.length) {
try { const pd = (typeof window !== 'undefined') ? window.IWBPluginData : null; if (pd && pd.restoreAll) await pd.restoreAll(items.pluginData) } catch (e) { /* 插件数据还原失败不阻塞其它项 */ }
}
if (restoreSel.outputs && items.outputs) {
if (restoreMerge) {
const cur = await api('outputs').catch(() => ({ files: [] }))
+10 -4
View File
@@ -116,10 +116,16 @@
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!storageAuditBusy, onClick: runStorageAudit }, storageAuditBusy ? '处理中…' : '存储体检'),
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!storageAuditBusy, onClick: reclaimOrphans }, '安全回收孤儿'),
),
storageAudit ? el('div', { className: 'iwb-diag-list' }, el('div', { className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, 'IDB 图片键 ' + storageAudit.total + '(blob ' + storageAudit.counts.blob + ' / ref ' + storageAudit.counts.ref + ' / out ' + storageAudit.counts.out + ' / orig ' + storageAudit.counts.orig + ' / 其它 ' + storageAudit.counts.other + ')'),
el('div', { className: 'iwb-diag-extra' }, '图库索引 ' + storageAudit.outputsIndexSize + ' 条 · 悬空索引 ' + storageAudit.danglingOutputIndex + ' · 孤儿输出字节 ' + storageAudit.orphanOutputBytes),
)) : el('div', { className: 'iwb-hint' }, '点「存储体检」查看一致性;发现悬空 / 孤儿再决定是否回收。'),
storageAudit ? el('div', { className: 'iwb-diag-list' },
el('div', { className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, 'IDB 图片键 ' + storageAudit.total + '(blob ' + storageAudit.counts.blob + ' / ref ' + storageAudit.counts.ref + ' / out ' + storageAudit.counts.out + ' / orig ' + storageAudit.counts.orig + ' / 其它 ' + storageAudit.counts.other + ')'),
el('div', { className: 'iwb-diag-extra' }, '图库索引 ' + storageAudit.outputsIndexSize + ' 条 · 悬空索引 ' + storageAudit.danglingOutputIndex + ' · 孤儿输出字节 ' + storageAudit.orphanOutputBytes),
),
storageAudit.pluginDataCount !== undefined ? el('div', { className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, '插件数据 ' + storageAudit.pluginDataCount + ' 个 · ' + Math.round((storageAudit.pluginDataBytes || 0) / 1024) + ' KB'),
el('div', { className: 'iwb-diag-extra' }, '存放于资料目录 plugin-data/(与插件代码分离,卸载插件默认保留)'),
) : null,
) : el('div', { className: 'iwb-hint' }, '点「存储体检」查看一致性;发现悬空 / 孤儿再决定是否回收。'),
el('div', { className: 'iwb-section-sub' }, '画板找回(索引里没有、但本体还在 · ' + orphanRows.length + ' 个)'),
orphanRows.length ? el('div', { className: 'iwb-diag-list' }, orphanRows.map((row, i) => el('div', { key: 'or' + i, className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, row.name + ' · ' + row.nodes + ' 个节点 · ' + row.id),
+1
View File
@@ -23,6 +23,7 @@
"IWBMetricsSwallow",
"IWBNativeClipboard",
"IWBNodeBodies",
"IWBPluginData",
"IWBPluginHost",
"IWBProviderPing",
"IWBResultImg",
+1
View File
@@ -49,6 +49,7 @@
"gallery-query.js",
"gallery-hydration.js",
"ui-components.js",
"plugin-data.js",
"plugin-host.js",
"image-compress.js",
"storage-fallback-indexeddb.js",
+95
View File
@@ -0,0 +1,95 @@
'use strict'
// 插件数据层行为测试(src/plugin-data.js,v3.25.42 / M2)
//
// 为什么要有:ctx.data 是"插件唯一能放心存业务数据"的地方,
// 一旦串行队列写错(并发 patch 互相覆盖)或上限判定失效(静默截断),用户数据会悄悄丢。
// 这里用注入 backend(内存 Map)跑纯逻辑,不依赖 Tauri / 浏览器。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const lsMap = new Map()
// 存储走 IWBStorageLocal 门面(src 内禁止直调 localStorage)
const store = {
rawGet: (k, fb) => (lsMap.has(k) ? lsMap.get(k) : fb),
rawSet: (k, v) => { lsMap.set(k, String(v)); return true },
remove: (k) => { lsMap.delete(k); return true },
keys: () => Array.from(lsMap.keys()),
}
const sandbox = { TextEncoder, IWBStorageLocal: { getStore: () => store } }
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'plugin-data.js'), 'utf8'), sandbox)
const PD = sandbox.IWBPluginData
assert.ok(PD, 'IWBPluginData 未导出')
// vm 里造出来的对象原型不同,deepStrictEqual 会误报 ⇒ 统一用 JSON 比较
const eq = (actual, expected, msg) => assert.strictEqual(JSON.stringify(actual), JSON.stringify(expected), msg)
function memBackend () {
const store = new Map()
return {
store,
read: async (id) => (store.has(id) ? store.get(id) : null),
write: async (id, text) => { store.set(id, text); return true },
remove: async (id) => { store.delete(id); return true },
list: async () => Array.from(store.keys()).map((id) => ({ id })),
}
}
;(async () => {
const be = memBackend()
const d = PD.create('test-a', { backend: be, maxBytes: 2048, schemaVersion: 3 }) // 下限 1KB,这里取 2KB 方便测上限
eq(await d.read(), {}, '空数据应返回 {}')
assert.strictEqual(d.schemaVersion, 3)
await d.write({ x: 1 })
eq(await d.read(), { x: 1 })
await d.patch({ y: 2 })
eq(await d.read(), { x: 1, y: 2 })
await d.patch((o) => Object.assign({}, o, { x: 9 }))
eq(await d.read(), { x: 9, y: 2 })
// 并发 20 次 patch:串行队列必须一个都不丢
await Promise.all(Array.from({ length: 20 }, (_, i) => d.patch((o) => Object.assign({}, o, { ['k' + i]: i }))))
const all = await d.read()
for (let i = 0; i < 20; i++) assert.strictEqual(all['k' + i], i, '并发 patch 丢了 k' + i)
assert.strictEqual(all.x, 9)
// 超上限:抛错、且不破坏上一次成功写入
let err = null
try { await d.write({ big: 'x'.repeat(4000) }) } catch (e) { err = e }
assert.ok(err && err.code === 'plugin-data-too-large', '超上限应抛 plugin-data-too-large')
eq(await d.read(), all, '写失败不得改动已有数据')
assert.ok((await d.size()) > 0, 'size 应大于 0')
await d.remove()
eq(await d.read(), {}, 'remove 后应回到空')
// stripLegacy:旧 iwb_plugins[id].data 搬到暂存,首次 read 再落盘
lsMap.set('iwb_plugins', JSON.stringify({ legacy1: { enabled: true, data: { a: 1, b: 'x' } }, plain: { enabled: false } }))
const moved = PD.stripLegacy()
assert.strictEqual(moved, 1, '应搬走 1 个插件的旧数据')
const stateAfter = JSON.parse(lsMap.get('iwb_plugins'))
assert.strictEqual(stateAfter.legacy1.data, undefined, '旧 data 必须从宿主状态移除(避免双份)')
assert.ok(stateAfter.legacy1.migratedAt > 0, '应记录 migratedAt')
assert.strictEqual(stateAfter.plain.enabled, false, '其它字段不得被改动')
const legacyBackend = memBackend()
const dLegacy = PD.create('legacy1', { backend: legacyBackend })
eq(await dLegacy.read(), { a: 1, b: 'x' }, '首次读取应拿到迁移过来的旧数据')
assert.ok(legacyBackend.store.has('legacy1'), '迁移应落到新后端')
const legacyLeft = JSON.parse(lsMap.get('iwb_plugin_data_legacy') || '{}')
assert.strictEqual(legacyLeft.legacy1, undefined, '迁移完成后应清掉暂存')
// 备份:collectAll / restoreAll(无注入 backend ⇒ 走内存兜底)
const dMem = PD.create('backup-a')
await dMem.write({ keep: [1, 2, 3] })
const collected = await PD.collectAll()
const hit = collected.find((x) => x.id === 'backup-a')
assert.ok(hit && Array.isArray(hit.data.keep), 'collectAll 应包含插件数据')
await PD.restoreAll([{ id: 'restored-x', data: { ok: true } }])
eq(await PD.create('restored-x').read(), { ok: true }, 'restoreAll 应写回数据')
console.log('plugin-data checks passed(串行队列 / 上限 / 迁移 / 备份)')
})().catch((e) => { console.error(e); process.exit(1) })
+1
View File
@@ -32,6 +32,7 @@ interface Window {
IWBRuntimePluginLoader?: any
IWBRuntimePluginMarket?: any
IWBRuntimePluginBackup?: any
IWBPluginData?: any
IWBPluginRuntime?: any
IWBDesktop?: any
IWBStorageFallbackIndexedDb?: any