diablo2-web/src/client/plugin-host/api.ts

444 lines
14 KiB
TypeScript

/**
* Public Plugin API Contract (`src/client/plugin-host/api.ts`).
*
* Architectural Rule 9: This is the SOLE `src/client/` module that `plugins/**` may import.
* It defines the plugin descriptor contract, runtime context, status reporting, fail-fast
* registry validation, and the standalone plugin page bootstrapper (`bootPluginPage`).
*/
import {
getGameLang,
initLangFromBrowser,
onLangChange,
setLang,
type GameLang,
} from '../i18n/lang.ts'
import type { OnlineSession } from '../session/online-session.ts'
import { getGlobalSettingsStore } from '../settings/settings-store.ts'
import {
PLUGIN_CONFIG_STORAGE_KEY,
PluginConfigStore,
} from './plugin-config-store.ts'
export type { GameLang }
export interface LocalizedText {
readonly zh: string
readonly en: string
}
export type PluginSettingSpec =
| {
readonly kind: 'boolean'
readonly key: string
readonly label: LocalizedText
readonly default: boolean
}
| {
readonly kind: 'select'
readonly key: string
readonly label: LocalizedText
readonly default: string
readonly options: readonly {
readonly value: string
readonly label: LocalizedText
}[]
}
export type PluginActionSpec =
| {
readonly kind: 'link'
readonly id: string
readonly label: LocalizedText
readonly href: string
}
| {
readonly kind: 'button'
readonly id: string
readonly label: LocalizedText
run(ctx: PluginContext): void
}
export interface D2WebPlugin {
readonly id: string
readonly name: LocalizedText
readonly description: LocalizedText
readonly defaultEnabled: boolean
readonly settings?: readonly PluginSettingSpec[]
readonly actions?: readonly PluginActionSpec[]
activate(ctx: PluginContext): PluginInstance | Promise<PluginInstance>
}
export interface PluginInstance {
deactivate(): void | Promise<void>
getStatus?(): PluginStatus
}
export interface PluginStatus {
readonly level: 'ok' | 'warn' | 'error'
readonly text: LocalizedText
}
export type PluginSessionView = Pick<
OnlineSession,
'phase' | 'world' | 'loginHost' | 'getSnapshot' | 'onServerEvent' | 'onStateChange'
>
export interface PluginLogger {
info(msg: string, ...args: unknown[]): void
warn(msg: string, ...args: unknown[]): void
error(msg: string, ...args: unknown[]): void
}
export interface PluginContext {
readonly pluginId: string
readonly session: PluginSessionView
readonly settings: {
get(key: string): boolean | string
subscribe(fn: (key: string) => void): () => void
}
readonly toolbar: {
addLink(spec: { id: string; label: LocalizedText; href: string }): () => void
addButton(spec: { id: string; label: LocalizedText; onClick(): void }): () => void
}
readonly lang: {
get(): GameLang
subscribe(fn: (lang: GameLang) => void): () => void
}
readonly log: PluginLogger
notifyStatusChanged(): void
}
export interface PluginPageContext {
readonly pluginId: string
getLang(): GameLang
setLang(lang: GameLang): void
subscribeLang(fn: (lang: GameLang) => void): () => void
isEnabled(): boolean
subscribeEnabled(fn: (enabled: boolean) => void): () => void
getSetting(key: string): boolean | string
setSetting(key: string, value: boolean | string): void
subscribeSettings(fn: (key: string) => void): () => void
destroy(): void
}
const KEBAB_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
export function resolveLocalizedText(text: LocalizedText, lang: GameLang): string {
return lang === 'en' ? text.en : text.zh
}
export function isValidLocalizedText(value: unknown): value is LocalizedText {
if (!value || typeof value !== 'object') return false
const candidate = value as { zh?: unknown; en?: unknown }
return (
typeof candidate.zh === 'string' &&
candidate.zh.trim().length > 0 &&
typeof candidate.en === 'string' &&
candidate.en.trim().length > 0
)
}
/**
* Only relative paths inside the application are permitted for plugin link actions
* and toolbar links. External schemes (`http:`, `https:`, `javascript:`, `data:`),
* protocol-relative URLs (`//`), and root-absolute paths (`/`) are rejected.
*/
export function isRelativePluginHref(href: string): boolean {
if (typeof href !== 'string') return false
const trimmed = href.trim()
if (trimmed.length === 0) return false
if (trimmed.startsWith('/') || trimmed.startsWith('//') || trimmed.startsWith('\\')) {
return false
}
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
return false
}
return true
}
export function isValidPluginSettingValue(
spec: PluginSettingSpec,
value: unknown,
): value is boolean | string {
if (spec.kind === 'boolean') {
return typeof value === 'boolean'
}
if (spec.kind === 'select') {
return (
typeof value === 'string' &&
spec.options.some((opt) => opt.value === value)
)
}
return false
}
export function validatePluginDefinition(plugin: D2WebPlugin): void {
if (!plugin || typeof plugin !== 'object') {
throw new Error('[PluginHost] Invalid plugin definition: expected object')
}
if (typeof plugin.id !== 'string' || !KEBAB_ID_RE.test(plugin.id)) {
throw new Error(
`[PluginHost] Invalid plugin id "${String(plugin.id)}": must be non-empty kebab-case`,
)
}
if (!isValidLocalizedText(plugin.name)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" must provide non-empty localized name (zh & en)`,
)
}
if (!isValidLocalizedText(plugin.description)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" must provide non-empty localized description (zh & en)`,
)
}
if (typeof plugin.defaultEnabled !== 'boolean') {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" defaultEnabled must be a boolean`,
)
}
if (typeof plugin.activate !== 'function') {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" must implement activate(ctx)`,
)
}
if (plugin.settings !== undefined) {
if (!Array.isArray(plugin.settings)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" settings must be an array`,
)
}
const seenKeys = new Set<string>()
for (const spec of plugin.settings) {
if (!spec || typeof spec !== 'object') {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" has an invalid setting descriptor`,
)
}
if (typeof spec.key !== 'string' || spec.key.trim().length === 0) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" has a setting with an empty key`,
)
}
if (seenKeys.has(spec.key)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" has duplicate setting key "${spec.key}"`,
)
}
seenKeys.add(spec.key)
if (!isValidLocalizedText(spec.label)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" setting "${spec.key}" must have non-empty localized label`,
)
}
if (spec.kind === 'boolean') {
if (typeof spec.default !== 'boolean') {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" boolean setting "${spec.key}" must have boolean default`,
)
}
} else if (spec.kind === 'select') {
if (!Array.isArray(spec.options) || spec.options.length === 0) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" select setting "${spec.key}" must have non-empty options`,
)
}
const optionValues = new Set<string>()
for (const opt of spec.options) {
if (!opt || typeof opt.value !== 'string' || opt.value.trim().length === 0) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" select setting "${spec.key}" has an option with empty value`,
)
}
if (optionValues.has(opt.value)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" select setting "${spec.key}" has duplicate option "${opt.value}"`,
)
}
optionValues.add(opt.value)
if (!isValidLocalizedText(opt.label)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" select setting "${spec.key}" option "${opt.value}" must have localized label`,
)
}
}
if (typeof spec.default !== 'string' || !optionValues.has(spec.default)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" select setting "${spec.key}" default "${String(spec.default)}" is not in options`,
)
}
} else {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" setting "${(spec as { key?: string }).key ?? ''}" has unsupported kind`,
)
}
}
}
if (plugin.actions !== undefined) {
if (!Array.isArray(plugin.actions)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" actions must be an array`,
)
}
const seenIds = new Set<string>()
for (const action of plugin.actions) {
if (!action || typeof action !== 'object') {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" has an invalid action descriptor`,
)
}
if (typeof action.id !== 'string' || !KEBAB_ID_RE.test(action.id)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" action id "${String(action.id)}" must be non-empty kebab-case`,
)
}
if (seenIds.has(action.id)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" has duplicate action id "${action.id}"`,
)
}
seenIds.add(action.id)
if (!isValidLocalizedText(action.label)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" action "${action.id}" must have non-empty localized label`,
)
}
if (action.kind === 'link') {
if (!isRelativePluginHref(action.href)) {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" link action "${action.id}" href "${String(action.href)}" must be a relative path`,
)
}
} else if (action.kind === 'button') {
if (typeof action.run !== 'function') {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" button action "${action.id}" must provide a run(ctx) function`,
)
}
} else {
throw new Error(
`[PluginHost] Plugin "${plugin.id}" action "${(action as { id?: string }).id ?? ''}" has unsupported kind`,
)
}
}
}
}
export function validatePluginRegistry(plugins: readonly D2WebPlugin[]): void {
if (!Array.isArray(plugins)) {
throw new Error('[PluginHost] Plugin registry must be an array')
}
const seenIds = new Set<string>()
for (const plugin of plugins) {
validatePluginDefinition(plugin)
if (seenIds.has(plugin.id)) {
throw new Error(`[PluginHost] Duplicate plugin id "${plugin.id}" in registry`)
}
seenIds.add(plugin.id)
}
}
/**
* Bootstrap context for a standalone plugin page (e.g. `/plugins/<id>/index.html`).
* - Resolves language using URL `?lang=` > stored `d2web.settings.v1` > `<html lang>`
* - Synchronizes global language and plugin enabled/settings state across tabs via `storage` events
*/
export function bootPluginPage(plugin: D2WebPlugin): PluginPageContext {
validatePluginDefinition(plugin)
initLangFromBrowser({ preferStoredSetting: true })
const settingsStore = getGlobalSettingsStore()
const currentLang = getGameLang()
if (settingsStore.get().lang !== currentLang) {
settingsStore.set({ lang: currentLang })
}
const configStore = new PluginConfigStore([plugin])
configStore.attachStorageListener()
const enabledListeners = new Set<(enabled: boolean) => void>()
const settingListeners = new Set<(key: string) => void>()
const unsubConfig = configStore.subscribe((change) => {
if (change.pluginId !== null && change.pluginId !== plugin.id) return
if (change.kind === 'enabled' || change.kind === 'reload' || change.kind === 'reset') {
const enabled = configStore.isEnabled(plugin.id)
for (const fn of [...enabledListeners]) {
fn(enabled)
}
}
if (change.kind === 'setting' && change.settingKey) {
for (const fn of [...settingListeners]) {
fn(change.settingKey)
}
} else if (change.kind === 'reload' || change.kind === 'reset') {
for (const spec of plugin.settings ?? []) {
for (const fn of [...settingListeners]) {
fn(spec.key)
}
}
}
})
const onWindowStorage = (ev: StorageEvent): void => {
if (ev.key === 'd2web.settings.v1' || ev.key === null) {
const reloaded = settingsStore.reload()
if (getGameLang() !== reloaded.lang) {
setLang(reloaded.lang)
}
} else if (ev.key === PLUGIN_CONFIG_STORAGE_KEY) {
configStore.reloadFromStorage(true)
}
}
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
window.addEventListener('storage', onWindowStorage)
}
return {
pluginId: plugin.id,
getLang(): GameLang {
return getGameLang()
},
setLang(lang: GameLang): void {
settingsStore.set({ lang })
setLang(lang)
},
subscribeLang(fn: (lang: GameLang) => void): () => void {
return onLangChange(fn)
},
isEnabled(): boolean {
return configStore.isEnabled(plugin.id)
},
subscribeEnabled(fn: (enabled: boolean) => void): () => void {
enabledListeners.add(fn)
return () => {
enabledListeners.delete(fn)
}
},
getSetting(key: string): boolean | string {
return configStore.getSetting(plugin.id, key)
},
setSetting(key: string, value: boolean | string): void {
configStore.setSetting(plugin.id, key, value)
},
subscribeSettings(fn: (key: string) => void): () => void {
settingListeners.add(fn)
return () => {
settingListeners.delete(fn)
}
},
destroy(): void {
unsubConfig()
configStore.detachStorageListener()
if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
window.removeEventListener('storage', onWindowStorage)
}
enabledListeners.clear()
settingListeners.clear()
},
}
}