235 lines
12 KiB
JavaScript
235 lines
12 KiB
JavaScript
'use strict'
|
||
|
||
const assert = require('assert')
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
const vm = require('vm')
|
||
|
||
const root = path.resolve(__dirname, '..')
|
||
const source = fs.readFileSync(path.join(root, 'src', 'plugin-host.js'), 'utf8')
|
||
const sandbox = {}
|
||
vm.runInNewContext(source, sandbox)
|
||
|
||
const host0 = sandbox.IWBPluginHost
|
||
assert.ok(Number.isInteger(host0.apiVersion) && host0.apiVersion >= 1, 'apiVersion 必须是正整数')
|
||
assert.ok(Array.isArray(host0.capabilities) && host0.capabilities.length >= 7, '能力清单应非空')
|
||
assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,files,gallery,generationHooks,grouplib,images,nodeActions,nodeTypes,panels,promptlib,providers')
|
||
|
||
const manifest = (over) => Object.assign({ id: 'demo-plugin', name: 'Demo', version: '1.0.0', apiVersion: 1, capabilities: [] }, over)
|
||
const stateOf = (ids) => {
|
||
const state = {}
|
||
for (const id of ids) state[id] = { enabled: true, settings: {}, data: {} }
|
||
return state
|
||
}
|
||
|
||
const registry = sandbox.IWBPluginHostFactory()
|
||
assert.strictEqual(registry.register(manifest(), () => ({})).ok, true)
|
||
assert.strictEqual(registry.register(manifest(), () => ({})).ok, false, '重复 id 必须拒绝')
|
||
assert.strictEqual(registry.register(manifest({ id: 'X' }), () => ({})).ok, false, '非法 id 必须拒绝')
|
||
assert.strictEqual(registry.register(manifest({ id: 'ab' }), () => ({})).ok, false, '过短 id 必须拒绝')
|
||
assert.strictEqual(registry.register({ name: 'no id' }, () => ({})).ok, false, '缺字段必须拒绝')
|
||
assert.strictEqual(registry.register(manifest({ id: 'no-version', version: undefined }), () => ({})).ok, false, '缺 version 必须拒绝')
|
||
assert.strictEqual(registry.register(manifest({ id: 'bad-api', apiVersion: 0 }), () => ({})).ok, false, 'apiVersion 必须正整数')
|
||
assert.strictEqual(registry.register(manifest({ id: 'bad-caps', capabilities: ['nope'] }), () => ({})).ok, false, '未知能力必须拒绝')
|
||
assert.strictEqual(registry.register(manifest({ id: 'bad-caps2', capabilities: 'panels' }), () => ({})).ok, false, 'capabilities 必须是数组')
|
||
assert.strictEqual(registry.register(manifest({ id: 'no-factory' }), 'nope').ok, false, '工厂必须是函数')
|
||
assert.strictEqual(registry.list().length, 1, '被拒绝的注册不得进入注册表')
|
||
// 2026-11-17:默认启用(插件随市场安装即可用;只有用户显式关掉才写 enabled:false)
|
||
assert.strictEqual(registry.isEnabled('demo-plugin'), true)
|
||
|
||
let persisted = { 'demo-plugin': { enabled: true, settings: { theme: 'dark' }, data: {} } }
|
||
const writes = []
|
||
let disposes = 0
|
||
const heard = []
|
||
const contexts = []
|
||
const deps = (state, capabilities) => ({
|
||
readState: () => JSON.parse(JSON.stringify(state)),
|
||
writeState: (next) => { persisted = JSON.parse(JSON.stringify(next)); writes.push(next) },
|
||
log: () => {},
|
||
capabilities: capabilities || {}
|
||
})
|
||
|
||
const host = sandbox.IWBPluginHostFactory()
|
||
host.register(manifest(), (ctx) => {
|
||
contexts.push(ctx)
|
||
ctx.events.on('node:created', (payload) => heard.push(payload))
|
||
return { dispose() { disposes++ } }
|
||
})
|
||
const activated = host.init(deps(persisted))
|
||
assert.strictEqual(activated.length, 1)
|
||
assert.strictEqual(activated[0].ok, true)
|
||
assert.strictEqual(contexts.length, 1)
|
||
assert.strictEqual(disposes, 0)
|
||
|
||
const ctx = contexts[0]
|
||
assert.strictEqual(ctx.id, 'demo-plugin')
|
||
assert.strictEqual(ctx.apiVersion, host.apiVersion)
|
||
assert.strictEqual(ctx.settings.get('theme'), 'dark', '设置应从持久化状态读入')
|
||
assert.strictEqual(typeof ctx.settings.set, 'function')
|
||
assert.strictEqual(typeof ctx.storage.namespace, 'function')
|
||
assert.strictEqual(typeof ctx.events.on, 'function')
|
||
assert.strictEqual(typeof ctx.log, 'function')
|
||
assert.strictEqual(ctx.canvas, undefined, '未声明能力不得发放 canvas')
|
||
assert.strictEqual(ctx.ui, undefined, '未声明能力不得发放 ui')
|
||
assert.strictEqual(ctx.nodes, undefined)
|
||
|
||
ctx.settings.set('theme', 'light')
|
||
assert.strictEqual(persisted['demo-plugin'].settings.theme, 'light', '设置写入必须回写持久化')
|
||
|
||
const bucket = ctx.storage.namespace('ns1')
|
||
bucket.set('k', 1)
|
||
assert.strictEqual(bucket.get('k'), 1)
|
||
assert.strictEqual(bucket.keys().join(','), 'k')
|
||
assert.strictEqual(persisted['demo-plugin'].data.ns1.k, 1)
|
||
bucket.remove('k')
|
||
assert.strictEqual(bucket.get('k'), undefined)
|
||
|
||
host.emit('node:created', { id: 'n1' })
|
||
assert.strictEqual(heard.length, 1, '宿主广播应到达插件监听器')
|
||
|
||
host.setEnabled('demo-plugin', false)
|
||
assert.strictEqual(disposes, 1, '停用必须调用 dispose')
|
||
assert.strictEqual(host.list()[0].active, false)
|
||
host.setEnabled('demo-plugin', true)
|
||
host.emit('node:created', { id: 'n2' })
|
||
assert.strictEqual(heard.length, 2, '重新启用不得重复订阅(应为 2 而非 3)')
|
||
host.setEnabled('demo-plugin', false)
|
||
assert.strictEqual(disposes, 2)
|
||
assert.strictEqual(host.deactivate('demo-plugin').already, true, '重复停用应幂等')
|
||
assert.strictEqual(disposes, 2, '幂等停用不得再次 dispose')
|
||
assert.strictEqual(host.setEnabled('unregistered', true).ok, false, '未注册插件不得启停')
|
||
|
||
const isolated = sandbox.IWBPluginHostFactory()
|
||
const other = []
|
||
for (const id of ['plugin-a', 'plugin-b']) {
|
||
isolated.register(manifest({ id }), (c) => {
|
||
c.storage.namespace('shared').set('owner', id)
|
||
other.push([id, c.storage.namespace('shared').get('owner')])
|
||
return {}
|
||
})
|
||
}
|
||
isolated.init(deps(stateOf(['plugin-a', 'plugin-b'])))
|
||
assert.deepStrictEqual(other, [['plugin-a', 'plugin-a'], ['plugin-b', 'plugin-b']], '插件存储命名空间必须互相隔离')
|
||
|
||
const granted = sandbox.IWBPluginHostFactory()
|
||
let panels = 0
|
||
granted.register(manifest({ id: 'panel-plugin', capabilities: ['panels', 'canvas'] }), (c) => {
|
||
c.ui.registerPanel({ id: 'p' })
|
||
c.canvas.getNodes()
|
||
return {}
|
||
})
|
||
granted.init(deps(stateOf(['panel-plugin']), {
|
||
panels: () => ({ registerPanel: () => { panels++; return true } }),
|
||
canvas: () => ({ getNodes: () => [] })
|
||
}))
|
||
assert.strictEqual(panels, 1, '声明且已提供的能力应发放对应子 API')
|
||
granted.setEnabled('panel-plugin', false)
|
||
granted.setEnabled('panel-plugin', true)
|
||
assert.strictEqual(panels, 2, '重新启用应重新发放能力')
|
||
|
||
const broken = sandbox.IWBPluginHostFactory()
|
||
broken.register(manifest({ id: 'boom-plugin' }), () => { throw new Error('boom') })
|
||
broken.register(manifest({ id: 'ok-plugin' }), () => ({}))
|
||
const results = broken.init(deps(stateOf(['boom-plugin', 'ok-plugin'])))
|
||
assert.strictEqual(results.length, 2)
|
||
assert.strictEqual(results[0].ok, false, '工厂抛错必须被隔离')
|
||
assert.ok(/boom/.test(results[0].error))
|
||
assert.strictEqual(results[1].ok, true, '一个插件抛错不得影响其他插件')
|
||
assert.strictEqual(broken.list().find((p) => p.id === 'ok-plugin').active, true)
|
||
assert.strictEqual(broken.snapshot().errors, 1)
|
||
|
||
const future = sandbox.IWBPluginHostFactory()
|
||
future.register(manifest({ id: 'future-plugin', apiVersion: 99 }), () => ({}))
|
||
assert.strictEqual(future.register(manifest({ id: 'future-plugin-2', apiVersion: 99 }), () => ({})).ok, true)
|
||
assert.strictEqual(future.activate('future-plugin').ok, false, 'apiVersion 高于宿主必须拒绝激活')
|
||
assert.strictEqual(future.list().find((p) => p.id === 'future-plugin').compatible, false)
|
||
assert.strictEqual(future.list().find((p) => p.id === 'future-plugin').active, false)
|
||
|
||
assert.strictEqual(host.snapshot().initialized, true)
|
||
assert.strictEqual(host.snapshot().registered, 1)
|
||
assert.deepStrictEqual(writes.length > 0, true)
|
||
assert.strictEqual(host.disposeAll()[0].already, true)
|
||
|
||
assert.strictEqual(sandbox.IWBPluginHostFactory().register(manifest({ id: 'bad-settings', settings: 'nope' }), () => ({})).ok, false, 'settings 必须是对象')
|
||
assert.strictEqual(sandbox.IWBPluginHostFactory().register(manifest({ id: 'bad-settings2', settings: [] }), () => ({})).ok, false, 'settings 不得是数组')
|
||
|
||
const panel = sandbox.IWBPluginHostFactory()
|
||
const changed = []
|
||
panel.register(manifest({ id: 'panel-plugin', settings: { tone: { type: 'text', label: '语气' }, loud: { type: 'boolean' } } }), (c) => {
|
||
c.settings.onChange((name) => changed.push(name))
|
||
return {}
|
||
})
|
||
panel.init(deps({ 'panel-plugin': { enabled: true, settings: { tone: 'calm' }, data: {} } }))
|
||
const row = panel.list()[0]
|
||
assert.strictEqual(row.id, 'panel-plugin')
|
||
assert.strictEqual(Object.keys(row.settingsSchema).join(','), 'tone,loud', '管理面板需要拿到设置 schema')
|
||
assert.strictEqual(row.settings.tone, 'calm', '管理面板需要拿到当前设置值')
|
||
assert.strictEqual(panel.setSetting('panel-plugin', 'tone', 'loud').ok, true)
|
||
assert.strictEqual(persisted['panel-plugin'].settings.tone, 'loud', 'setSetting 必须回写持久化')
|
||
assert.strictEqual(changed.join(','), 'tone', 'setSetting 必须通知插件自身的 onChange')
|
||
assert.strictEqual(panel.setSetting('unregistered', 'x', 1).ok, false, '未注册插件不得改设置')
|
||
|
||
const capHost = sandbox.IWBPluginHostFactory()
|
||
const closed = []
|
||
let opened = 0
|
||
capHost.register(manifest({ id: 'cap-plugin', capabilities: ['commands'] }), () => ({}))
|
||
capHost.init(deps(stateOf(['cap-plugin']), {
|
||
commands: () => {
|
||
opened++
|
||
return { register: () => true, dispose: () => closed.push(opened) }
|
||
},
|
||
}))
|
||
assert.strictEqual(opened, 1, '能力工厂应在激活时被调用以便发放子 API')
|
||
capHost.setEnabled('cap-plugin', false)
|
||
assert.strictEqual(closed.join(','), '1', '能力产物必须随停用卸载')
|
||
capHost.setEnabled('cap-plugin', true)
|
||
assert.strictEqual(opened, 2, '重新启用应重新发放能力产物')
|
||
assert.strictEqual(closed.join(','), '1')
|
||
assert.strictEqual(capHost.list()[0].active, true)
|
||
|
||
const notices = []
|
||
const off = capHost.on((event) => notices.push(event.kind))
|
||
const before = notices.length
|
||
capHost.setEnabled('cap-plugin', false)
|
||
assert.ok(notices.length > before, '宿主级 on 应收到生命周期通知')
|
||
off()
|
||
const after = notices.length
|
||
capHost.activate('cap-plugin')
|
||
assert.strictEqual(notices.length, after, '取消订阅后不得再收到通知')
|
||
|
||
const mergeHost = sandbox.IWBPluginHostFactory()
|
||
let mergedKeys = ''
|
||
mergeHost.register(manifest({ id: 'canvas-plugin', capabilities: ['canvas', 'canvasWrite'] }), (c) => {
|
||
mergedKeys = Object.keys(c.canvas).sort().join(',')
|
||
return {}
|
||
})
|
||
mergeHost.init(deps(stateOf(['canvas-plugin']), {
|
||
canvas: () => ({ getNodes: () => [], listNodeTypes: () => [] }),
|
||
canvasWrite: () => ({ createNode: () => null }),
|
||
}))
|
||
assert.strictEqual(mergedKeys, 'createNode,getNodes,listNodeTypes', '映射到同一 ctx key 的多个能力必须合并,不能互相覆盖')
|
||
|
||
const defaultsHost = sandbox.IWBPluginHostFactory()
|
||
let seenSettings = null
|
||
defaultsHost.register(manifest({ id: 'defaults-plugin', settings: { crop: { type: 'boolean', default: true }, label2: { type: 'text', default: 'hi' }, noDefault: { type: 'text' } } }), (c) => {
|
||
seenSettings = { crop: c.settings.get('crop'), label2: c.settings.get('label2'), noDefault: c.settings.get('noDefault'), all: c.settings.all() }
|
||
return {}
|
||
})
|
||
defaultsHost.init(deps({ 'defaults-plugin': { enabled: true, settings: {}, data: {} } }))
|
||
assert.strictEqual(seenSettings.crop, true, '清单声明的 default 必须在未存值时可读(否则插件看不到自己的默认值)')
|
||
assert.strictEqual(seenSettings.label2, 'hi')
|
||
assert.strictEqual(seenSettings.noDefault, undefined)
|
||
assert.strictEqual(seenSettings.all.crop, true, 'all() 必须包含声明默认值')
|
||
|
||
// A2 按需加载:isEnabled 必须能读「未注册」插件的持久化开关(启动加载器据此决定是否下载远程脚本),
|
||
// 且查询本身不得为陌生 id 创建 state 条目(否则会把从未启用的插件写进持久化)。
|
||
const lazyHost = sandbox.IWBPluginHostFactory()
|
||
const lazyState = { 'lazy-plugin': { enabled: true, settings: {}, data: {} } }
|
||
lazyHost.init({ readState: () => lazyState, writeState: () => {}, log: () => {} })
|
||
assert.strictEqual(lazyHost.isEnabled('lazy-plugin'), true, '未注册插件也应读出持久化的启用开关')
|
||
// 2026-11-17:改为默认 true —— 启动早期持久化还没读到时,若按 false 处理会把所有插件判成"已停用"而进 idle
|
||
assert.strictEqual(lazyHost.isEnabled('never-heard'), true, '持久化里没有记录的未注册插件按默认启用(true)')
|
||
assert.strictEqual(Object.keys(lazyState).join(','), 'lazy-plugin', 'isEnabled 查询不得为未注册插件创建 state 条目')
|
||
|
||
console.log('plugin host checks passed')
|