feat(plugin): 插件目录化 M1 —— 目录插件加载 + 旧单文件兼容 v3.25.41

- loader 新增 loadFolder():manifest → main.js(逐文件 sha256,内置信随包 index.json)→ blob 注入;
  样式文本暂存,激活时注入、停用时移除(配合 host 新增 onActivate/onDeactivate 钩子)
- storage-file 增加 plugins.listDirs/readFile/writeFile/writeBinary/mkdir/removeDir(按段校验,禁 ..)
- app.js:三路合并支持目录条目(dir/main/style/files),失败隔离 + 按 id 排序
- 修复:无 iwb_plugins 记录时插件永不激活(首次安装面板显示「未加载」)
- 备份模块兼容目录形态;市场暂时跳过目录插件(M3 zip 后恢复)
- 试点:image-annotate 转为 plugins/image-annotate/{manifest.json,main.js}
- 方案文档 docs/PLUGIN-ARCHITECTURE-PLAN.md 一并入库
This commit is contained in:
qiqi committed 2026-11-20 09:08:56 +08:00
1 parent 8dbc0c0603
commit 7ed3ba6738
17 files changed
+673 -22

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.41(2026-11-20)插件目录化 M1:目录插件加载 + 兼容旧单文件
- 插件支持**目录形态**:`<plugins>/<id>/{manifest.json,main.js[,styles.css]}`;内置 `image-annotate` 转为目录做试点,其余 7 个仍是单文件(双轨兼容)。
- 加载器新增 `loadFolder()`:读 manifest → 逐文件 **sha256 校验**(内置以随包 index.json 为准)→ blob 注入 → 样式文本暂存,**激活时才注入**、停用时移除。
- 目录插件失败隔离:单个插件 manifest 损坏/hash 不符只记 `error`,不中断其余插件加载;加载顺序按 id 稳定排序。
- 新增磁盘能力:`plugins.listDirs/readFile/writeFile/writeBinary/mkdir/removeDir`(路径按段校验,禁 `..`)。
- 修复历史 bug:**首次安装(`iwb_plugins` 无记录)时所有插件都不会激活**,表现为面板显示「xxx 未加载」;现在无记录即默认启用。
- 插件备份(`runtime-plugin-backup`)兼容目录形态(收集 main+style,恢复写回目录)。
- 市场索引暂时跳过目录插件(zip 打包在 M3 落地后恢复)。
- 同步脚本 `sync-plugins-from-repo.js` / `copy-plugins.js` 支持产出与打包目录插件。
## v3.25.40(2026-11-20)图库设定行去掉文字标签,只留三个窄下拉
- 去掉「插入 / 显示 / 时间」三个文字标签(按用户选择),三个下拉直接并排:`0.5K | 特大 | 全部`。
+17 -4
View File
@@ -8678,6 +8678,8 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
}
} catch (e) { /* 开发者模式读取失败不影响启动 */ }
for (const e of ext) { const id = String((e && e.id) || ''); if (id) byId.set(id, Object.assign({}, e, { source: 'external' })) }
// 目录插件(v3.25.41):扫描 <资料目录>/plugins/*/manifest.json;与单文件同 id 时目录优先
try { const L0 = wPluginLoader(); if (L0 && L0.listFolderEntries) for (const e of await L0.listFolderEntries()) if (!byId.has(e.id)) byId.set(e.id, e) } catch (e2) { /* 目录扫描失败不影响内置加载 */ }
// 关键:加载前先快照「用户关掉过哪些插件」,加载过程绝不能覆盖这个状态
let persistedState = {}
try {
@@ -8696,9 +8698,18 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
const file = String((entry && entry.file) || '')
const isExt = (entry && entry.source) === 'external'
const isLocalEntry = (entry && entry.source) === 'local'
const record = { id, file, version: (entry && entry.version) || '', status: 'loading', error: null, code: (entry && entry.code) || '', source: isExt ? 'external' : ((entry && entry.source === 'local') ? 'local' : 'builtin') }
const dir = String((entry && entry.dir) || '')
const mainName = String((entry && entry.main) || 'main.js')
const record = { id, dir, main: mainName, style: String((entry && entry.style) || ''), hashes: (entry && entry.files) || null, file: dir ? dir + '/' + mainName : file, version: (entry && entry.version) || '', status: 'loading', error: null, code: (entry && entry.code) || '', source: isExt ? 'external' : ((entry && entry.source === 'local') ? 'local' : 'builtin') }
wRuntimePlugins.push(record)
if (!id || !/^[A-Za-z0-9._-]+$/.test(file)) { record.status = 'bad-entry'; continue }
if (!id) { record.status = 'bad-entry'; continue }
if (dir) {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(dir) || !/^[A-Za-z0-9._-]+\.js$/.test(mainName)) { record.status = 'bad-entry'; record.error = '目录或入口名不合法'; continue }
if (!record.hashes || !record.hashes[mainName]) { record.status = 'bad-entry'; record.error = '缺少文件哈希(拒绝加载)'; continue }
const LF = wPluginLoader(); if (PluginHost && LF && LF.loadFolder) pending.push(LF.loadFolder(record)); else record.status = 'idle'
continue
}
if (!/^[A-Za-z0-9._-]+$/.test(file)) { record.status = 'bad-entry'; continue }
const integrity = String((entry && entry.integrity) || '')
// fail-closed:无 integrity 声明即拒绝加载(清单由 KV 发布脚本生成、必带 integrity;缺失视为不可信)
if (!integrity && !isLocalEntry) { record.status = 'bad-entry'; record.error = 'integrity 缺失(拒绝加载)'; continue }
@@ -8719,8 +8730,8 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
for (const r of (wRuntimePlugins || [])) {
if (!r || r.status !== 'loaded') continue
const rec = st[r.id]
if (!rec) continue
const want = rec.enabled !== false
// 没有持久化记录 ⇒ 默认启用(修复:首次安装/清空存储后插件永远不激活,面板显示"未加载")
const want = !rec || rec.enabled !== false
if (!PluginHost || typeof PluginHost.setEnabled !== 'function') continue
// 注意:插件是在 init() 之后才注册的,init 的"激活已启用项"覆盖不到它们。
// 所以这里对 want=true 一律再 setEnabled(true)(activate 幂等:已激活会返回 already),
@@ -8736,6 +8747,8 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
if (PluginHost && typeof PluginHost.init === 'function') {
try {
PluginHost.init({
onActivate: (id) => { const L = wPluginLoader(); if (L && L.applyStyleFor) L.applyStyleFor(id) },
onDeactivate: (id) => { const L = wPluginLoader(); if (L && L.removeStyle) L.removeStyle(id) },
readState: () => { const v = lsGet('iwb_plugins', {}); return v && typeof v === 'object' ? v : {} },
writeState: (state) => { lsSet('iwb_plugins', state) },
log: () => { try { wLog.apply(null, arguments) } catch (e) { /* ignore */ } },
+354
View File
@@ -0,0 +1,354 @@
# 插件目录化 + 三个库插件化 · 完整方案
> v2(2026-11-20)· 已并入「桌面端定位」「展示页例外」「不做分类」三项裁定
> 范围:插件从「单文件」改为「文件夹」;随后把 **图库 / 提示词库 / 节点组库** 改为插件
> 非目标:分类插件(画布分类维持现状);插件安全沙箱;画布内核重构
---
## 0. 决策摘要(本方案按这 10 条执行)
| # | 决策 | 状态 |
|---|---|---|
| 1 | 应用本体 = 独立桌面端(Tauri);产品代码不加浏览器降级分支 | 已定 |
| 2 | **例外**:插件展示页 / 市场页 / 下载页仍是静态网页,继续维护 | 已定 |
| 3 | 插件格式 = 目录(`manifest.json + main.js + styles.css + data.json + assets/`) | 本方案 |
| 4 | 插件数据落 `<资料目录>/plugin-data/<id>.json`(与代码目录分离,卸载默认保留) | 建议默认 |
| 5 | 市场安装 = zip 整包 + 逐文件 sha256;安装仅桌面 | 建议默认 |
| 6 | 旧单文件插件保留一个版本周期的双轨兼容 | 本方案 |
| 7 | **不做**分类插件(`iwb_home_cats` + `workspace.category` 维持现状) | 已定 |
| 8 | 插件不得直接改画布:插入/实例化一律走宿主 capability | 本方案 |
| 9 | 市场包用 **ZIP STORE(不压缩)**,绕开旧 WebView 无 `DecompressionStream` 的兼容坑 | 复查新增 |
| 10 | 图库/提示词/节点组插件化后,**保留宿主面板一个版本周期**可一键退回(`iwb_panels_mode`) | 复查新增 |
---
## 1. 现状(代码核对过的事实)
| 环节 | 现状 | 位置 |
|---|---|---|
| 插件产物 | 单个 IIFE `<id>.<hash>.js`,内容寻址 | `plugins/runtime/` |
| 清单 | `index.json`:`{id,file,version,integrity}`;展示信息在 `meta.json` | `plugins/index.json` |
| 注册契约 | 插件自注册 `IWBPluginHost.register(manifest, factory)` | 各插件末尾 |
| 内置加载 | `<script src="/plugins/x.js" integrity=…>`(SRI) | `runtime-plugin-loader.js:54` |
| 外部加载 | 读文本 → sha256 → blob 注入 | `:71` |
| 开发模式 | **已是目录**:`<资料目录>/plugins/local/<id>/plugin.js` | `storage-file.js:441` |
| 市场安装 | 下载单文件 → sha256 → 写盘 → 重启 | `runtime-plugin-market.js:65` |
| 插件数据 | `ctx.storage.namespace(ns)` → 全量落 `localStorage['iwb_plugins']`(≈5MB) | `plugin-host.js:100` |
| 能力面 | panels/commands/nodeTypes/generationHooks/providers/canvas/canvasWrite/nodeActions | `plugin-host.js:8` |
| CSP | `script-src 'self' blob:`;`style-src 'self' 'unsafe-inline'` | `tauri.conf.json` |
| 图库规模 | 上限 500 张 | `runtime-constants.js:6` |
| 展示页 | `site/plugins/index.html` ← `gen-site.js` ← `market/index.json` | 静态站 |
三条判断:
1. **目录形态已有先例**(dev 模式),只是没推广到正式插件 → 改动可控。
2. **瓶颈是数据不是形态**:所有插件共用一个 localStorage 键,图库/提示词一大就爆。
3. **展示页与桌面端共享 `market/index.json`**:新字段只能加、不能改,原有 `name/desc/tags/version/icon/author` 必须保留。
---
## 2. 目标形态
### 2.1 目录结构
```
<插件根>/<id>/
manifest.json 唯一真源
main.js IIFE,自注册(沿用现有 register)
styles.css 可选,注入 <style data-plugin="<id>">
data.json 可选,插件数据(由宿主代理读写,见 2.3)
assets/ 可选,图标/图片(ctx.asset → data URL)
```
与 Obsidian 完全同构(`manifest.json/main.js/styles.css/data.json`),差异只有 `minAppVersion→apiVersion` 与可选 `assets/`。
### 2.2 manifest 字段
```jsonc
{
"id": "gallery", "name": "图库", "version": "1.0.0", "apiVersion": 1,
"main": "main.js", "style": "styles.css",
"description": "…", "author": "official", "icon": "🖼️", "tags": ["资源"],
"capabilities": ["panels", "gallery"],
"permissions": ["gallery.read", "gallery.delete", "canvas.insertRef"],
"settings": {},
"data": { "schemaVersion": 1, "maxBytes": 2097152 }
}
```
- `description/author/icon/tags` 接管原 `meta.json`,展示页从构建期汇总读取。
- 旧单文件插件的内嵌清单继续有效;同 id 时**目录优先**。
### 2.3 数据层(核心)
| 层 | 用途 | 落点 | API |
|---|---|---|---|
| settings | 少量配置 | `localStorage['iwb_plugins'][id].settings`(现状) | `ctx.settings`(同步,不变) |
| **data** | 业务数据 | `<资料目录>/plugin-data/<id>.json` | **`ctx.data`(异步,新增)** |
| assets | 图标/图片 | `<插件目录>/assets/` | `ctx.asset(name)` → data URL |
```js
ctx.data.read() // → object(不存在返回 {})
ctx.data.write(obj) // 全量覆盖;原子写:<id>.json.tmp → rename
ctx.data.patch(fn|obj) // 读-改-写,内部串行队列
ctx.data.remove() // 清空
ctx.data.size() // 字节数(设置页展示占用)
ctx.data.schemaVersion
```
约束:单文件上限 `maxBytes`(默认 2MiB,最高 16MiB),超限写失败并提示,不静默截断;同一插件的写串行化;**图片字节不进 data.json**(图库图仍在宿主 `images/`,data.json 只存元数据)。
三件必须同时做的事(复查补充):
- **备份/还原**:`plugin-data/` 纳入备份(新增 `items.pluginData`,体积小、默认勾选);同时改造 `runtime-plugin-backup.js`——它现在只备份单文件插件的 `code`,目录插件会丢。
- **存储审计**:`wStorageAudit` 增加「插件数据」占用,设置页可见、可清空。
- **双写禁令**:`ctx.storage`(同步、落 localStorage)从 M2 起只允许存 settings 级小值;业务数据一律 `ctx.data`。迁移后把 `iwb_plugins[id].data` 清空只留 `migratedAt`,避免两份真源。
> 唯一例外:jsdom / playwright 测试在非 Tauri 环境跑应用,`ctx.data` 保留内存兜底,标注"仅供测试",不得据此在产品代码加浏览器分支。
### 2.4 加载流程
```
内置: /plugins/index.json(构建生成的目录索引,含逐文件 sha256) + /plugins/<id>/manifest.json
外部: <资料目录>/plugins/index.json + <资料目录>/plugins/<id>/manifest.json
扫描: 桌面额外扫描 <资料目录>/plugins/*/manifest.json(手工放入、无索引也能识别)
开发: <资料目录>/plugins/local/<id>/plugin.js(免签名)
```
`loadFolder(record)`:读 manifest → 校验(apiVersion/capabilities/permissions)→ 读 main.js 并校验 hash → 注入 `__IWB_PLUGIN_MANIFEST__` → blob 注入 → 注入 styles.css → 等自注册。
> Tauri 资源协议**不能列目录** ⇒ 内置索引必须构建期生成;外部目录才可扫描。
复查补充的 4 条硬规则:
1. **信任模型**:内置插件只信**随包的** `plugins/index.json`(里面的逐文件 sha256 写死在包里);manifest 里的 hash 只用于"外部/市场安装"校验,不能拿它自证。
2. **确定性顺序**:两路合并后按 `id` 升序加载;不依赖文件系统返回顺序。
3. **失败隔离**:单个插件 manifest 损坏 / 脚本抛错 → 记 `record.error` 并跳过,**不得中断整轮加载**。
4. **注册去重**:`registerPanel/registerNodeType` 按 `pluginId + 自身 id` 去重,防止热启停导致面板重复。
### 2.5 安装(仅桌面)
市场条目:
```jsonc
{ "id":"gallery","version":"1.0.0","minApiVersion":1,
"bundle":"gallery-1.0.0.zip",
"files":[{"path":"manifest.json","sha256":"…","size":812}, …] }
```
流程:下载 zip(30s 超时)→ `wZipParseEntries` 解析 → 校验 path(禁 `../`/绝对路径)+ sha256 + size → 解到 `plugins/.staging/<id>/` → 校验 manifest 可解析且 id 匹配 → 替换目录 → 更新 index.json → 提示重启。
复查补充:
- **压缩方式固定 STORE**:`wZipReadEntry` 对 DEFLATE 依赖 `DecompressionStream('deflate-raw')`,而项目未设 `minimumSystemVersion`(默认 10.13),旧 macOS 的 WKWebView 没有该 API ⇒ 安装直接失败。插件包只有几十 KB,用 STORE 不压缩,顺带消除这个依赖。
- **Windows 覆盖替换**:`fs().rename` 在 Windows 对"已存在的目标目录"会报错。改为 `<id>.new` 就位 → 旧目录改名 `<id>.old` → rename `<id>.new` → 成功后删 `<id>.old`;失败则把 `<id>.old` 改回,保证可回滚。
- **安装限额**:解压后 ≤ 10MB、文件数 ≤ 200、单文件 ≤ 2MB;超限拒装(防 zip 炸弹与超大 assets)。
卸载:删目录 + **询问是否连数据一起删**(默认保留 `plugin-data/<id>.json`)。
### 2.6 展示页(唯一保留的网页)
`site/plugins/index.html` 与 `site/plugins-index.json` 由 `gen-site.js` 从 `market/index.json` 生成,部署在 `download.maqiart.eu.org/plugins/`。
- 页面只渲染卡片(图标/名称/版本/作者/描述/标签)+ 安装说明,**不直接读插件目录**(静态站没有文件系统)。
- 目录化后无需改页面结构;只需保证 `market/index.json` 字段可加性。
### 2.7 权限(advisory)
`permissions` 在 manifest 声明,宿主按声明放行 capability(无 `gallery.read` 就拿不到 `ctx.gallery`)。
诚实边界:插件仍运行在主页面上下文,**不是安全沙箱**;权限只是 API 门禁 + 安装时展示。
---
## 3. 里程碑
每阶段可独立发布/回滚。
### M1 目录插件加载(兼容旧单文件)
| 改动 | 文件 | 关键点 |
|---|---|---|
| 目录读写 API | `src/storage-file.js` | `listDirs/readFile/writeFile/writeBinary/mkdir/removeDir`;路径按段校验,禁 `..` |
| `loadFolder()` | `src/runtime-plugin-loader.js` | 见 2.4 |
| 三路合并 | `app.js` `wLoadRuntimePlugins` | 索引 + 扫描 + dev;目录优先 |
| 清单校验 | `src/plugin-host.js` `validate()` | 增 `main/style/permissions/data` |
| 构建产物 | `scripts/sync-plugins-from-repo.js` | 产出 `plugins/<id>/` + 升级版 index.json;单文件产物保留一版用于回滚 |
**验收**:`image-annotate` 转目录形态后台可加载、面板正常;其余 7 个单文件插件行为零变化。
### M2 数据层 `ctx.data`
| 改动 | 文件 |
|---|---|
| 数据适配器(Tauri 文件;非桌面内存兜底) | 新 `src/plugin-data.js` |
| `ctx.data` 注入 + 串行队列 | `src/plugin-host.js` |
| `iwb_plugins[id].data` 一次性迁移 | `app.js`(幂等,带 migrated 标记) |
| 设置页显示占用 + 清空 | `src/ui-settings-sections.js` |
**验收**:annotate 记住笔刷/颜色,重启仍在;旧数据迁移后保留一版原值。
### M3 市场 zip 安装
| 改动 | 文件 |
|---|---|
| 安装/卸载/校验/原子替换 | `src/runtime-plugin-market.js` |
| zip 读取复用 | `src/storage-zip.js`(现有 `wZipParseEntries`) |
| 市场索引生成(bundle + files)+ **Node 侧 STORE zip 打包** | `scripts/gen-market.js` + 发布脚本(复用 STORE 写法,勿引入压缩) |
**验收**:装到 `<资料目录>/plugins/<id>/` 且逐文件 hash 全对;改坏一个文件即拒装、旧版本不受影响;**Windows 上覆盖升级成功**、旧 macOS(无 DecompressionStream)也能装(因为包是 STORE)。
### M4 插件源仓构建目录化
| 改动 | 文件(iwb-plugins-desktop) |
|---|---|
| 产物改为目录(`manifest.json` + `main.js`),**CSS 仍内联** | `scripts/build-plugin.mjs` |
| 校验 manifest 完整性 | `scripts/validate.mjs` |
| 脚手架 | `template/` |
**验收**:任一插件 build + validate 后产出的目录可被 M1 直接消费;8 个插件迁移后功能一致。
> 复查修正:现有 8 个插件都是**运行时 `createElement('style')` 注入 CSS**(已实测 annotate),
> 因此 `styles.css` 只作为「手写插件」的可选项,**不改 esbuild 的 CSS 处理**,省掉一轮构建改造。
### M5 图库插件(第一个业务插件)
宿主新增 `gallery` capability(新 `src/plugin-api-gallery.js`):
```js
ctx.gallery = {
list({query, range, limit, offset}), thumb(name), original(name),
remove(names), download(names), insertToCanvas(names, {sizeK}),
on('changed', fn)
}
```
插件侧搬迁:`src/ui-gallery-head.js` + 图库网格 JSX(约 200 行)→ `gallery/main.js`;`app.js` 只留 `dockPanels` 一行注册。
**验收**:滚动/选中/全选反选/下载/插入/删除/双击预览/拖入画布 全一致;宿主删掉图库 JSX(app.js 行数下降)。
### M6 提示词库插件
宿主新增 `ctx.library.prompts`:
```js
list(), save({prompts, groups}), canvasPrompts(), insert(text, name)
```
数据搬进 `plugins/prompts/data.json`;插入画布走 `canvas.insertPrompt`(宿主实现,插件不碰画布状态)。
**验收**:增删改/分组/搜索/插入/导入导出全通;迁移前备份 `iwb_prompts`。
### M7 节点组库插件
宿主补齐 `canvasWrite`:
```js
saveSelectionAsGroup(name), instantiateGroup(snapshot), previewGroup(id)
```
**验收**:保存/应用/预览/删除全通;应用后位置不重叠、连线正确、可撤销。
---
## 4. 三个库的边界(插件化后)
| 关注点 | 归属 |
|---|---|
| 面板 UI、列表/筛选/按钮 | 插件 |
| 提示词/分组/节点组快照数据 | 插件 `data.json` |
| 图片字节 | **宿主** `images/`(不搬) |
| 图库索引 | 宿主(`out_*` + IDB),插件只读 |
| 画布插入/实例化 | 宿主 capability |
好处:卸载「图库插件」不删用户图片;卸载「提示词插件」可选连带数据。
---
## 5. 迁移与兼容
| 对象 | 策略 |
|---|---|
| 旧单文件插件 | 继续加载,给一个版本周期的双轨期 |
| 老市场单文件包 | 仍可安装(索引同时保留 `file` 与 `bundle`) |
| `localStorage['iwb_plugins']` | 一次性迁到新数据层,原值保留一版 |
| 提示词/分组 | 迁到插件 data.json,先写 `iwb_prompts_backup_<date>` |
| 图库 | **不迁移**,仍走宿主存储 |
| 测试快照 | 插件顺序/边界守门/市场测试同步;快照重生成须写理由 |
---
## 6. 回归清单(每个里程碑都跑)
1. 8 个内置插件全部加载,面板/节点/命令可用;设置页开关生效。
2. 开发者模式 `local/<id>/plugin.js` 仍可覆盖内置。
3. 同 id 的目录插件与单文件插件共存时,目录优先且只有一个实例。
4. 卸载后:面板/命令/节点类型/CSS 全部消失,无残留。
5. 数据:写→重启→读一致;并发两次写不丢(串行队列)。
6. 非桌面测试环境:插件可加载、`ctx.data` 内存兜底不抛错。
7. 桌面手工放 `<资料目录>/plugins/<id>/` 可被识别(无索引)。
8. `lint / typecheck / test:unit / test:facts` 全绿。
---
## 7. 风险
| 风险 | 缓解 |
|---|---|
| 插件无沙箱,权限只是门禁 | 安装时展示 permissions;只从官方市场安装;文档明确声明 |
| 目录形态失去 SRI | 逐文件 sha256 写进 index/manifest,加载前校验,不符拒载 |
| 双后端(文件/内存兜底)行为差异 | 同一套契约测试跑两遍;兜底只在无 Tauri 时启用 |
| UI 搬迁期宿主与插件双份代码 | 每个里程碑"搬完即删",不留双轨 |
| 画布写入 API 设计不当 | capability 内部复用 `commitCanvas` + 历史栈,插件只提交声明式快照 |
| 展示页与安装器共用索引,字段冲突 | 新字段可加性;`gen-site.js` 只读已知字段 |
---
## 8. 顺序
```
M1 目录加载 ──┬─→ M2 数据层 ──→ M5 图库插件 ──→ M6 提示词插件 ──→ M7 节点组插件
└─→ M4 源仓构建
M3 市场 zip ←(依赖 M1 的文件写入)
```
M1 与 M4 可并行;M3 与 M2 可并行;M5 之后每步都复用同一种 capability 模式。
---
## 9. 复查修订(2026-11-20 · 逐项核对代码后)
复查方法:把方案里每个"技术依赖"回到代码验证(zip 解压、fs 能力、备份范围、插件 CSS 注入方式、CSP、系统版本)。
| # | 复查发现 | 影响 | 处置 | 落点 |
|---|---|---|---|---|
| R1 | `wZipReadEntry` 的 DEFLATE 依赖 `DecompressionStream`,而 `tauri.conf` 未设 `minimumSystemVersion`(默认 10.13) | 旧 macOS 市场安装直接失败 | 市场包固定 **ZIP STORE** | M3 |
| R2 | `fs().rename` 在 Windows 覆盖已存在目录会报错 | 升级安装失败、无法回滚 | `<id>.new` → 旧目录改 `<id>.old` → rename → 删 old;失败回滚 | M3 |
| R3 | `runtime-plugin-backup.js` 只 collect 单文件 `code` | 目录插件**备份后恢复不回来** | collect/restore 改为按目录收集(不含 `data.json`) | M2/M3 |
| R4 | 备份 `items` 与 `wStorageAudit` 都不含插件数据 | 换机丢插件数据、占用看不见 | 备份加 `pluginData`;审计加「插件数据」项 | M2 |
| R5 | `ctx.storage`(localStorage)与 `ctx.data` 并存 → 双真源 | 迁移后同一数据两份、互相覆盖 | storage 只留 settings;迁移后清空 `iwb_plugins[id].data` 只留 `migratedAt` | M2 |
| R6 | 方案原要求构建产出 `styles.css`,但现有插件是运行时 `createElement('style')` 注入(annotate 实测) | 白改一轮 esbuild 管线 | `styles.css` 降为**手写插件可选项**,不改 CSS 构建 | M4 |
| R7 | 注入的 `<style>` 是全局的,停用/卸载不清理 | 插件 CSS 污染宿主 UI | 注入打 `data-plugin`,deactivate 时移除;手写插件强制 `.iwb-p-<id>-` 前缀(validate 校验) | M1 |
| R8 | 目录插件若只靠 manifest 自带的 hash 校验,等于自证 | 篡改可绕过 | 内置只信随包 `index.json`;manifest hash 只用于外部/市场 | 2.4 |
| R9 | 目录扫描顺序由文件系统决定;单插件异常可能中断整轮 | 加载不稳定 | 按 id 排序 + 单插件失败隔离 | M1 |
| R10 | 每次启动对 8 个插件做 sha256 + 读盘 | 冷启动变慢 | 内置按 `mtime+size` 缓存校验结果;外部每次校验 | M1 |
| R11 | 无解压体积/文件数限制 | zip 炸弹、超大 assets | 解压后 ≤10MB、≤200 文件、单文件 ≤2MB | M3 |
| R12 | 热启停可能重复注册面板/节点类型 | 面板出现两份 | `pluginId + id` 去重 | M1 |
| R13 | `ctx.asset` 每次读字节转 data URL | 图标频繁 IO | 内置走 `/plugins/<id>/assets/…` URL;外部读一次进缓存,停用清空 | M1 |
| R14 | 图库 500 张每次全量 `list` | 面板卡顿 | 分页 + `on('changed')` 节流 + 宿主侧索引缓存 | M5 |
| R15 | 插件化后若出问题只能发版回退 | 风险高 | 保留宿主面板一版,`iwb_panels_mode = legacy \| plugin` 开关 | M5–M7 |
| R16 | 第三方缺开发文档 | 只有你能写插件 | 产出 `docs/PLUGIN-DEV-GUIDE.md`(manifest/ctx/样式前缀/调试) | M4 |
### 顺带的 4 个优化(不改结构,但省事)
1. **先空跑**:M1 只把 annotate 转目录、行为零变化,用来验证加载链;不动任何业务面板。
2. **内置不扫描**:内置只读随包索引(快且安全),只有外部目录才扫描——省掉每次启动的文件系统遍历。
3. **图库插件首版只读**:先做「列表 + 预览 + 下载 + 插入」,删除/批量操作放到第二版,缩小首个业务插件的爆炸半径。
4. **双轨只保留一个版本**:目录插件稳定后,一次性删掉单文件产物与旧市场包,避免长期两套产物。
---
## 10. 明确不做
- 分类插件(画布分类维持 `iwb_home_cats` + `workspace.category`)。
- 插件沙箱、跨插件依赖声明、热重载(安装后仍要求重启)。
- 网页版应用:只有展示页/市场页/下载页是网页。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "image-workbench-web",
"private": true,
"version": "3.25.40",
"version": "3.25.41",
"description": "Browser-based node canvas image workbench",
"scripts": {
"build": "node scripts/build.js && node scripts/copy-plugins.js",
+17
View File
@@ -0,0 +1,17 @@
{
"id": "image-annotate",
"name": "标注 / 修图",
"version": "1.20.6",
"apiVersion": 1,
"main": "main.js",
"description": "在画布内标注、涂抹、局部重绘",
"author": "official",
"icon": "🖌️",
"tags": [
"修图",
"标注"
],
"files": {
"main.js": "7a865c7c353c3fbcaac551a8aeb5acd1bf624ca25f104db96fce493c3084b24f"
}
}
+5 -2
View File
@@ -19,9 +19,12 @@
},
{
"id": "image-annotate",
"file": "plugin-image-annotate.7a865c7c353c.js",
"dir": "image-annotate",
"main": "main.js",
"version": "1.20.6",
"integrity": "sha256-eoZcfDU8P7yqxVGorrWs0b9iTKJfEE25b85JPDCEsk8="
"files": {
"main.js": "7a865c7c353c3fbcaac551a8aeb5acd1bf624ca25f104db96fce493c3084b24f"
}
},
{
"id": "image-vectorize",
+13 -2
View File
@@ -21,6 +21,17 @@ for (const name of fs.readdirSync(src)) {
fs.copyFileSync(path.join(src, name), path.join(dst, name))
count++
}
// 索引与插件文件必须同源同包:应用按 index.json 里的 filename 去 /plugins/ 取
// v3.25.41(M1):目录插件 <plugins>/<id>/{manifest.json,main.js} 一并进包(应用按 /plugins/<id>/… 取)
let folders = 0
const pluginsRoot = path.join(root, 'plugins')
for (const name of fs.readdirSync(pluginsRoot)) {
const abs = path.join(pluginsRoot, name)
if (!fs.statSync(abs).isDirectory()) continue
if (name === 'runtime' || name === 'local') continue
if (!fs.existsSync(path.join(abs, 'manifest.json'))) continue
fs.cpSync(abs, path.join(dst, name), { recursive: true })
folders++
}
// 索引与插件文件必须同源同包:应用按 index.json 里的 filename / dir 去 /plugins/ 取
fs.copyFileSync(path.join(root, 'plugins', 'index.json'), path.join(dst, 'index.json'))
console.log('[copy-plugins] 已拷入 ' + count + ' 个插件 → dist/plugins/')
console.log('[copy-plugins] 已拷入 ' + count + ' 个文件 + ' + folders + ' 个目录插件 → dist/plugins/')
+4 -1
View File
@@ -12,7 +12,10 @@ const out = path.join(root, 'market')
fs.mkdirSync(path.join(out, 'plugins'), { recursive: true })
const sha = (buf) => crypto.createHash('sha256').update(buf)
const plugins = []
let skipped = 0
for (const e of man) {
// 目录插件(v3.25.41):市场打包(zip)在 M3 落地,这一版先跳过,避免生成缺 bundle 的条目
if (e.dir) { skipped++; console.warn('跳过目录插件(待 M3 打包):' + e.id); continue }
const src = path.join(root, 'plugins', 'runtime', e.file)
if (!fs.existsSync(src)) { console.warn('缺少产物:' + e.file); continue }
const buf = fs.readFileSync(src)
@@ -29,5 +32,5 @@ for (const e of man) {
}
const index = { version: 1, updatedAt: new Date().toISOString(), plugins: plugins }
fs.writeFileSync(path.join(out, 'index.json'), JSON.stringify(index, null, 2) + '\n')
console.log('market/index.json:' + plugins.length + ' 个插件')
console.log('market/index.json:' + plugins.length + ' 个插件' + (skipped ? '(跳过 ' + skipped + ' 个目录插件)' : ''))
for (const p of plugins) console.log(' ' + p.id.padEnd(16) + p.version.padEnd(8) + (p.size + ' B'))
+34 -1
View File
@@ -11,6 +11,8 @@ const root = path.resolve(__dirname, '..')
const srcRoot = process.argv[2] ? path.resolve(process.argv[2]) : path.resolve(root, '..', 'iwb-plugins-desktop')
const outDir = path.join(root, 'plugins', 'runtime')
const IDS = ['batch-export', 'blank-canvas', 'browser', 'image-annotate', 'image-vectorize', 'style-source', 'white-bg-800', 'xianyi-cutout']
// v3.25.41(M1):目录化插件试点 —— 这些 id 产出 <id>/{manifest.json,main.js},其余仍是单文件(双轨兼容)
const FOLDER_IDS = ['image-annotate']
const sha = (buf) => crypto.createHash('sha256').update(buf).digest()
const shaHex = (buf) => sha(buf).toString('hex')
@@ -21,12 +23,43 @@ fs.mkdirSync(outDir, { recursive: true })
const manifest = []
let copied = 0, changed = 0
const metaAll = (() => { try { return JSON.parse(fs.readFileSync(path.join(root, 'plugins', 'meta.json'), 'utf8')) } catch (e) { return {} } })()
for (const id of IDS) {
const artifact = path.join(srcRoot, id, 'src', 'index.js')
if (!fs.existsSync(artifact)) { console.warn('跳过 ' + id + '(无 ' + artifact + ')'); continue }
const buf = fs.readFileSync(artifact)
const name = 'plugin-' + id + '.' + shaHex(buf).slice(0, 12) + '.js'
const pkg = JSON.parse(fs.readFileSync(path.join(srcRoot, id, 'package.json'), 'utf8'))
if (FOLDER_IDS.indexOf(id) >= 0) {
// 目录形态:plugins/<id>/{manifest.json,main.js}
const dir = path.join(root, 'plugins', id)
fs.mkdirSync(dir, { recursive: true })
const mainPath = path.join(dir, 'main.js')
if (!fs.existsSync(mainPath) || shaHex(fs.readFileSync(mainPath)) !== shaHex(buf)) { fs.writeFileSync(mainPath, buf); copied++ }
const meta = metaAll[id] || {}
const manifestJson = {
id: id,
name: meta.name || id,
version: pkg.version,
apiVersion: Number((pkg.ibwPlugin && pkg.ibwPlugin.apiVersion) || 1),
main: 'main.js',
description: meta.desc || '',
author: meta.author || 'official',
icon: meta.icon || '',
tags: Array.isArray(meta.tags) ? meta.tags : [],
files: { 'main.js': shaHex(buf) },
}
fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifestJson, null, 2) + '\n')
// 同 id 的旧单文件产物清理(目录优先,留着会造成两份)
for (const old of fs.readdirSync(outDir)) {
if (old.indexOf('plugin-' + id + '.') === 0) { fs.unlinkSync(path.join(outDir, old)); changed++ }
}
manifest.push({ id: id, dir: id, main: 'main.js', style: manifestJson.style || '', version: pkg.version, files: manifestJson.files })
console.log(id.padEnd(16), pkg.version.padEnd(8), 'dir/' + id + '/main.js')
continue
}
const name = 'plugin-' + id + '.' + shaHex(buf).slice(0, 12) + '.js'
for (const old of fs.readdirSync(outDir)) {
if (old.indexOf('plugin-' + id + '.') === 0 && old !== name) { fs.unlinkSync(path.join(outDir, old)); changed++ }
}
+1 -1
View File
@@ -1983,7 +1983,7 @@ dependencies = [
[[package]]
name = "image-workbench"
version = "3.25.40"
version = "3.25.41"
dependencies = [
"arboard",
"base64 0.22.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "image-workbench"
version = "3.25.40"
version = "3.25.41"
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.40",
"version": "3.25.41",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
+7
View File
@@ -77,6 +77,11 @@
if (!Number.isInteger(manifest.apiVersion) || manifest.apiVersion < 1) return '清单 apiVersion 必须是正整数'
if (!Array.isArray(manifest.capabilities)) return '清单 capabilities 必须是数组'
if (manifest.settings !== undefined && (typeof manifest.settings !== 'object' || manifest.settings === null || Array.isArray(manifest.settings))) return '清单 settings 必须是对象'
// v3.25.41 目录插件(可选字段):入口/样式/权限/数据声明
if (manifest.main !== undefined && (typeof manifest.main !== 'string' || !/\.js$/.test(manifest.main))) return '清单 main 必须是 .js 文件名'
if (manifest.style !== undefined && (typeof manifest.style !== 'string' || !/\.css$/.test(manifest.style))) return '清单 style 必须是 .css 文件名'
if (manifest.permissions !== undefined && (!Array.isArray(manifest.permissions) || manifest.permissions.some((x) => typeof x !== 'string'))) return '清单 permissions 必须是字符串数组'
if (manifest.data !== undefined && (typeof manifest.data !== 'object' || manifest.data === null || Array.isArray(manifest.data))) return '清单 data 必须是对象'
for (const name of manifest.capabilities) {
if (CAPABILITIES.indexOf(name) < 0) return '未知能力 ' + name
}
@@ -192,6 +197,7 @@
record.active = true
record.instance = instance || null
record.error = null
if (deps && typeof deps.onActivate === 'function') { try { deps.onActivate(id) } catch (error) { log('plugin-activate-hook-failed', id, error && error.message) } }
notify({ kind: 'lifecycle', id, active: true })
return { ok: true, id }
}
@@ -215,6 +221,7 @@
for (const api of record.capabilityApis.splice(0)) {
try { if (api && typeof api.dispose === 'function') api.dispose() } catch (error) { log('plugin-capability-dispose-failed', id, error && error.message) }
}
if (deps && typeof deps.onDeactivate === 'function') { try { deps.onDeactivate(id) } catch (error) { log('plugin-deactivate-hook-failed', id, error && error.message) } }
notify({ kind: 'lifecycle', id, active: false })
return { ok: true, id }
}
+36 -6
View File
@@ -1,8 +1,12 @@
/* runtime-plugin-backup.js —— 插件进出备份
*
* 备份里带上插件清单与源码(体积很小),换机器恢复后不必重装。
* collect() → [{ id, version, file, integrity, code }]
* v3.25.41:兼容目录插件(<plugins>/<id>/{manifest.json,main.js,styles.css})
* collect() → [{ id, version, kind:'file', file, integrity, code }]
* | [{ id, version, kind:'folder', dir, main, style, files:{name: text}, hashes }]
* restore(v) → 写回 <资料目录>/plugins/ 并合并清单(备份里没有的插件保留)
*
* 注意:只备份**代码**,不备份插件数据(plugin-data 单独进备份,见 M2)。
*/
;(function (global) {
'use strict'
@@ -19,11 +23,23 @@
try { list = await s.manifest() } catch (e) { return [] }
const out = []
for (const e of (Array.isArray(list) ? list : [])) {
if (!e || !e.id || !e.file) continue
if (!e || !e.id) continue
// 目录插件:main + 可选 style 一起收(manifest 里的 files 只存 hash,文本要读出来)
if (e.dir) {
try {
const main = String(e.main || 'main.js')
const files = {}
files[main] = String(await s.readFile(String(e.dir) + '/' + main) || '')
if (e.style) files[String(e.style)] = String(await s.readFile(String(e.dir) + '/' + e.style) || '')
out.push({ id: e.id, version: e.version || '', kind: 'folder', dir: String(e.dir), main: main, style: e.style ? String(e.style) : '', files: files, hashes: e.files || null })
} catch (err) { /* 单个插件读失败不影响其它 */ }
continue
}
if (!e.file) continue
try {
const text = await s.read(e.file)
out.push({ id: e.id, version: e.version || '', file: e.file, integrity: e.integrity || '', code: String(text || '') })
} catch (err) { /* 单个插件读失败不影响其它 */ }
out.push({ id: e.id, version: e.version || '', kind: 'file', file: e.file, integrity: e.integrity || '', code: String(text || '') })
} catch (err) { /* 同上 */ }
}
return out
}
@@ -36,7 +52,21 @@
const byId = new Map((Array.isArray(cur) ? cur : []).map(function (e) { return [String(e && e.id), e] }))
let n = 0
for (const p of list) {
if (!p || !p.id || !p.file) continue
if (!p || !p.id) continue
if (p.kind === 'folder' && p.dir && p.files && typeof p.files === 'object') {
if (!/^[A-Za-z0-9._-]+$/.test(String(p.dir))) continue
try {
const names = Object.keys(p.files)
for (const name of names) {
if (!/^[A-Za-z0-9._-]+$/.test(name)) continue
await s.writeFile(String(p.dir) + '/' + name, String(p.files[name] || ''))
}
byId.set(String(p.id), { id: String(p.id), dir: String(p.dir), main: String(p.main || 'main.js'), style: String(p.style || ''), version: String(p.version || ''), files: p.hashes || null })
n++
} catch (err) { /* 单个失败忽略 */ }
continue
}
if (!p.file) continue
if (!/^[A-Za-z0-9._-]+$/.test(String(p.file))) continue
try {
await s.write(String(p.file), String(p.code || ''))
@@ -49,4 +79,4 @@
}
global.IWBRuntimePluginBackup = { collect: collect, restore: restore }
})(typeof window !== 'undefined' ? window : globalThis)
})(typeof window !== 'undefined' ? window : globalThis)
+108 -1
View File
@@ -29,6 +29,108 @@
return global.btoa(bin) === expect
}
async function sha256Hex (text) {
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(String(text)))
return Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('')
}
// 目录插件(v3.25.41 / M1):一个插件一个目录
// <内置>/plugins/<id>/{manifest.json,main.js,styles.css}
// <资料目录>/plugins/<id>/{同}
// 与单文件插件共用同一套「自注册」契约,区别只是多读一个 manifest 和可选 styles.css。
const styleNodes = {}
const pendingStyles = {}
function applyStyle (id, css) {
if (!css) return
try {
const doc = global.document
if (!doc) return
if (styleNodes[id] && styleNodes[id].parentNode) styleNodes[id].parentNode.removeChild(styleNodes[id])
const node = doc.createElement('style')
node.setAttribute('data-plugin', String(id))
node.textContent = String(css)
doc.head.appendChild(node)
styleNodes[id] = node
} catch (e) { /* 样式失败不影响脚本 */ }
}
function applyStyleFor (id) {
const css = pendingStyles[id]
if (css) applyStyle(id, css)
}
function removeStyle (id) {
try { const n = styleNodes[id]; if (n && n.parentNode) n.parentNode.removeChild(n); delete styleNodes[id] } catch (e) { /* ignore */ }
}
async function readFolderFile (record, name) {
if (record.source === 'external') {
const src = source()
if (!src || typeof src.readFile !== 'function') throw new Error('外部插件目录不可用')
return await src.readFile(record.dir + '/' + name)
}
const resp = await global.fetch('/plugins/' + record.dir + '/' + name, { cache: 'no-store' })
if (!resp.ok) throw new Error('读取插件文件失败:' + name + '(HTTP ' + resp.status + ')')
return await resp.text()
}
// 扫描 <资料目录>/plugins/*/manifest.json(无索引也能识别手工放入的目录插件)
async function listFolderEntries () {
const src = source()
if (!src || typeof src.listDirs !== 'function') return []
const out = []
let dirs = []
try { dirs = await src.listDirs() } catch (e) { return [] }
for (const d of dirs) {
const id = String((d && d.id) || '')
if (!id) continue
try {
const m = JSON.parse(await src.readFile(id + '/manifest.json'))
if (!m || String(m.id || '') !== id) continue
out.push({ id: id, dir: id, main: m.main || 'main.js', style: m.style || '', version: m.version || '', files: m.files || null, source: 'external' })
} catch (e) { /* 不是插件目录 */ }
}
return out
}
async function loadFolder (record) {
record.status = 'loading'
try {
// 目录里的 manifest.json 是入口/样式的真源:内置索引只带 hash,字段缺省时向 manifest 补
if (record.source !== 'external') {
try {
const m = JSON.parse(await readFolderFile(record, 'manifest.json'))
if (m && typeof m === 'object') {
if (typeof m.main === 'string' && m.main) record.main = m.main
if (typeof m.style === 'string' && m.style) record.style = m.style
if (!record.version && m.version) record.version = String(m.version)
}
} catch (e) { /* 无 manifest 时按索引里的 main */ }
}
const main = String(record.main || 'main.js')
const code = await readFolderFile(record, main)
// 逐文件 sha256:内置以随包 index.json 的值为准(外部/市场安装同理),不一致直接拒载
const expect = record.hashes && record.hashes[main]
if (expect) {
const actual = await sha256Hex(code)
if (actual !== String(expect).toLowerCase()) throw new Error('完整性校验失败(' + main + ' 的 sha256 不符)')
}
if (record.style) {
// 只在插件**激活**时注入样式(停用状态不该污染宿主 UI);文本先暂存,激活由宿主触发
try { pendingStyles[record.id] = await readFolderFile(record, String(record.style)) } catch (e) { /* 样式缺失不阻断 */ }
}
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
try {
await inject({ src: url, error: '插件脚本执行失败(' + record.id + ')' })
} finally {
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
}
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
// 注入一段脚本并等它执行完(插件在加载期自我注册)
function inject (attrs) {
return new Promise(function (resolve, reject) {
@@ -114,8 +216,13 @@
global.IWBRuntimePluginLoader = {
source: source,
verifyCode: verifyCode,
sha256Hex: sha256Hex,
loadBuiltin: loadBuiltin,
loadExternal: loadExternal,
loadLocal: loadLocal
loadLocal: loadLocal,
loadFolder: loadFolder,
listFolderEntries: listFolderEntries,
applyStyleFor: applyStyleFor,
removeStyle: removeStyle
}
})(typeof window !== 'undefined' ? window : globalThis)
+63 -1
View File
@@ -460,6 +460,68 @@
return p
}
// ---- 目录插件(v3.25.41 / M1):<资料目录>/plugins/<id>/{manifest.json,main.js,styles.css,…} ----
// 路径一律按「段」校验,禁绝对路径与 ..(防目录穿越);单文件读写沿用上面的 read/write。
function safePluginRel(rel) {
const parts = String(rel || '').split('/')
if (!parts.length || parts.length > 6) throw new Error('非法插件路径')
for (const seg of parts) {
if (!seg || !/^[A-Za-z0-9._-]+$/.test(seg) || seg === '.' || seg === '..') throw new Error('非法插件路径')
}
return parts.join('/')
}
async function pluginRoot() {
const p = await pluginDir()
try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ }
return p
}
async function pluginFilePath(rel) {
return join(await pluginRoot(), safePluginRel(rel))
}
// 扫描 <plugins>/* 的目录(不递归),只返回目录名,是否是真插件由调用方读 manifest 判断
async function pluginListDirs() {
try {
const root = await pluginRoot()
const entries = await fs().readDir(root)
return entries.filter((e) => e && e.isDirectory && /^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(e.name)).map((e) => ({ id: e.name }))
} catch (e) { return [] }
}
async function pluginReadFile(rel) {
return fs().readTextFile(await pluginFilePath(rel))
}
async function pluginWriteFile(rel, text) {
const abs = await pluginFilePath(rel)
const segs = safePluginRel(rel).split('/')
if (segs.length > 1) {
const parent = await join(await pluginRoot(), segs.slice(0, -1).join('/'))
try { await fs().mkdir(parent, { recursive: true }) } catch (e) { /* 已存在 */ }
}
await fs().writeTextFile(abs, String(text))
return true
}
async function pluginWriteBinary(rel, bytes) {
const abs = await pluginFilePath(rel)
const segs = safePluginRel(rel).split('/')
if (segs.length > 1) {
const parent = await join(await pluginRoot(), segs.slice(0, -1).join('/'))
try { await fs().mkdir(parent, { recursive: true }) } catch (e) { /* 已存在 */ }
}
await fs().writeFile(abs, new Uint8Array(bytes))
return true
}
async function pluginMkdir(rel) {
const abs = await pluginFilePath(rel)
await fs().mkdir(abs, { recursive: true })
return true
}
// 删除插件目录(递归)。只允许一级 <id>,避免误删 plugins 根或上级目录。
async function pluginRemoveDir(id) {
const seg = safePluginRel(id)
if (seg.indexOf('/') >= 0) throw new Error('只允许删除一级插件目录')
await fs().remove(await join(await pluginRoot(), seg), { recursive: true })
return true
}
async function loadInto() {
// data.json 不存在 ⇒ 把当前 WebView 里的数据迁过去(只做一次)
const target = await join(dir, DATA_FILE)
@@ -895,7 +957,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 },
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 },
storage: () => storage,
kv: () => kv,
dir: () => dir,