Files
Reims-Go/frontend/src/lib/uiSdk.ts
T

188 lines
6.2 KiB
TypeScript

// Lazy-loaded Tier-3 Interactive Theme UI SDK (docs/plugin-architecture.md §5.1).
// Loaded ONLY when a trusted interactive theme with `ui:script` is enabled (§8.1).
import { UI_API_VERSION, UI_CONTRACT_PARTS, UI_CONTRACT_SLOTS, type UIContractPart, type UIContractSlot } from '../styles/ui-contract'
import { hideWailsGlobals } from '../wails'
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
export interface ReimsUISDK {
readonly uiApi: string
/** Registers a cleanup callback run in LIFO order on theme switch/disable. */
onDispose: (fn: () => void) => void
/** Runs a named feature isolated so errors disable only that feature. */
feature: (name: string, setup: (dispose: (fn: () => void) => void) => void) => void
/** Read-only non-sensitive state snapshot & subscription. */
getState: () => UIStateSnapshot
subscribeState: (cb: (snap: UIStateSnapshot) => void) => () => void
/** Queries elements strictly by contract part class (`rg-p-*`). */
queryPart: (part: UIContractPart) => HTMLElement | null
/** Shared MutationObserver bus scoped to a contract part. */
observePart: (part: UIContractPart, cb: () => void) => () => void
/** Shared RAF read/write batch pipeline to avoid layout thrashing. */
scheduleRead: (fn: () => void) => void
scheduleWrite: (fn: () => void) => void
/** Framework-agnostic DOM mounting into a declared slot anchor. */
mountSlot: (slot: UIContractSlot, node: HTMLElement) => () => void
/** Restricted non-destructive UI actions only (no start/stop/delete/config write). */
actions: ThemeSDKHostActions
}
const stateListeners = new Set<(snap: UIStateSnapshot) => void>()
export function notifyThemeSDKState(snap: UIStateSnapshot): void {
if (stateListeners.size === 0) return
for (const cb of stateListeners) {
try { cb(snap) } catch {}
}
}
// Shared RAF read/write pipeline.
let readQueue: Array<() => void> = []
let writeQueue: Array<() => void> = []
let rafScheduled = false
function flushFrame() {
rafScheduled = false
const reads = readQueue
const writes = writeQueue
readQueue = []
writeQueue = []
for (const r of reads) { try { r() } catch {} }
for (const w of writes) { try { w() } catch {} }
}
function scheduleRAF() {
if (rafScheduled) return
rafScheduled = true
requestAnimationFrame(flushFrame)
}
export async function mountInteractiveThemeScript(
scriptURL: string,
getState: () => UIStateSnapshot,
actions: ThemeSDKHostActions,
): Promise<() => void> {
if (!scriptURL.startsWith('/plugin-assets/') || scriptURL.includes('..')) {
throw new Error('Refused to load theme script outside /plugin-assets/')
}
let disposed = false
const disposers = new Set<() => void>()
const partSet = new Set<string>(UI_CONTRACT_PARTS)
const slotSet = new Set<string>(UI_CONTRACT_SLOTS)
const addDisposer = (fn: () => void) => {
if (disposed) return
disposers.add(fn)
}
const disposeAll = () => {
if (disposed) return
disposed = true
const list = Array.from(disposers).reverse()
disposers.clear()
for (const fn of list) {
try { fn() } catch {}
}
}
const sdk: ReimsUISDK = {
uiApi: UI_API_VERSION,
onDispose: addDisposer,
feature: (_name, setup) => {
if (disposed) return
const localDisposers: Array<() => void> = []
const localDispose = () => {
while (localDisposers.length > 0) {
try { localDisposers.pop()?.() } catch {}
}
}
addDisposer(localDispose)
try {
setup((fn) => localDisposers.push(fn))
} catch {
// Feature-isolated error: tear down only this feature (§4.2, §5.1).
localDispose()
}
},
getState: () => {
const s = getState()
return { ...s, vms: s.vms.map((v) => ({ ...v })) }
},
subscribeState: (cb) => {
if (disposed) return () => {}
stateListeners.add(cb)
const off = () => {
stateListeners.delete(cb)
disposers.delete(off)
}
addDisposer(off)
return off
},
queryPart: (part) => {
if (disposed || !partSet.has(part)) return null
return document.querySelector<HTMLElement>(`.${part}`)
},
observePart: (part, cb) => {
if (disposed || !partSet.has(part)) return () => {}
const target = document.querySelector<HTMLElement>(`.${part}`)
if (!target) return () => {}
const obs = new MutationObserver(() => {
if (disposed) return
try { cb() } catch {}
})
obs.observe(target, { attributes: true, childList: true, subtree: false })
const off = () => {
obs.disconnect()
disposers.delete(off)
}
addDisposer(off)
return off
},
scheduleRead: (fn) => {
if (disposed) return
readQueue.push(() => { if (!disposed) fn() })
scheduleRAF()
},
scheduleWrite: (fn) => {
if (disposed) return
writeQueue.push(() => { if (!disposed) fn() })
scheduleRAF()
},
mountSlot: (slot, node) => {
if (disposed || !slotSet.has(slot)) return () => {}
const host = document.querySelector<HTMLElement>(`[data-rg-slot="${CSS.escape(slot)}"]`)
if (!host) return () => {}
host.appendChild(node)
const off = () => {
node.remove()
disposers.delete(off)
}
addDisposer(off)
return off
},
actions: {
toggleSidebar: actions.toggleSidebar,
openSettings: actions.openSettings,
focusVMWindow: actions.focusVMWindow,
},
}
// Hide Wails binding globals from `window` before executing any theme script,
// and shadow bridge identifiers inside its closure (§5.1, B6). Note: scripts
// in the main window still run in the same DOM realm, so `ui:script` remains
// a high-trust permission requiring explicit user approval.
hideWailsGlobals()
const resp = await fetch(scriptURL, { credentials: 'same-origin' })
if (!resp.ok) throw new Error(`Failed to fetch theme script (${resp.status})`)
const source = await resp.text()
const runner = new Function('sdk', 'go', 'runtime', 'WailsInvoke', 'wails', `"use strict";\n${source}`)
try {
runner(sdk, undefined, undefined, undefined, undefined)
} catch (err) {
disposeAll()
throw err
}
return disposeAll
}