Files
image-workbench-desktop/src/plugin-host.js
T

315 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
;(function (global) {
'use strict'
const API_VERSION = 1
const ID_PATTERN = /^[a-z][a-z0-9-]{2,31}$/
const REQUIRED_FIELDS = ['id', 'name', 'version', 'apiVersion', 'capabilities']
const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions']
const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions' }
function createPluginHost(options) {
const opt = options || {}
const plugins = new Map()
const listeners = []
let deps = null
let state = {}
function log() {
if (typeof opt.log === 'function') { try { opt.log.apply(null, arguments) } catch (error) { /* 日志失败不影响宿主 */ } }
if (deps && typeof deps.log === 'function') { try { deps.log.apply(null, arguments) } catch (error) { /* 同上 */ } }
}
function readState() {
if (deps && typeof deps.readState === 'function') {
try {
const value = deps.readState()
if (value && typeof value === 'object') return value
} catch (error) { log('plugin-state-read-failed', error && error.message) }
}
return {}
}
function writeState() {
if (deps && typeof deps.writeState === 'function') {
try { deps.writeState(state) } catch (error) { log('plugin-state-write-failed', error && error.message) }
}
}
function recordOf(id) {
const current = state[id]
if (current && typeof current === 'object') return current
// 默认启用:插件随包发布即应可用;只有用户显式关掉才写 enabled:false
const created = { enabled: true, settings: {}, data: {} }
state[id] = created
return created
}
function subscribe(handler) {
listeners.push(handler)
let active = true
return function () {
if (!active) return
active = false
const index = listeners.indexOf(handler)
if (index >= 0) listeners.splice(index, 1)
}
}
function notify(event) {
for (const handler of listeners.slice()) {
try { handler(event) } catch (error) { log('plugin-listener-failed', error && error.message) }
}
}
function noteError(id, error) {
const message = error && error.message ? error.message : String(error)
const record = plugins.get(id)
if (record) record.error = message
log('plugin-callback-failed', id, message)
}
function validate(manifest) {
if (!manifest || typeof manifest !== 'object') return '清单必须是对象'
for (const field of REQUIRED_FIELDS) {
if (manifest[field] === undefined || manifest[field] === null) return '清单缺少必填字段 ' + field
}
if (!ID_PATTERN.test(String(manifest.id))) return '清单 id 不合法(须 ^[a-z][a-z0-9-]{2,31}$)'
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 必须是对象'
for (const name of manifest.capabilities) {
if (CAPABILITIES.indexOf(name) < 0) return '未知能力 ' + name
}
return null
}
function compatible(manifest) {
return Number.isInteger(manifest.apiVersion) && manifest.apiVersion <= API_VERSION
}
function register(manifest, factory) {
const invalid = validate(manifest)
if (invalid) { log('plugin-register-rejected', invalid); return { ok: false, error: invalid } }
if (typeof factory !== 'function') { const error = '插件工厂必须是函数'; log('plugin-register-rejected', error); return { ok: false, error } }
const id = String(manifest.id)
if (plugins.has(id)) { const error = '插件 id 重复:' + id; log('plugin-register-rejected', error); return { ok: false, error } }
plugins.set(id, { manifest, factory, active: false, instance: null, error: null, subscriptions: [], capabilityApis: [] })
return { ok: true, id }
}
function buildStorage(id) {
function bucket(ns) {
const key = ns === undefined || ns === null ? '' : String(ns)
const record = recordOf(id)
const data = record.data && typeof record.data === 'object' ? record.data : (record.data = {})
const slot = data[key] && typeof data[key] === 'object' ? data[key] : (data[key] = {})
return {
get: function (name) { return slot[String(name)] },
set: function (name, value) { slot[String(name)] = value; writeState() },
remove: function (name) { delete slot[String(name)]; writeState() },
keys: function () { return Object.keys(slot) }
}
}
return { namespace: bucket }
}
function buildContext(id, manifest) {
const record = recordOf(id)
const entry = plugins.get(id)
const track = function (unsubscribe) {
if (typeof unsubscribe === 'function' && entry && Array.isArray(entry.subscriptions)) entry.subscriptions.push(unsubscribe)
return unsubscribe
}
const declaredDefaults = {}
const schema = manifest.settings && typeof manifest.settings === 'object' ? manifest.settings : {}
for (const key of Object.keys(schema)) {
if (schema[key] && typeof schema[key] === 'object' && schema[key].default !== undefined) declaredDefaults[key] = schema[key].default
}
const settings = {
all: function () { return Object.assign({}, declaredDefaults, record.settings) },
get: function (name) {
const key = String(name)
if (record.settings[key] !== undefined) return record.settings[key]
return declaredDefaults[key]
},
set: function (name, value) { record.settings[String(name)] = value; writeState(); notify({ kind: 'settings', id, name: String(name) }) },
onChange: function (handler) {
if (typeof handler !== 'function') return function () {}
return track(subscribe(function (event) {
if (event.kind !== 'settings' || event.id !== id) return
try { handler(event.name) } catch (error) { noteError(id, error) }
}))
}
}
const storage = buildStorage(id)
const events = {
on: function (name, handler) {
if (typeof handler !== 'function') return function () {}
return track(subscribe(function (event) {
if (event.kind !== 'event' || event.name !== name) return
try { handler(event.payload) } catch (error) { noteError(id, error) }
}))
},
emit: function (name, payload) { notify({ kind: 'event', id, name: String(name), payload }); return true }
}
const ctx = {
id,
manifest,
apiVersion: API_VERSION,
log: function () { const args = ['[plugin:' + id + ']'].concat(Array.prototype.slice.call(arguments)); log.apply(null, args) },
settings,
storage,
events
}
const granted = deps && deps.capabilities && typeof deps.capabilities === 'object' ? deps.capabilities : {}
for (const name of manifest.capabilities) {
const apiKey = CAPABILITY_API_KEYS[name]
if (!apiKey || typeof granted[name] !== 'function') continue
try {
const api = granted[name]({ id, manifest, settings, storage, events, log: ctx.log })
if (api && typeof api === 'object') {
ctx[apiKey] = Object.assign({}, ctx[apiKey], api)
if (typeof api.dispose === 'function' && entry) entry.capabilityApis.push(api)
}
} catch (error) { noteError(id, error) }
}
return ctx
}
function activate(id) {
const record = plugins.get(id)
if (!record) return { ok: false, error: '未注册的插件:' + id }
if (!compatible(record.manifest)) { record.error = 'apiVersion 不兼容(插件 ' + record.manifest.apiVersion + ' > 宿主 ' + API_VERSION + ')'; log('plugin-incompatible', id); return { ok: false, error: record.error } }
if (record.active) return { ok: true, id, already: true }
let instance = null
try {
instance = record.factory(buildContext(id, record.manifest))
} catch (error) {
record.error = error && error.message ? error.message : String(error)
log('plugin-activate-failed', id, record.error)
return { ok: false, error: record.error }
}
record.active = true
record.instance = instance || null
record.error = null
notify({ kind: 'lifecycle', id, active: true })
return { ok: true, id }
}
function deactivate(id) {
const record = plugins.get(id)
if (!record) return { ok: false, error: '未注册的插件:' + id }
if (!record.active) return { ok: true, id, already: true }
const instance = record.instance
record.active = false
record.instance = null
try {
if (instance && typeof instance.dispose === 'function') instance.dispose()
} catch (error) {
record.error = error && error.message ? error.message : String(error)
log('plugin-dispose-failed', id, record.error)
}
for (const unsubscribe of record.subscriptions.splice(0)) {
try { unsubscribe() } catch (error) { log('plugin-unsubscribe-failed', id, error && error.message) }
}
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) }
}
notify({ kind: 'lifecycle', id, active: false })
return { ok: true, id }
}
function setEnabled(id, enabled) {
const record = plugins.get(id)
if (!record) return { ok: false, error: '未注册的插件:' + id }
recordOf(id).enabled = Boolean(enabled)
writeState()
return recordOf(id).enabled ? activate(id) : deactivate(id)
}
function isEnabled(id) {
if (plugins.has(id)) return Boolean(recordOf(id).enabled)
// 未注册:有持久化记录就按记录;**没有记录 ⇒ 默认启用**
// (否则启动早期 state 还没读到时,所有插件都会被判成「已停用」而进 idle)
const rec = state[id]
if (!rec) return true
return Boolean(rec.enabled)
}
function init(nextDeps) {
deps = nextDeps && typeof nextDeps === 'object' ? nextDeps : {}
state = readState()
const activated = []
for (const id of Array.from(plugins.keys())) {
if (recordOf(id).enabled) activated.push(activate(id))
}
notify({ kind: 'ready', apiVersion: API_VERSION, plugins: plugins.size })
return activated
}
function disposeAll() {
const result = []
for (const id of Array.from(plugins.keys())) result.push(deactivate(id))
return result
}
function list() {
const out = []
for (const entry of plugins.entries()) {
const id = entry[0]
const record = entry[1]
const persisted = state[id] && typeof state[id] === 'object' ? state[id] : {}
out.push({
id,
name: record.manifest.name,
version: record.manifest.version,
apiVersion: record.manifest.apiVersion,
capabilities: record.manifest.capabilities.slice(),
settingsSchema: record.manifest.settings || {},
settings: Object.assign({}, persisted.settings),
enabled: Boolean(persisted.enabled),
active: record.active,
compatible: compatible(record.manifest),
error: record.error
})
}
out.sort(function (a, b) { return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0) })
return out
}
function setSetting(id, name, value) {
if (!plugins.has(id)) return { ok: false, error: '未注册的插件:' + id }
const record = recordOf(id)
record.settings[String(name)] = value
writeState()
notify({ kind: 'settings', id, name: String(name) })
return { ok: true, id }
}
function on(handler) {
if (typeof handler !== 'function') return function () {}
return subscribe(handler)
}
function emit(name, payload) {
notify({ kind: 'event', id: null, name: String(name), payload })
return true
}
function snapshot() {
let active = 0
let errors = 0
for (const record of plugins.values()) {
if (record.active) active++
if (record.error) errors++
}
return { apiVersion: API_VERSION, registered: plugins.size, active, errors, listeners: listeners.length, initialized: Boolean(deps) }
}
return { apiVersion: API_VERSION, capabilities: CAPABILITIES.slice(), register, list, init, setEnabled, isEnabled, activate, deactivate, disposeAll, setSetting, on, emit, snapshot }
}
global.IWBPluginHostFactory = createPluginHost
global.IWBPluginHost = createPluginHost()
})(typeof window !== 'undefined' ? window : globalThis)