A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): user-scriptable editor plugins
esengine108b67f6a63f
diff --git a/.gitignore b/.gitignoreindex ed65707cc..3f3c97f71 100644--- a/.gitignore+++ b/.gitignore@@ -125,6 +125,9 @@ docs/REARCH_*.md**/.esengine/play/**/.esengine/sdk/**/.esengine/editor/+# Plugin API typings: written by the editor on project open, always matching the+# running version. A committed copy would go stale against a different editor.+**/.esengine/plugins/.types/# Generated by xcodegen from native/ios/project.ymlnative/ios/*.xcodeproj/diff --git a/desktop/electron/contentPolicy.ts b/desktop/electron/contentPolicy.tsindex 98c4231f1..694b75db7 100644--- a/desktop/electron/contentPolicy.ts+++ b/desktop/electron/contentPolicy.ts@@ -6,6 +6,7 @@* can't disagree. `.meta` sidecars and dot entries are pipeline/plumbing, not* content. Pure (no I/O) → unit-testable.*/+import { PROJECT_PLUGIN_REL } from '../src/plugins/paths';/** Sidecar suffix carrying an asset's uuid/type/importer (see assetDb). */export const META_EXT = '.meta';@@ -20,11 +21,32 @@ export const isContentDir = (name: string): boolean =>export const isContentFile = (name: string): boolean =>!name.startsWith('.') && !name.endsWith(META_EXT);-/** True when any path segment leaves content space (the watcher's noise filter).- * `.meta` files themselves stay watched — an external edit must re-scan. */+/** True when any path segment leaves content space.+ * `.meta` files themselves stay content — an external edit must re-scan. */export function isNonContentPath(rel: string): boolean {return rel.replace(/\\/g, '/').split('/').some((seg) => seg.startsWith('.') || NON_CONTENT_DIRS.has(seg));}++/**+ * Editor-plugin SOURCE, which the watcher must report even though it lives under a+ * dot dir. Plugin sources are not browsable content (they must stay out of the+ * Content Browser and the asset scan), but they are the input to plugin hot reload —+ * two different questions, so two predicates rather than one loosened rule.+ *+ * Dot-prefixed entries INSIDE the plugin dir stay excluded: `.types` is written by+ * the editor itself, and watching it would loop.+ */+export function isPluginSourcePath(rel: string): boolean {+ const p = rel.replace(/\\/g, '/');+ if (!p.startsWith(`${PROJECT_PLUGIN_REL}/`)) return false;+ const rest = p.slice(PROJECT_PLUGIN_REL.length + 1);+ return rest.length > 0 && !rest.startsWith('.');+}++/** What the project watcher reports: content, plus plugin sources. */+export function isWatchedPath(rel: string): boolean {+ return isPluginSourcePath(rel) || !isNonContentPath(rel);+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 96e300b6b..0656d318d 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -39,6 +39,9 @@ import { ensureSdkTypes } from './syncSdkTypes';import { ensureProjectShaderTwins } from './shaderTwins';import { installCrashCapture, logsDir } from './resilience';import { mcpMode, startMcpEndpoint } from './mcpEndpoint';+import {+ discoverPlugins, compilePlugin, isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,+} from './pluginHost';import { checkForUpdate } from './updateCheck';import {listPlatforms, loadProjectPlatform, createProjectPlatform,@@ -928,6 +931,45 @@ ipcMain.handle('recents:list', () => listRecents());ipcMain.handle('recents:add', (_e, root: string, name: string) => addRecent(root, name));ipcMain.handle('recents:remove', (_e, root: string) => removeRecent(root));+// — Editor plugins. Discovery, compilation, and the trust record live in main+// (disk + userData); activation lives in the renderer, which is the realm the+// contributions land in. A renderer plugin runs in the editor's own realm, so+// `load` hands back code + its hash and whether the user approved THAT build —+// main never decides to run it. —+const userData = (): string => app.getPath('userData');++ipcMain.handle('plugins:list', async () => {+ const found = await discoverPlugins(projectRoot, userData());+ return found.map((p) => ({ ...p, disabled: isDisabled(userData(), p.id) }));+});++ipcMain.handle('plugins:load', async (_e, id: string) => {+ const found = await discoverPlugins(projectRoot, userData());+ const plugin = found.find((p) => p.id === id && !p.shadowedBy);+ if (!plugin) return { ok: false, errors: [`plugin "${id}" not found`], warnings: [] };+ const entry = plugin.manifest?.main?.editor;+ if (!entry) return { ok: false, errors: [`plugin "${id}" has no renderer entry`], warnings: [] };+ const built = await compilePlugin(plugin.dir, entry);+ return { ...built, trusted: isTrusted(userData(), id, plugin.manifest!.version, plugin.dir) };+});++// The renderer says only "the user approved this id" — main resolves which version+// and folder that means, so the approval can't be recorded against a stale pair.+ipcMain.handle('plugins:trust', async (_e, id: string) => {+ const found = await discoverPlugins(projectRoot, userData());+ const plugin = found.find((p) => p.id === id && p.manifest);+ if (plugin) trustPlugin(userData(), id, plugin.manifest!.version, plugin.dir);+});+ipcMain.handle('plugins:revokeTrust', (_e, id: string) => revokeTrust(userData(), id));+ipcMain.handle('plugins:setEnabled', (_e, id: string, enabled: boolean) =>+ setPluginEnabled(userData(), id, enabled),+);+ipcMain.handle('plugins:reveal', async (_e, id: string) => {+ const found = await discoverPlugins(projectRoot, userData());+ const dir = found.find((p) => p.id === id)?.dir;+ if (dir) shell.openPath(dir);+});+// New-project templates + creation (launcher New tab).ipcMain.handle('templates:list', () => listTemplates());ipcMain.handle('project:createFromTemplate', (_e, templateDir: string, location: string, name: string) =>diff --git a/desktop/electron/pluginHost.ts b/desktop/electron/pluginHost.tsnew file mode 100644index 000000000..df67f0e6b--- /dev/null+++ b/desktop/electron/pluginHost.ts@@ -0,0 +1,255 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The main-process half of the editor plugin system: find plugins, compile+ * their entry, and remember which ones the user trusted or disabled.+ *+ * Three things the renderer cannot do for itself:+ *+ * 1. DISCOVERY. Plugins live on disk in two scopes — inside the project+ * (`.esengine/plugins/`, versioned with it, shared by the team) and per-user+ * (`<userData>/plugins/`, personal tools across projects). A project plugin+ * shadows a user plugin with the same id, and the shadowed one is REPORTED+ * rather than dropped.+ *+ * 2. COMPILATION. Authors write ESM TypeScript with no build step; esbuild turns+ * the entry into one CJS module through the same single door the project-script+ * bundler uses (esbuildRuntime, which handles the packaged-asar binary path).+ * Output is returned in memory and NOT cached: a small plugin compiles in+ * milliseconds, and a cache here would only buy that back in exchange for the+ * entire stale-artifact bug class — reload has to be exactly right for hot+ * reload to be trustworthy.+ *+ * 3. TRUST. A renderer plugin runs in the editor's own realm, so loading one is a+ * decision only the user can make. Approval is keyed by `<id>@<version>` AND+ * the folder it was approved from: publishing a new version re-asks, and so+ * does a different folder claiming the same id.+ *+ * Deliberately NOT keyed by a hash of the code. That would re-prompt on every+ * save, which is fatal to the loop of actually writing a plugin — and it buys+ * little, since the threat model here is "code I did not write", not "code I+ * just edited". This is the same bargain every extension ecosystem strikes:+ * approval is per identity, and an update rides on it.+ *+ * Pure Node apart from the userData path (injected), so it stays unit-testable.+ */+import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { readdir, readFile } from 'node:fs/promises';+import path from 'node:path';+import { loadEsbuild } from './esbuildRuntime';+import { validateManifest, type PluginManifest } from '../src/plugins/manifest';+import { PROJECT_PLUGIN_REL } from '../src/plugins/paths';++/** Where a project keeps its own plugins (sibling of `.esengine/platforms/`),+ * resolved to this OS's separator from the one shared spelling. */+export const PROJECT_PLUGIN_DIR = path.join(...PROJECT_PLUGIN_REL.split('/'));+/** Per-user plugin folder name, under Electron's userData. */+export const USER_PLUGIN_DIR = 'plugins';++/** Which scope a plugin was found in. Project shadows user on an id collision. */+export type PluginScope = 'project' | 'user';++/** What the renderer needs to list one plugin. Serializable by construction. */+export interface DiscoveredPlugin {+ id: string;+ scope: PluginScope;+ /** Absolute plugin folder — shown in the UI and opened by "Reveal". */+ dir: string;+ /** Present when the manifest parsed and validated. */+ manifest?: PluginManifest;+ /** Present when it did not: the reason, so a broken plugin is named not hidden. */+ error?: string;+ /** Set when a same-id plugin in a higher-priority scope took precedence. */+ shadowedBy?: PluginScope;+}++export interface CompiledPlugin {+ ok: boolean;+ /** CJS module text, loaded by the renderer through an injected `require`. */+ code?: string;+ errors: string[];+ warnings: string[];+}++// The host provides these; a plugin bundling its own copy would mean two Reacts+// (broken hooks) or two SDK instances (two component registries).+const EDITOR_EXTERNALS = ['react', 'react-dom', 'react-dom/client', 'react/jsx-runtime', '@estella/editor-api', 'esengine'];++// =============================================================================+// Discovery+// =============================================================================++async function readPluginDir(dir: string, scope: PluginScope): Promise<DiscoveredPlugin[]> {+ if (!existsSync(dir)) return [];+ let names: string[];+ try {+ names = (await readdir(dir, { withFileTypes: true }))+ // A leading dot is for editor-managed sidecars (e.g. the generated `.types`+ // folder), never a plugin.+ .filter((e) => e.isDirectory() && !e.name.startsWith('.'))+ .map((e) => e.name)+ .sort();+ } catch {+ return [];+ }+ const out: DiscoveredPlugin[] = [];+ for (const name of names) {+ const pluginDir = path.join(dir, name);+ const manifestFile = path.join(pluginDir, 'plugin.json');+ if (!existsSync(manifestFile)) {+ out.push({ id: name, scope, dir: pluginDir, error: 'folder has no plugin.json' });+ continue;+ }+ try {+ const parsed: unknown = JSON.parse(await readFile(manifestFile, 'utf8'));+ const result = validateManifest(parsed);+ if ('error' in result) {+ out.push({ id: name, scope, dir: pluginDir, error: result.error });+ } else {+ out.push({ id: result.manifest.id, scope, dir: pluginDir, manifest: result.manifest });+ }+ } catch (e) {+ out.push({ id: name, scope, dir: pluginDir, error: `plugin.json is not valid JSON (${String(e)})` });+ }+ }+ return out;+}++/**+ * Every plugin visible right now, project scope first. A user plugin whose id a+ * project plugin also claims is listed with `shadowedBy`, so the UI can explain+ * why it isn't running instead of leaving the user wondering.+ */+export async function discoverPlugins(root: string | null, userDataDir: string): Promise<DiscoveredPlugin[]> {+ const project = root ? await readPluginDir(path.join(root, PROJECT_PLUGIN_DIR), 'project') : [];+ const user = await readPluginDir(path.join(userDataDir, USER_PLUGIN_DIR), 'user');+ const claimed = new Set(project.map((p) => p.id));+ return [+ ...project,+ ...user.map((p) => (claimed.has(p.id) ? { ...p, shadowedBy: 'project' as PluginScope } : p)),+ ];+}++// =============================================================================+// Compilation+// =============================================================================++/**+ * Compile a plugin's renderer entry to a single CJS module. CJS (not ESM) because+ * the renderer loads it with an injected `require`, which is how host modules get+ * dependency-injected without a second module graph or an import map — see the+ * loader in src/plugins/loader.ts. Authors never see it: they write ESM TS.+ *+ * Never throws: a plugin that fails to build comes back with its diagnostics.+ */+export async function compilePlugin(dir: string, entryRel: string): Promise<CompiledPlugin> {+ const entry = path.join(dir, entryRel);+ if (!existsSync(entry)) {+ return { ok: false, errors: [`entry not found: ${entryRel}`], warnings: [] };+ }+ try {+ const { build } = await loadEsbuild();+ const result = await build({+ entryPoints: [entry],+ bundle: true,+ format: 'cjs',+ platform: 'browser',+ target: 'es2020',+ external: EDITOR_EXTERNALS,+ jsx: 'automatic',+ write: false,+ sourcemap: 'inline',+ logLevel: 'silent',+ // Resolve bare imports from the plugin's own folder, so a plugin may vendor+ // dependencies in its node_modules and have them bundled in.+ absWorkingDir: dir,+ });+ const code = result.outputFiles?.[0]?.text;+ if (!code) return { ok: false, errors: ['esbuild produced no output'], warnings: [] };+ return {+ ok: true,+ code,+ errors: result.errors.map((e) => e.text),+ warnings: result.warnings.map((w) => w.text),+ };+ } catch (err) {+ const e = err as { errors?: { text: string }[]; warnings?: { text: string }[]; message?: string };+ return {+ ok: false,+ errors: e.errors?.map((x) => x.text) ?? [String(e.message ?? err)],+ warnings: e.warnings?.map((x) => x.text) ?? [],+ };+ }+}++// =============================================================================+// Trust + enablement (per-user, in userData)+// =============================================================================++interface TrustFile {+ /** `<id>@<version>` → the absolute folder it was approved from. */+ trusted: Record<string, string>;+ /** ids the user switched off (independent of trust). */+ disabled: string[];+}++/** Approval identity: a version bump or a different folder re-asks. */+const trustKey = (id: string, version: string): string => `${id}@${version}`;++const EMPTY: TrustFile = { trusted: {}, disabled: [] };++const trustFile = (userDataDir: string): string => path.join(userDataDir, 'estella-plugin-trust.json');++function readTrust(userDataDir: string): TrustFile {+ try {+ const raw: unknown = JSON.parse(readFileSync(trustFile(userDataDir), 'utf8'));+ const f = raw as Partial<TrustFile>;+ return {+ trusted: f.trusted && typeof f.trusted === 'object' ? f.trusted : {},+ disabled: Array.isArray(f.disabled) ? f.disabled : [],+ };+ } catch {+ return { ...EMPTY };+ }+}++function writeTrust(userDataDir: string, next: TrustFile): void {+ try {+ writeFileSync(trustFile(userDataDir), `${JSON.stringify(next, null, 2)}\n`);+ } catch {+ /* read-only profile — trust simply won't persist this session */+ }+}++/** Whether the user approved this plugin id + version, from this folder. */+export function isTrusted(userDataDir: string, id: string, version: string, dir: string): boolean {+ return readTrust(userDataDir).trusted[trustKey(id, version)] === dir;+}++export function trustPlugin(userDataDir: string, id: string, version: string, dir: string): void {+ const f = readTrust(userDataDir);+ f.trusted[trustKey(id, version)] = dir;+ writeTrust(userDataDir, f);+}++/** Withdraw approval for every version of a plugin; it stops loading until re-approved. */+export function revokeTrust(userDataDir: string, id: string): void {+ const f = readTrust(userDataDir);+ for (const key of Object.keys(f.trusted)) {+ if (key.startsWith(`${id}@`)) delete f.trusted[key];+ }+ writeTrust(userDataDir, f);+}++export function isDisabled(userDataDir: string, id: string): boolean {+ return readTrust(userDataDir).disabled.includes(id);+}++export function setPluginEnabled(userDataDir: string, id: string, enabled: boolean): void {+ const f = readTrust(userDataDir);+ const set = new Set(f.disabled);+ if (enabled) set.delete(id);+ else set.add(id);+ f.disabled = [...set].sort();+ writeTrust(userDataDir, f);+}diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 6e2d49c8e..0bf2f057c 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -12,6 +12,7 @@ import type {} from './platformCatalog';import type { PlayRealmResult } from './buildPlayRealm';import type { LatestRelease } from './updateCheck';+import type { DiscoveredPlugin, CompiledPlugin } from './pluginHost';// The privileged bridge the renderer is allowed to touch. Keep this surface small// and explicit — anything the editor needs from the OS or Node goes through here.@@ -200,6 +201,23 @@ const api = {workspace: {save: (ws: WorkspaceState): Promise<void> => ipcRenderer.invoke('workspace:save', ws),},+ // Editor plugins. Main finds + compiles them and owns the trust record; the+ // renderer decides nothing about trust, it only reports what main says.+ plugins: {+ /** Every plugin on disk (project scope first), each with its manifest or the+ * reason it failed to load, plus whether the user switched it off. */+ list: (): Promise<(DiscoveredPlugin & { disabled: boolean })[]> => ipcRenderer.invoke('plugins:list'),+ /** Compile a plugin's renderer entry and report whether the user approved this+ * id+version from this folder. Compiling never runs the plugin. */+ load: (id: string): Promise<CompiledPlugin & { trusted: boolean }> => ipcRenderer.invoke('plugins:load', id),+ /** Record the user's approval; main resolves the version + folder it applies to. */+ trust: (id: string): Promise<void> => ipcRenderer.invoke('plugins:trust', id),+ revokeTrust: (id: string): Promise<void> => ipcRenderer.invoke('plugins:revokeTrust', id),+ setEnabled: (id: string, enabled: boolean): Promise<void> =>+ ipcRenderer.invoke('plugins:setEnabled', id, enabled),+ /** Reveal the plugin's folder in Finder / Explorer. */+ reveal: (id: string): Promise<void> => ipcRenderer.invoke('plugins:reveal', id),+ },// Recent projects (launcher), persisted in userData.recents: {list: (): Promise<RecentEntry[]> => ipcRenderer.invoke('recents:list'),diff --git a/desktop/electron/projectWatcher.ts b/desktop/electron/projectWatcher.tsindex 93ef7587d..bbd64b1e8 100644--- a/desktop/electron/projectWatcher.ts+++ b/desktop/electron/projectWatcher.ts@@ -16,13 +16,15 @@*/import { watch, type FSWatcher } from 'node:fs';import type { WebContents } from 'electron';-import { isNonContentPath } from './contentPolicy';+import { isWatchedPath } from './contentPolicy';// Our own cache writes (assets.json / schemas.json / scripts.mjs under// `.esengine`) MUST be ignored — refreshing on them would loop; contentPolicy's-// dot rule covers that plus the usual heavy noise dirs.-/** True if a project-relative path is watcher noise (outside content space). */-export const isIgnoredPath = isNonContentPath;+// dot rule covers that plus the usual heavy noise dirs. Editor-plugin sources are+// the one dot-dir exception (they drive plugin hot reload), which is why the+// predicate is "watched" rather than plain "is content".+/** True if a project-relative path is watcher noise (nothing subscribes to it). */+export const isIgnoredPath = (rel: string): boolean => !isWatchedPath(rel);const DEBOUNCE_MS = 180;diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 1ef9e5c59..ec4c5caa9 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -353,6 +353,14 @@ commands.register({isChecked: () => dockApi.isMaximized(),run: () => dockApi.toggleMaximizePanel('viewport'),});+commands.register({+ id: 'plugins.open',+ label: t('plug.panelTitle'),+ category: t('cat.view'),+ // The Plugins panel isn't ensured in the layout (most sessions have none), so a+ // command is how it's reached — palette, Window menu, and rebindable like any other.+ run: () => dockApi.openPanel('plugins'),+});commands.register({id: 'view.resetLayout',label: t('menu.resetLayout'),diff --git a/desktop/src/i18n/messages/index.ts b/desktop/src/i18n/messages/index.tsindex 69c47741d..1f1fbabed 100644--- a/desktop/src/i18n/messages/index.ts+++ b/desktop/src/i18n/messages/index.ts@@ -39,6 +39,7 @@ import { projectMessages } from './project';import { controllerMessages } from './controllers';import { animatorMessages } from './animator';import { eventMessages } from './events';+import { pluginMessages } from './plugins';/** Every per-area module, for the uniqueness guard in i18n.test.ts. */export const messageModules = {@@ -63,6 +64,7 @@ export const messageModules = {controllers: controllerMessages,animator: animatorMessages,events: eventMessages,+ plugins: pluginMessages,} as const;export const editorMessages = {@@ -87,4 +89,5 @@ export const editorMessages = {...controllerMessages,...animatorMessages,...eventMessages,+ ...pluginMessages,} as const;diff --git a/desktop/src/i18n/messages/plugins.ts b/desktop/src/i18n/messages/plugins.tsnew file mode 100644index 000000000..76fe9b1d6--- /dev/null+++ b/desktop/src/i18n/messages/plugins.ts@@ -0,0 +1,65 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file plugins.ts — strings for the Plugins panel (PluginsPanel.tsx) and the+ * trust prompt. Note these describe the editor's own plugin chrome; a+ * plugin's OWN strings come from its manifest / contributions, which carry+ * per-locale text of their own (plugins can't use this catalog).+ */+import { defineMessages } from './types';++export const pluginMessages = defineMessages({+ 'plug.panelTitle': { en: 'Plugins', zh: '插件' },+ 'plug.emptyTitle': { en: 'No plugins', zh: '没有插件' },+ 'plug.emptyHint': {+ en: 'Drop a plugin folder into .esengine/plugins/ in this project, then Refresh.',+ zh: '把插件文件夹放进本项目的 .esengine/plugins/,然后点刷新。',+ },+ 'plug.noProjectHint': { en: 'Open a project to see its plugins.', zh: '打开一个项目以查看它的插件。' },+ 'plug.refresh': { en: 'Refresh', zh: '刷新' },+ 'plug.reload': { en: 'Reload', zh: '重新加载' },+ 'plug.reloadTip': { en: 'Recompile from source and re-activate', zh: '从源码重新编译并激活' },+ 'plug.reveal': { en: 'Reveal', zh: '打开目录' },+ 'plug.enable': { en: 'Enable', zh: '启用' },+ 'plug.disable': { en: 'Disable', zh: '停用' },+ 'plug.trust': { en: 'Trust and load', zh: '信任并加载' },+ 'plug.revokeTrust': { en: 'Withdraw trust', zh: '撤销信任' },++ // Lifecycle phases (the status chip on each row).+ 'plug.phase.discovered': { en: 'Found', zh: '已发现' },+ 'plug.phase.compiling': { en: 'Compiling', zh: '编译中' },+ 'plug.phase.needsTrust': { en: 'Needs trust', zh: '待信任' },+ 'plug.phase.activating': { en: 'Activating', zh: '激活中' },+ 'plug.phase.active': { en: 'Active', zh: '运行中' },+ 'plug.phase.failed': { en: 'Failed', zh: '失败' },+ 'plug.phase.disabled': { en: 'Disabled', zh: '已停用' },+ 'plug.phase.incompatible': { en: 'Incompatible', zh: '版本不兼容' },+ 'plug.phase.shadowed': { en: 'Shadowed', zh: '被遮蔽' },++ 'plug.scope.project': { en: 'project', zh: '项目' },+ 'plug.scope.user': { en: 'user', zh: '用户' },++ // The trust gate. Deliberately plain about what loading a plugin means: it runs+ // in the editor's own realm, which no wording should soften.+ 'plug.trustTitle': { en: 'Trust this plugin?', zh: '信任这个插件?' },+ 'plug.trustBody': {+ en: 'A plugin runs with the same access the editor has: your project files and anything the editor can reach. Load it only if you trust where it came from.',+ zh: '插件与编辑器拥有同等权限:你的项目文件,以及编辑器能触及的一切。只在你信任其来源时加载。',+ },+ 'plug.trustRechecked': {+ en: 'Approval covers this version from this folder. A new version, or another folder claiming the same id, asks again.',+ zh: '批准仅针对该版本与该目录。新版本、或另一个目录声称同一 id,都会重新询问。',+ },+ 'plug.capabilities': { en: 'Declares', zh: '声明能力' },+ 'plug.noCapabilities': { en: 'no extra capabilities', zh: '无额外能力' },+ 'plug.cap.fsProject': { en: 'read/write project files', zh: '读写项目文件' },+ 'plug.cap.net': { en: 'network access', zh: '网络访问' },+ 'plug.cap.shell': { en: 'run OS commands', zh: '执行系统命令' },+ 'plug.cap.process': { en: 'spawn processes', zh: '启动子进程' },+ 'plug.capsAdvisory': {+ en: 'Declared capabilities describe intent — they are not a sandbox.',+ zh: '声明的能力表达意图 —— 它不是沙箱。',+ },+ 'plug.errorCount': { en: '{n} error(s) this session', zh: '本次会话 {n} 个错误' },+ 'plug.contributes': { en: 'Contributes', zh: '贡献' },+});diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsxindex 3996e4806..1d210834b 100644--- a/desktop/src/layout/DockLayout.tsx+++ b/desktop/src/layout/DockLayout.tsx@@ -22,7 +22,7 @@ import {panelDef, panelDefs, panelComponent, isPanelClosable, ensuredPanels,panelRegistry, panelTitle,} from '@/layout/panels';-import { PANEL_RENDERERS } from '@/layout/panelComponents';+import { PANEL_RENDERERS, MountedPanel, type PanelRenderer } from '@/layout/panelComponents';import { t } from '@/i18n';// Each dock panel is a thin wrapper so dockview owns mount/unmount. The@@ -47,7 +47,10 @@ function buildComponents(): Record<string, FC<IDockviewPanelProps>> {const out: Record<string, FC<IDockviewPanelProps>> = {};for (const def of panelDefs()) {const key = panelComponent(def);- const render = PANEL_RENDERERS[key];+ const { mount } = def;+ const render: PanelRenderer | undefined = mount+ ? () => <MountedPanel mount={mount} />+ : PANEL_RENDERERS[key];if (!render) continue; // registered with no renderer — nothing to mountout[key] = (p) =>panel(p.api, render({ panelId: p.api.id, params: p.params as Record<string, unknown> | undefined }), def.noPerf);diff --git a/desktop/src/layout/dockApi.ts b/desktop/src/layout/dockApi.tsindex d5a3c2e7d..0c15293f3 100644--- a/desktop/src/layout/dockApi.ts+++ b/desktop/src/layout/dockApi.ts@@ -207,6 +207,16 @@ export const dockApi = {}},+ /** Close a panel if it's open (a retracted contribution must not leave its tab). */+ closePanel(id: string) {+ api?.getPanel(id)?.api.close();+ },++ /** Whether a panel currently exists in the dock. */+ isPanelOpen(id: string): boolean {+ return !!api?.getPanel(id);+ },+/** Open (or reveal) the Game view as a tab beside the Viewport — used on Play. */openGame() {this.openPanel('game');diff --git a/desktop/src/layout/menus.ts b/desktop/src/layout/menus.tsindex 6f561a87e..6e473222f 100644--- a/desktop/src/layout/menus.ts+++ b/desktop/src/layout/menus.ts@@ -120,6 +120,7 @@ const BUILTIN_ITEMS: MenuContribution[] = [// Resets only the dock layout, rebuilt in place (keeps scene/engine/undo), and// guarded so a wedged dirty asset-editor tab can't vanish unwarned.cmd('window', 'layout', 'view.resetLayout'),+ cmd('window', 'layout', 'plugins.open'),{// The same guarded command as File ▸ Close Project, worded for where it leads —// never a second exit path that could skip the unsaved-changes prompt.diff --git a/desktop/src/layout/panelComponents.tsx b/desktop/src/layout/panelComponents.tsxindex f647bb9b5..3b94476c6 100644--- a/desktop/src/layout/panelComponents.tsx+++ b/desktop/src/layout/panelComponents.tsx@@ -7,8 +7,12 @@* pull in the entire panel tree (and cycle back through the command* registry), while most consumers only need a panel's title or dock rules —* the same separation assetTypes/assetOpen use.+ *+ * A CONTRIBUTED panel supplies `mount(host)` on its def instead of a renderer here,+ * and {@link MountedPanel} adapts it — so the dock frames, profiles, and error-traps+ * built-in and contributed panels identically.*/-import type { ReactNode } from 'react';+import { useEffect, useRef, type ReactNode } from 'react';import { Outliner } from '@/panels/Outliner';import { Viewport } from '@/panels/Viewport';import { Details } from '@/panels/Details';@@ -27,6 +31,7 @@ import { StateMachineEditor } from '@/panels/StateMachineEditor';import { AnimatorEditor } from '@/panels/AnimatorEditor';import { BtTreeEditor } from '@/panels/BtTreeEditor';import { ProfilerPanel } from '@/panels/ProfilerPanel';+import { PluginsPanel } from '@/panels/PluginsPanel';/** What a panel renderer is handed: its live panel id and dockview params. */export interface PanelRenderContext {@@ -36,6 +41,27 @@ export interface PanelRenderContext {export type PanelRenderer = (ctx: PanelRenderContext) => ReactNode;+/**+ * Adapts a contributed panel's imperative `mount(host)`: the plugin owns the DOM+ * inside, the dock owns the frame around it. The teardown runs on unmount, so+ * closing the tab — or unloading the plugin, which retracts the panel — disposes+ * whatever the plugin built.+ */+export function MountedPanel({ mount }: { mount: (host: HTMLElement) => () => void }) {+ const ref = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const host = ref.current;+ if (!host) return;+ const teardown = mount(host);+ return () => {+ teardown?.();+ // The plugin may have left nodes behind; the frame must come back clean.+ host.replaceChildren();+ };+ }, [mount]);+ return <div className="plugin-panel" ref={ref} />;+}+/** Renderer per dockview component key. Keys match `panelComponent(def)`. */export const PANEL_RENDERERS: Record<string, PanelRenderer> = {outliner: () => <Outliner />,@@ -55,6 +81,7 @@ export const PANEL_RENDERERS: Record<string, PanelRenderer> = {animatorcontroller: () => <AnimatorEditor />,behaviortree: () => <BtTreeEditor />,profiler: () => <ProfilerPanel />,+ plugins: () => <PluginsPanel />,game: () => <GamePanel />,gameClient: ({ params }) => <GameClientPanel realmId={Number(params?.realmId ?? 0)} />,};diff --git a/desktop/src/layout/panels.ts b/desktop/src/layout/panels.tsindex 12c398189..8bfba89f7 100644--- a/desktop/src/layout/panels.ts+++ b/desktop/src/layout/panels.ts@@ -62,6 +62,13 @@ export interface PanelDef {poppable?: boolean;/** Skip the Perf wrapper (the profiler must not profile its own render). */noPerf?: boolean;+ /**+ * A CONTRIBUTED panel's contents: build into `host`, return a teardown. Built-in+ * panels omit this and are rendered by the component map instead. Plain DOM+ * rather than a React element so a plugin isn't forced into our render tree —+ * it may still use the host's React, which the loader injects.+ */+ mount?(host: HTMLElement): () => void;/*** Set for a MULTI-INSTANCE panel: `id` is then only a component key, and its live* panels are `${instanceIdPrefix}<n>`. Such a panel has no static title/layout@@ -89,6 +96,9 @@ const BOTTOM: PanelDef[] = [{ id: 'sequencer', title: () => t('layout.panel.sequencer'), placement: 'bottom', refs: ['content', 'log'], ensure: true },{ id: 'profiler', title: () => t('layout.panel.profiler'), placement: 'bottom', refs: ['log', 'content'], ensure: true, noPerf: true },{ id: 'audiomixer', title: () => t('mix.panelTitle'), placement: 'bottom', refs: ['log', 'content'], ensure: true },+ // Opened on demand rather than ensured: most sessions have no plugins, and a+ // permanent tab for an empty list is noise.+ { id: 'plugins', title: () => t('plug.panelTitle'), placement: 'bottom', refs: ['log', 'content'] },];// Full editing canvases — opened on demand as center tabs beside the Viewport.diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 1d24d5b19..fffb9bead 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -37,6 +37,7 @@ import './theme/chrome.css';import './theme/menus.css';import './theme/settings.css';import './theme/launcher.css';+import './theme/plugins.css';import { App } from './App';import { ProjectStore } from './project/ProjectStore';import { useEditorStore } from './store/editorStore';@@ -59,6 +60,7 @@ import { ViewportController } from './engine/ViewportController';import { PerfMonitor } from './engine/PerfMonitor';import { LogStore } from './store/LogStore';import { initFsWatch } from './project/fsWatch';+import { initPlugins } from './plugins/init';import { ASSET_OPEN } from './project/assetOpen';import { assetTypeOf } from './project/assetTypes';import { initBackgroundThrottle } from './engine/backgroundThrottle';@@ -77,6 +79,8 @@ applySettings();initFsWatch();initBackgroundThrottle();+// Load the open project's editor plugins (and unload them when it closes).+initPlugins();// Sync the FX-preview default into the engine flag before anything boots (the// flag is module-scoped; emitters auto-play lazily once a scene loads), and@@ -221,6 +225,9 @@ if (new URLSearchParams(location.search).has('automation')) {ASSET_OPEN[assetTypeOf(name)]?.(path, name);},reveal: (id: string) => dockApi.revealAndExpand(id),+ /** Open a registered panel by id, docking it where its def says (reveal only+ * fronts an ALREADY-docked panel, so on-demand panels need this door). */+ openPanel: (id: string) => dockApi.openPanel(id),/** Resize a docked panel (shot tests: reproduce narrow-dock layouts). */setPanelSize: (id: string, size: { width?: number; height?: number }) => dockApi.setPanelSize(id, size),/** The Output Log's captured entries (editor + SDK + wasm + play realm),diff --git a/desktop/src/panels/PluginsPanel.tsx b/desktop/src/panels/PluginsPanel.tsxnew file mode 100644index 000000000..59519779e--- /dev/null+++ b/desktop/src/panels/PluginsPanel.tsx@@ -0,0 +1,174 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file PluginsPanel — what's installed, what's running, and what went wrong.+ *+ * Every plugin the editor found appears here, INCLUDING the broken ones: a plugin+ * whose manifest failed to parse, whose build failed, or whose id a project plugin+ * shadowed is listed with the reason. Silently dropping a folder the user wrote is+ * the one behaviour this panel must never have.+ *+ * It is also where the trust gate lives. A renderer plugin runs in the editor's own+ * realm, so nothing loads until the user has approved it — the row states that+ * plainly rather than dressing it up as a formality.+ */+import { useEffect, useSyncExternalStore } from 'react';+import { AlertTriangle, FolderOpen, Plug, Power, RefreshCw, RotateCw, ShieldCheck, ShieldX } from 'lucide-react';+import { EmptyState } from '@/components/EmptyState';+import { PluginHost, type PluginPhase, type PluginRecord } from '@/plugins/PluginHost';+import { ProjectStore } from '@/project/ProjectStore';+import { t, type MsgKey } from '@/i18n';++const PHASE_LABEL: Record<PluginPhase, MsgKey> = {+ discovered: 'plug.phase.discovered',+ compiling: 'plug.phase.compiling',+ 'needs-trust': 'plug.phase.needsTrust',+ activating: 'plug.phase.activating',+ active: 'plug.phase.active',+ failed: 'plug.phase.failed',+ disabled: 'plug.phase.disabled',+ incompatible: 'plug.phase.incompatible',+ shadowed: 'plug.phase.shadowed',+};++const CAPABILITY_LABEL: Record<string, MsgKey> = {+ 'fs:project': 'plug.cap.fsProject',+ net: 'plug.cap.net',+ shell: 'plug.cap.shell',+ process: 'plug.cap.process',+};++function PhaseChip({ phase }: { phase: PluginPhase }) {+ return <span className={`plug-chip is-${phase}`}>{t(PHASE_LABEL[phase])}</span>;+}++/** The trust gate: what loading means, what the plugin declared, and one decision. */+function TrustGate({ record }: { record: PluginRecord }) {+ return (+ <div className="plug-trust">+ <div className="plug-trust__title">+ <ShieldCheck size={14} strokeWidth={2} />+ {t('plug.trustTitle')}+ </div>+ <p className="plug-trust__body">{t('plug.trustBody')}</p>+ <div className="plug-trust__caps">+ <span className="plug-trust__capsLabel">{t('plug.capabilities')}:</span>+ {record.capabilities.length === 0 ? (+ <span className="plug-muted">{t('plug.noCapabilities')}</span>+ ) : (+ record.capabilities.map((c) => (+ <span key={c} className="plug-cap">+ {CAPABILITY_LABEL[c] ? t(CAPABILITY_LABEL[c]) : c}+ </span>+ ))+ )}+ </div>+ <p className="plug-muted">{t('plug.capsAdvisory')}</p>+ <p className="plug-muted">{t('plug.trustRechecked')}</p>+ <button type="button" className="btn-soft is-primary" onClick={() => void PluginHost.trust(record.id)}>+ {t('plug.trust')}+ </button>+ </div>+ );+}++function PluginRow({ record }: { record: PluginRecord }) {+ const canToggle = record.phase !== 'shadowed';+ const isDisabled = record.phase === 'disabled';+ return (+ <div className="plug-row">+ <div className="plug-row__head">+ <span className="plug-row__name">{record.name}</span>+ {record.version && <span className="plug-row__version">{record.version}</span>}+ <span className="plug-row__scope">{t(record.scope === 'project' ? 'plug.scope.project' : 'plug.scope.user')}</span>+ <span className="plug-row__spacer" />+ <PhaseChip phase={record.phase} />+ </div>+ {record.description && <div className="plug-row__desc">{record.description}</div>}+ {record.detail && (+ <div className="plug-row__detail">+ <AlertTriangle size={12} strokeWidth={2} />+ <span>{record.detail}</span>+ </div>+ )}+ {record.warnings.map((w) => (+ <div key={w} className="plug-row__detail is-warn">+ <AlertTriangle size={12} strokeWidth={2} />+ <span>{w}</span>+ </div>+ ))}+ {record.errorCount > 0 && (+ <div className="plug-row__detail">{t('plug.errorCount', { n: record.errorCount })}</div>+ )}+ {record.phase === 'needs-trust' && <TrustGate record={record} />}+ <div className="plug-row__actions">+ <button type="button" className="btn-soft" title={t('plug.reloadTip')} onClick={() => void PluginHost.reload(record.id)}>+ <RotateCw size={12} strokeWidth={2} />+ {t('plug.reload')}+ </button>+ {canToggle && (+ <button+ type="button"+ className="btn-soft"+ onClick={() => void (isDisabled ? PluginHost.enable(record.id) : PluginHost.disable(record.id))}+ >+ <Power size={12} strokeWidth={2} />+ {t(isDisabled ? 'plug.enable' : 'plug.disable')}+ </button>+ )}+ {record.phase === 'active' && (+ <button type="button" className="btn-soft" onClick={() => void PluginHost.revokeTrust(record.id)}>+ <ShieldX size={12} strokeWidth={2} />+ {t('plug.revokeTrust')}+ </button>+ )}+ <button type="button" className="btn-soft" onClick={() => void window.estella.plugins.reveal(record.id)}>+ <FolderOpen size={12} strokeWidth={2} />+ {t('plug.reveal')}+ </button>+ </div>+ </div>+ );+}++export function PluginsPanel() {+ const records = useSyncExternalStore(PluginHost.subscribe, PluginHost.getSnapshot);+ const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);++ // The panel may be opened before anything scanned (a fresh layout), so make+ // opening it a scan — the list is never mysteriously empty.+ useEffect(() => {+ void PluginHost.refresh();+ }, []);++ if (records.length === 0) {+ return (+ <EmptyState+ icon={Plug}+ title={t('plug.emptyTitle')}+ hint={project ? t('plug.emptyHint') : t('plug.noProjectHint')}+ >+ <button type="button" className="btn-soft" onClick={() => void PluginHost.refresh()}>+ <RefreshCw size={12} strokeWidth={2} />+ {t('plug.refresh')}+ </button>+ </EmptyState>+ );+ }++ return (+ <div className="plug-panel">+ <div className="plug-toolbar">+ <button type="button" className="btn-soft" onClick={() => void PluginHost.refresh()}>+ <RefreshCw size={12} strokeWidth={2} />+ {t('plug.refresh')}+ </button>+ </div>+ <div className="plug-list">+ {records.map((r) => (+ <PluginRow key={r.id} record={r} />+ ))}+ </div>+ </div>+ );+}diff --git a/desktop/src/plugins/PluginHost.ts b/desktop/src/plugins/PluginHost.tsnew file mode 100644index 000000000..d82607d7f--- /dev/null+++ b/desktop/src/plugins/PluginHost.ts@@ -0,0 +1,368 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file PluginHost.ts+ * @brief The renderer-side plugin lifecycle: discover → compile → trust-gate →+ * activate → (reload | deactivate). Holds the reactive record list the+ * Plugins panel renders, and owns the two policies that keep a plugin from+ * taking the editor down with it.+ *+ * POLICY 1 — attribution. A plugin's contributions all carry `plugin:<id>` as+ * owner, so unloading is one `disposeOwner` per registry plus the context's own+ * disposables. That is what makes hot reload trustworthy: nothing survives a+ * reload except what the plugin re-registers.+ *+ * POLICY 2 — quarantine. Every plugin callback runs inside {@link guard}: a throw+ * is logged with its plugin's name, counted, and swallowed with a safe fallback so+ * the editor surface that called it (a menu, an enablement check, a panel mount)+ * keeps working. Past a threshold the plugin is disabled rather than left to throw+ * on every render — the same posture ErrorBoundary/resilience.ts take.+ *+ * Trust is NOT decided here: main hands back whether the user approved this plugin+ * (id + version, from this folder), and an unapproved one stops at `needs-trust`+ * until they say so.+ */+import { commands } from '@/commands/registry';+import { panelRegistry } from '@/layout/panels';+import { menuRegistry, menuItemRegistry } from '@/layout/menus';+import { settingsRegistry } from '@/settings/registry';+import { dockApi } from '@/layout/dockApi';+import { editorModeRegistry } from '@/mode/editorModes';+import { entitySourceRegistry } from '@/engine/entitySources';+import { LogStore } from '@/store/LogStore';+import { Toasts } from '@/store/Toasts';+import { PerfMonitor } from '@/engine/PerfMonitor';+import { editorLocale } from '@/i18n';+// The editor's own version, the same source the status bar shows — what a+// plugin's `engines.editor` range is checked against.+import { version as EDITOR_VERSION } from '../../package.json';+import type { Owner } from '@/contrib/ContributionRegistry';+import { resolveLocalized, satisfiesEditorRange, type PluginManifest } from './manifest';+import { evaluatePlugin } from './loader';+import { buildPluginContext, type BuiltContext } from './context';+import type { EditorPlugin } from './types';++/** Where a plugin sits in its lifecycle — what the Plugins panel shows. */+export type PluginPhase =+ | 'discovered'+ | 'compiling'+ | 'needs-trust'+ | 'activating'+ | 'active'+ | 'failed'+ | 'disabled'+ | 'incompatible'+ | 'shadowed';++export interface PluginRecord {+ id: string;+ /** Display name, already localized. */+ name: string;+ description: string;+ version: string;+ scope: 'project' | 'user';+ dir: string;+ phase: PluginPhase;+ /** Why it's failed / incompatible / shadowed. */+ detail?: string;+ /** Declared capabilities, shown at the trust prompt. */+ capabilities: string[];+ /** Non-fatal build diagnostics. */+ warnings: string[];+ /** Throws attributed to this plugin this session. */+ errorCount: number;+}++/** Throws tolerated before a plugin is disabled for the session. */+const QUARANTINE_THRESHOLD = 5;++const ownerOf = (id: string): Owner => `plugin:${id}`;++// Every registry a plugin can contribute to. Unloading walks this list, so adding+// a contribution kind means adding it HERE and nowhere else in the teardown path.+const CONTRIBUTION_REGISTRIES = [+ { disposeOwner: (o: Owner) => commands.disposeOwner(o) },+ panelRegistry,+ menuRegistry,+ menuItemRegistry,+ { disposeOwner: (o: Owner) => settingsRegistry.disposeOwner(o) },+ editorModeRegistry,+ entitySourceRegistry,+];++interface LoadedPlugin {+ plugin: EditorPlugin;+ context: BuiltContext;+}++class PluginHostImpl {+ private records = new Map<string, PluginRecord>();+ private loaded = new Map<string, LoadedPlugin>();+ private readonly listeners = new Set<() => void>();+ private snapshot: PluginRecord[] = [];++ // — Reactive surface for the Plugins panel —++ subscribe = (fn: () => void): (() => void) => {+ this.listeners.add(fn);+ return () => this.listeners.delete(fn);+ };++ getSnapshot = (): PluginRecord[] => this.snapshot;++ private changed(): void {+ this.snapshot = [...this.records.values()];+ for (const fn of this.listeners) fn();+ }++ private set(id: string, patch: Partial<PluginRecord>): void {+ const prev = this.records.get(id);+ if (prev) this.records.set(id, { ...prev, ...patch });+ this.changed();+ }++ /**+ * Wrap a plugin callback. Returns `fallback` if it throws, so the caller — a+ * menu building its rows, a panel mounting — is never broken by a plugin bug.+ * Timed through PerfMonitor so a slow plugin shows up in the profiler beside the+ * editor's own work, under `plugin.<id>.<what>`.+ */+ private guard<T>(id: string, what: string, fn: () => T, fallback: T): T {+ try {+ return PerfMonitor.measure(`plugin.${id}.${what}`, fn);+ } catch (e) {+ this.recordError(id, what, e);+ return fallback;+ }+ }++ private recordError(id: string, what: string, e: unknown): void {+ const record = this.records.get(id);+ const count = (record?.errorCount ?? 0) + 1;+ LogStore.push('error', `plugin:${id}`, `${what} failed: ${e instanceof Error ? e.message : String(e)}`);+ if (e instanceof Error && e.stack) LogStore.push('error', `plugin:${id}`, e.stack);+ this.set(id, { errorCount: count });+ if (count >= QUARANTINE_THRESHOLD && record?.phase === 'active') {+ Toasts.push(`Plugin "${record.name}" kept failing and was disabled.`, 'error');+ void this.disable(id, `disabled after ${count} errors this session`);+ }+ }++ // — Discovery + activation —++ /**+ * Re-read the plugin folders and bring the set in line: newly present plugins+ * load, ones that vanished unload, and ones already running are left alone so+ * this is safe to call repeatedly (project open, the panel's Refresh).+ *+ * `forceDirs` names plugin FOLDERS whose source changed on disk — those reload+ * even though they're active. Folders, not ids, because the watcher reports+ * paths and a folder name need not match the id inside its manifest.+ */+ async refresh(opts?: { forceDirs?: readonly string[] }): Promise<void> {+ const found = await window.estella.plugins.list();+ const seen = new Set<string>();+ const force = new Set(opts?.forceDirs ?? []);+ const dirName = (dir: string): string => dir.replace(/[/\\]+$/, '').split(/[/\\]/).pop() ?? '';++ for (const p of found) {+ seen.add(p.id);+ const manifest = p.manifest;+ const name = manifest ? resolveLocalized(manifest.name, editorLocale) : p.id;+ const base: PluginRecord = {+ id: p.id,+ name,+ description: manifest ? resolveLocalized(manifest.description, editorLocale) : '',+ version: manifest?.version ?? '',+ scope: p.scope,+ dir: p.dir,+ phase: 'discovered',+ capabilities: manifest?.capabilities ?? [],+ warnings: [],+ errorCount: this.records.get(p.id)?.errorCount ?? 0,+ };++ if (p.error) {+ this.records.set(p.id, { ...base, phase: 'failed', detail: p.error });+ continue;+ }+ if (p.shadowedBy) {+ this.records.set(p.id, {+ ...base,+ phase: 'shadowed',+ detail: `a ${p.shadowedBy}-scoped plugin claims the same id`,+ });+ continue;+ }+ if (p.disabled) {+ this.records.set(p.id, { ...base, phase: 'disabled' });+ continue;+ }+ const range = manifest?.engines?.editor;+ if (range) {+ const compat = satisfiesEditorRange(EDITOR_VERSION, range);+ if (!compat.ok) {+ this.records.set(p.id, { ...base, phase: 'incompatible', detail: compat.reason });+ continue;+ }+ }+ const changed = force.has(dirName(p.dir));+ // Already running and unchanged — leave it alone (refresh is idempotent).+ if (!changed && this.loaded.has(p.id) && this.records.get(p.id)?.phase === 'active') continue;+ // Changed on disk: retract the old build's contributions before the new one+ // registers, or both would be live at once.+ let reopen: string[] = [];+ if (changed) {+ reopen = this.openPanelIds(ownerOf(p.id));+ await this.unload(p.id);+ }++ this.records.set(p.id, base);+ await this.activate(p.id, manifest!);+ this.restorePanels(reopen);+ }++ // Plugins whose folder went away must not keep their contributions.+ for (const id of [...this.records.keys()]) {+ if (seen.has(id)) continue;+ await this.unload(id);+ this.records.delete(id);+ }+ this.changed();+ }++ private async activate(id: string, manifest: PluginManifest): Promise<void> {+ this.set(id, { phase: 'compiling' });+ const built = await window.estella.plugins.load(id);+ if (!built.ok || !built.code) {+ this.set(id, { phase: 'failed', detail: built.errors.join('; ') || 'compilation failed' });+ return;+ }+ this.set(id, { warnings: built.warnings });+ if (!built.trusted) {+ // Stop here. A renderer plugin runs in the editor's own realm, so nothing+ // runs until the user has approved this exact build.+ this.set(id, { phase: 'needs-trust' });+ return;+ }++ this.set(id, { phase: 'activating' });+ const owner = ownerOf(id);+ const record = this.records.get(id)!;+ let context: BuiltContext | undefined;+ try {+ const plugin = evaluatePlugin(id, built.code);+ context = buildPluginContext(+ manifest,+ record.dir,+ owner,+ <T>(what: string, fn: () => T, fallback: T) => this.guard(id, what, fn, fallback),+ );+ this.loaded.set(id, { plugin, context });+ await plugin.activate(context.ctx);+ this.set(id, { phase: 'active', detail: undefined });+ LogStore.push('info', `plugin:${id}`, `activated (${record.version})`);+ } catch (e) {+ // A plugin that throws mid-activate may have registered some of its+ // contributions already — retract them, or it leaves a half-loaded surface.+ this.disposeContributions(owner, () => context?.dispose());+ this.loaded.delete(id);+ const message = e instanceof Error ? e.message : String(e);+ LogStore.push('error', `plugin:${id}`, `activation failed: ${message}`);+ this.set(id, { phase: 'failed', detail: message });+ }+ }++ /**+ * Retract every contribution of one owner and close the panel TABS it opened.+ *+ * Order matters: the tab ids have to be read BEFORE anything retracts the panel+ * registrations, because that's the only record of which tabs belonged to this+ * plugin. Closing after the registry is emptied would silently leave a stale tab+ * mounted, still rendering the previous build.+ */+ private disposeContributions(owner: Owner, disposeContext?: () => void): void {+ const panelIds = panelRegistry.byOwner(owner).map((d) => d.id);+ disposeContext?.();+ for (const registry of CONTRIBUTION_REGISTRIES) registry.disposeOwner(owner);+ for (const id of panelIds) dockApi.closePanel(id);+ }++ /** Ids of the plugin's panels the user currently has OPEN — so a reload can put+ * them back. Without this, editing a plugin makes its panel vanish mid-edit. */+ private openPanelIds(owner: Owner): string[] {+ return panelRegistry.byOwner(owner).filter((d) => dockApi.isPanelOpen(d.id)).map((d) => d.id);+ }++ /** Re-open panels that were open before a reload, if the new build still has them. */+ private restorePanels(ids: readonly string[]): void {+ for (const id of ids) if (panelRegistry.get(id)) dockApi.openPanel(id);+ }++ private async unload(id: string): Promise<void> {+ const entry = this.loaded.get(id);+ if (entry) {+ try {+ await entry.plugin.deactivate?.();+ } catch (e) {+ LogStore.push('warn', `plugin:${id}`, `deactivate failed: ${String(e)}`);+ }+ this.loaded.delete(id);+ }+ this.disposeContributions(ownerOf(id), () => entry?.context.dispose());+ }++ // — Actions the Plugins panel drives —++ /** Approve this plugin and activate it. */+ async trust(id: string): Promise<void> {+ await window.estella.plugins.trust(id);+ await this.reload(id);+ }++ /** Withdraw approval; the plugin unloads and waits to be approved again. */+ async revokeTrust(id: string): Promise<void> {+ await window.estella.plugins.revokeTrust(id);+ await this.unload(id);+ this.set(id, { phase: 'needs-trust', detail: undefined });+ }++ async disable(id: string, detail?: string): Promise<void> {+ await window.estella.plugins.setEnabled(id, false);+ await this.unload(id);+ this.set(id, { phase: 'disabled', detail });+ }++ async enable(id: string): Promise<void> {+ await window.estella.plugins.setEnabled(id, true);+ await this.reload(id);+ }++ /**+ * Unload and re-activate one plugin, recompiling from source. This is the hot+ * path for plugin development, and it is only correct because contributions are+ * owner-scoped: everything the old build registered goes away first.+ */+ async reload(id: string): Promise<void> {+ const found = await window.estella.plugins.list();+ const p = found.find((x) => x.id === id);+ const reopen = this.openPanelIds(ownerOf(id));+ await this.unload(id);+ if (!p?.manifest) {+ this.set(id, { phase: 'failed', detail: p?.error ?? 'plugin no longer on disk' });+ return;+ }+ this.set(id, { errorCount: 0, warnings: [], detail: undefined });+ await this.activate(id, p.manifest);+ this.restorePanels(reopen);+ }++ /** Unload everything (project close). Records are dropped with the project. */+ async unloadAll(): Promise<void> {+ for (const id of [...this.loaded.keys()]) await this.unload(id);+ this.records.clear();+ this.changed();+ }+}++export const PluginHost = new PluginHostImpl();diff --git a/desktop/src/plugins/api.ts b/desktop/src/plugins/api.tsnew file mode 100644index 000000000..af48a563b--- /dev/null+++ b/desktop/src/plugins/api.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file api.ts — the runtime half of `@estella/editor-api`, the one module a+ * plugin imports. It stays deliberately tiny: everything a plugin can DO+ * arrives through the context object handed to `activate`, not through+ * imported functions.+ *+ * The SIGNATURES live in ./types (which doubles as the `.d.ts` shipped to plugin+ * authors); each implementation below is annotated with the declared type, so an+ * implementation that stops matching what authors were promised is a compile error+ * rather than a runtime surprise in someone else's plugin.+ */+import type * as Api from './types';++export type * from './types';++export const definePlugin: typeof Api.definePlugin = (plugin) => plugin;++export const localize: typeof Api.localize = (value, locale) => {+ if (value === undefined) return '';+ if (typeof value === 'string') return value;+ return value[locale] ?? value.en ?? Object.values(value)[0] ?? '';+};diff --git a/desktop/src/plugins/context.ts b/desktop/src/plugins/context.tsnew file mode 100644index 000000000..003a267b4--- /dev/null+++ b/desktop/src/plugins/context.ts@@ -0,0 +1,303 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file context.ts+ * @brief Builds the {@link PluginContext} handed to one plugin's `activate`.+ *+ * This is where the design's central claim is cashed in: every `register` here+ * forwards to the SAME registry a built-in uses, tagged with this plugin's owner.+ * There is no plugin-specific implementation of commands, panels, menus, or+ * settings to drift from the built-in one — only an attribution.+ *+ * Two things the context adds on top of attribution:+ * - Localized strings are resolved here, so contributions reach the registries in+ * the editor's own `string` vocabulary and every consumer stays locale-agnostic.+ * - Plugin callbacks are wrapped (see PluginHost.guard) so a throw is attributed,+ * logged, and counted toward quarantine instead of breaking an editor surface.+ */+import { commands } from '@/commands/registry';+import { registerPanel } from '@/layout/panels';+import { registerMenuItem } from '@/layout/menus';+import { dockApi } from '@/layout/dockApi';+import { settingsRegistry } from '@/settings/registry';+import { useSettings } from '@/store/settingsStore';+import { useSelection } from '@/store/selectionStore';+import { useEditorStore } from '@/store/editorStore';+import { EditorControlSurface } from '@/engine/EditorSession';+import { ProjectStore } from '@/project/ProjectStore';+import { LogStore } from '@/store/LogStore';+import { Toasts } from '@/store/Toasts';+import { editorLocale } from '@/i18n';+import type { InspectorFieldValue } from '@/types';+import type { Owner, Disposable as CoreDisposable } from '@/contrib/ContributionRegistry';+import type { PluginManifest, PluginCapability } from './manifest';+import type {+ CommandContribution, Disposable, EditorEvents, EditorPlugin, EditorProjectApi, EditorSceneApi,+ FieldValue, LocalizedString, PanelContribution, PluginContext, PluginFs, SettingContribution,+} from './types';++const localize = (value: LocalizedString | undefined): string => {+ if (value === undefined) return '';+ if (typeof value === 'string') return value;+ return value[editorLocale] ?? value.en ?? Object.values(value)[0] ?? '';+};++/** Per-plugin persisted state, kept out of the project (it's a user preference). */+const stateKey = (id: string): string => `estella.plugin.state.${id}`;++function pluginState(id: string) {+ const read = (): Record<string, unknown> => {+ try {+ return JSON.parse(localStorage.getItem(stateKey(id)) ?? '{}') as Record<string, unknown>;+ } catch {+ return {};+ }+ };+ return {+ get<T>(key: string, fallback: T): T {+ const v = read()[key];+ return v === undefined ? fallback : (v as T);+ },+ set(key: string, value: unknown): void {+ const next = { ...read(), [key]: value };+ try {+ localStorage.setItem(stateKey(id), JSON.stringify(next));+ } catch {+ /* quota / private mode — state just won't persist */+ }+ },+ };+}++/**+ * The curated scene door. Delegates to the editor's own control surface, which+ * routes writes through SceneCommands — so a plugin's edits are undoable and+ * survive a play→stop rebuild without the plugin knowing either exists.+ */+function sceneApi(): EditorSceneApi {+ const s = EditorControlSurface;+ return {+ getSelection: () => s.getSelection(),+ getSelectionIds: () => s.getSelectionIds(),+ select: (id) => s.select(id),+ selectMany: (ids, primary) => s.selectMany(ids, primary),+ getSceneTree: () => s.getSceneTree(),+ getEntity: (id) => {+ const e = s.getEntity(id);+ return e ? { name: e.name, components: e.components } : null;+ },+ getFieldValue: (entity, component, key) => s.getFieldValue(entity, component, key) as FieldValue | null,+ addEntity: () => s.addEntity(),+ deleteEntity: (id) => s.deleteEntity(id),+ duplicateEntity: (id) => s.duplicateEntity(id),+ renameEntity: (id, name) => s.renameEntity(id, name),+ setParent: (id, parent) => s.setParent(id, parent),+ // The surface resolves the field's DECLARED inspector type and coerces against+ // it (rejecting a wrong shape or arity loudly), so a plugin never has to know+ // or state a field's type — the type argument here is advisory and ignored, and+ // the cast is safe because that runtime check is stricter than this signature.+ setField: (entity, component, key, value) =>+ s.setField(entity, component, key, 'string', value as InspectorFieldValue),+ addComponent: (entity, component) => s.addComponent(entity, component),+ removeComponent: (entity, component) => s.removeComponent(entity, component),+ setEntityXY: (id, x, y) => s.setEntityXY(id, x, y),+ transact: (label, fn) => s.transact(label, fn),+ undo: () => s.undo(),+ redo: () => s.redo(),+ };+}++function projectApi(): EditorProjectApi {+ return {+ root: () => ProjectStore.getSnapshot()?.root ?? null,+ currentScene: () => ProjectStore.getSnapshot()?.currentScene ?? null,+ save: () => ProjectStore.save(),+ listAssets: () => ProjectStore.listAssets().map((a) => a.path),+ refreshAssets: () => ProjectStore.refreshAssets(),+ };+}++/**+ * Filesystem access, gated on declared capabilities. The plugin's own folder is+ * always readable/writable; the project needs `fs:project`. Note this is a gate on+ * the CONVENIENCE API, not a sandbox — a renderer plugin shares the editor's realm+ * and could reach the bridge directly. The real boundary is the trust prompt; this+ * keeps honest plugins honest and makes their intent visible to the user.+ */+function pluginFs(id: string, dir: string, capabilities: PluginCapability[]): PluginFs {+ const denied = (what: string) => (): never => {+ throw new Error(`plugin "${id}" needs the "fs:project" capability in plugin.json to ${what}`);+ };+ // The plugin dir is absolute; the bridge is project-relative, so plugin-local+ // paths only resolve for a project-scoped plugin. A user-scoped plugin lives+ // outside the project root the bridge sandboxes to, and says so.+ const root = ProjectStore.getSnapshot()?.root;+ const local = (relPath: string): string => {+ if (!root || !dir.startsWith(root)) {+ throw new Error(`plugin "${id}" is outside the open project, so its own files aren't reachable yet`);+ }+ return `${dir.slice(root.length).replace(/^[/\\]/, '')}/${relPath}`.replace(/\\/g, '/');+ };+ const canProject = capabilities.includes('fs:project');+ return {+ read: (relPath) => window.estella.fs.read(local(relPath)),+ write: (relPath, contents) => window.estella.fs.write(local(relPath), contents),+ readProject: canProject ? (relPath) => window.estella.fs.read(relPath) : denied('read project files'),+ writeProject: canProject ? (relPath, contents) => window.estella.fs.write(relPath, contents) : denied('write project files'),+ };+}++function editorEvents(track: (d: Disposable) => Disposable): EditorEvents {+ return {+ on: (event, handler) => {+ switch (event) {+ case 'selectionChanged':+ return track({ dispose: useSelection.subscribe(handler) });+ case 'sceneChanged':+ return track({ dispose: ProjectStore.subscribe(handler) });+ case 'playStateChanged':+ // Fires only on an actual edit↔play transition, not on every store touch.+ return track({+ dispose: useEditorStore.subscribe((s, prev) => {+ if (s.isPlaying !== prev.isPlaying || s.isPaused !== prev.isPaused) handler();+ }),+ });+ }+ },+ };+}++/** What PluginHost needs back to tear a plugin down. */+export interface BuiltContext {+ ctx: PluginContext;+ /** Retract everything this plugin registered, in reverse order. */+ dispose(): void;+}++/**+ * Build the context for one plugin. `guard` wraps every callback the plugin hands+ * us; PluginHost supplies it so the throw-attribution and quarantine policy live in+ * one place rather than being re-implemented per contribution kind.+ */+export function buildPluginContext(+ manifest: PluginManifest,+ dir: string,+ owner: Owner,+ guard: <T>(what: string, fn: () => T, fallback: T) => T,+): BuiltContext {+ const id = manifest.id;+ const capabilities = manifest.capabilities ?? [];+ const disposables: Disposable[] = [];+ const track = <T extends Disposable>(d: T): T => {+ disposables.push(d);+ return d;+ };+ const adopt = (d: CoreDisposable): Disposable => track({ dispose: () => d.dispose() });++ const log = {+ info: (...args: unknown[]) => LogStore.push('info', `plugin:${id}`, args.map(String).join(' ')),+ warn: (...args: unknown[]) => LogStore.push('warn', `plugin:${id}`, args.map(String).join(' ')),+ error: (...args: unknown[]) => LogStore.push('error', `plugin:${id}`, args.map(String).join(' ')),+ };++ const registerCommand = (c: CommandContribution): Disposable => {+ const disposals: CoreDisposable[] = [+ commands.register(+ {+ id: c.id,+ label: localize(c.title),+ category: localize(c.category) || localize(manifest.name),+ keybinding: c.keybinding,+ run: () => guard(`command ${c.id}`, () => c.run(), undefined),+ isEnabled: c.isEnabled ? () => guard(`command ${c.id} isEnabled`, () => !!c.isEnabled!(), false) : undefined,+ isChecked: c.isChecked ? () => guard(`command ${c.id} isChecked`, () => !!c.isChecked!(), false) : undefined,+ },+ owner,+ ),+ ];+ // A menu row is a separate contribution pointing at the command, exactly as the+ // built-in menus are — so a contributed row can't restate label or enablement.+ if (c.menu) {+ disposals.push(+ registerMenuItem({ id: `${c.menu}/${c.id}`, location: c.menu, group: c.menu === 'tools' ? 'tools' : 'plugins', command: c.id }, owner),+ );+ }+ return track({ dispose: () => disposals.forEach((d) => d.dispose()) });+ };++ const registerPluginPanel = (p: PanelContribution): Disposable =>+ adopt(+ registerPanel(+ {+ id: p.id,+ title: () => localize(p.title),+ placement: p.placement ?? 'bottom',+ width: p.width,+ refs: ['log', 'content'],+ mount: (host) => guard(`panel ${p.id} mount`, () => p.mount(host), () => {}),+ },+ owner,+ ),+ );++ const registerSetting = (s: SettingContribution): Disposable => {+ const section = `plugin:${id}`;+ // One section per plugin, created on its first setting so a plugin with none+ // doesn't leave an empty page in the dialog's nav.+ if (!settingsRegistry.getSection(section)) {+ adopt(settingsRegistry.registerSection({ id: section, label: localize(manifest.name), category: 'plugin' }, owner));+ }+ const base = { id: s.id, scope: 'editor' as const, section, label: localize(s.label), description: localize(s.description) || undefined };+ const descriptor =+ s.type === 'enum'+ ? { ...base, type: 'enum' as const, default: s.default, options: s.options.map((o) => ({ value: o.value, label: localize(o.label) })) }+ : s.type === 'number'+ ? { ...base, type: 'number' as const, default: s.default, min: s.min, max: s.max, step: s.step }+ : s.type === 'string'+ ? { ...base, type: 'string' as const, default: s.default, placeholder: s.placeholder }+ : { ...base, type: 'boolean' as const, default: s.default };+ return adopt(settingsRegistry.register(descriptor, owner));+ };++ const ctx: PluginContext = {+ id,+ version: manifest.version,+ subscriptions: [],+ log,+ ui: { toast: (message, level = 'info') => Toasts.push(message, level) },+ state: pluginState(id),+ commands: { register: registerCommand, run: (cid) => commands.run(cid) },+ panels: {+ register: registerPluginPanel,+ open: (pid) => dockApi.openPanel(pid),+ },+ settings: {+ register: registerSetting,+ get: <T extends boolean | number | string>(sid: string) => useSettings.getState().getValue(sid) as T | undefined,+ },+ scene: sceneApi(),+ project: projectApi(),+ fs: pluginFs(id, dir, capabilities),+ events: editorEvents(track),+ };++ return {+ ctx,+ dispose() {+ // The plugin's own subscriptions first (they may reference contributions),+ // then ours in reverse registration order.+ for (const d of [...ctx.subscriptions].reverse()) {+ try {+ d.dispose();+ } catch (e) {+ log.error(`subscription cleanup failed: ${String(e)}`);+ }+ }+ ctx.subscriptions.length = 0;+ for (const d of [...disposables].reverse()) d.dispose();+ disposables.length = 0;+ },+ };+}++export type { EditorPlugin };diff --git a/desktop/src/plugins/init.ts b/desktop/src/plugins/init.tsnew file mode 100644index 000000000..f4cb7f04a--- /dev/null+++ b/desktop/src/plugins/init.ts@@ -0,0 +1,97 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file init.ts+ * @brief Ties the plugin host to the editor's lifecycle: load a project's plugins+ * when it opens, unload them when it closes, and reload one when its source+ * changes on disk.+ *+ * Project scoping matters — plugins live WITH the project, so switching projects+ * must not leave the previous one's contributions registered. Keeping that rule+ * here (rather than inside PluginHost) leaves the host a pure lifecycle machine+ * that tests can drive without a project.+ */+import { ProjectStore } from '@/project/ProjectStore';+import { PROJECT_PLUGIN_REL, PLUGIN_TYPES_FILE } from './paths';+import { PluginHost } from './PluginHost';+// The public type surface, as TEXT. types.ts is types-only and import-free+// precisely so it doubles as the `.d.ts` plugin authors compile against — shipping+// the same file the editor itself is typed by means the two can never disagree,+// and there is no package to publish or copy to go stale.+import editorApiTypes from './types.ts?raw';++let currentRoot: string | null = null;+let inited = false;++/**+ * Write the plugin API typings into the project so an author's editor resolves+ * `@estella/editor-api` (their tsconfig points `paths` at this file — see the+ * sample plugin). Rewritten on every project open, so the typings always match the+ * running editor rather than whatever version last touched the folder.+ */+async function syncPluginTypes(): Promise<void> {+ try {+ await window.estella.fs.write(PLUGIN_TYPES_FILE, editorApiTypes);+ } catch {+ // A project with no plugins folder yet, or a read-only checkout — authors get+ // typings the moment the folder exists, and nothing here is load-bearing.+ }+}++/**+ * Watch the open project and keep the plugin set in step with it. Call once at+ * startup, before the first project opens.+ */+export function initPlugins(): void {+ if (inited) return;+ inited = true;+ ProjectStore.subscribe(() => {+ const root = ProjectStore.getSnapshot()?.root ?? null;+ if (root === currentRoot) return;+ currentRoot = root;+ // Unload unconditionally on any switch: the outgoing project's plugins must+ // not survive into the incoming one, even if it has plugins of its own.+ void PluginHost.unloadAll().then(async () => {+ if (!root) return;+ await syncPluginTypes();+ await PluginHost.refresh();+ });+ });+}++/** Whether a changed project path is editor-plugin source (never asset content). */+export function isPluginPath(relPath: string): boolean {+ return pluginDirNameOf(relPath) !== null;+}++/** Plugin folder a changed project path belongs to, or null. */+function pluginDirNameOf(relPath: string): string | null {+ const p = relPath.replace(/\\/g, '/');+ const prefix = `${PROJECT_PLUGIN_REL}/`;+ if (!p.startsWith(prefix)) return null;+ const name = p.slice(prefix.length).split('/')[0];+ // A dot-prefixed entry is an editor-managed sidecar (the generated types), and+ // rewriting it must not trigger a reload — that would be an endless loop.+ return name && !name.startsWith('.') ? name : null;+}++/**+ * React to disk changes under the project's plugin folder (called by fsWatch, the+ * editor's single watcher subscriber). Any touched plugin folder is reloaded, which+ * recompiles from source — the loop that makes writing a plugin bearable.+ *+ * Note a folder NAME need not match the plugin id, so this reloads by re-scanning+ * rather than by guessing the id from the path.+ */+export function pluginPathsChanged(paths: readonly string[]): void {+ const touched = new Set<string>();+ for (const p of paths) {+ const dir = pluginDirNameOf(p);+ if (dir) touched.add(dir);+ }+ if (touched.size === 0) return;+ // One refresh covers every case uniformly — a new plugin folder, a deleted one,+ // and an edit to a running one (forced to reload). Cheap: discovery is a shallow+ // directory read, and only the touched plugins recompile.+ void PluginHost.refresh({ forceDirs: [...touched] });+}diff --git a/desktop/src/plugins/loader.ts b/desktop/src/plugins/loader.tsnew file mode 100644index 000000000..23ecbf17d--- /dev/null+++ b/desktop/src/plugins/loader.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file loader.ts+ * @brief Turns a compiled plugin's module text into its exported plugin object.+ *+ * The module arrives as CJS (see electron/pluginHost.ts) and is evaluated with an+ * injected `require` that resolves ONLY the host modules below. That is the whole+ * trick, and it buys three things an ESM + import-map loader would not:+ *+ * - React (and the SDK) are the HOST's instances by construction, so a plugin+ * panel can use hooks without the two-copies-of-React failure mode.+ * - Loading is SYNCHRONOUS, which the contribution contracts need — a viewport+ * tool's pointer handler and an inspector's build() cannot be async.+ * - Reloading is just re-evaluating with a fresh module object: no import-map+ * plumbing per window, no cache-busted URLs accumulating in a module graph,+ * and identical behaviour in dev and in the packaged app.+ *+ * `new Function` needs `unsafe-eval`, which the editor's CSP already grants for+ * the engine's wasm glue — this adds no new privilege. Plugin AUTHORS never see+ * CJS: they write ESM TypeScript and esbuild converts it.+ */+import * as React from 'react';+import * as ReactDOM from 'react-dom';+import * as ReactDOMClient from 'react-dom/client';+import * as ReactJsxRuntime from 'react/jsx-runtime';+import * as esengine from 'esengine';+import * as editorApi from './api';+import type { EditorPlugin } from './types';++/**+ * The modules a plugin may import. A bare specifier outside this set is a load+ * error rather than a silent `undefined` — a plugin that quietly got nothing for+ * its import would fail later, somewhere unrelated.+ */+const HOST_MODULES: Record<string, unknown> = {+ react: React,+ 'react-dom': ReactDOM,+ 'react-dom/client': ReactDOMClient,+ 'react/jsx-runtime': ReactJsxRuntime,+ '@estella/editor-api': editorApi,+ esengine,+};++/** Specifiers a plugin can import, for the error message and the docs. */+export const HOST_MODULE_NAMES = Object.keys(HOST_MODULES);++function hostRequire(specifier: string): unknown {+ const mod = HOST_MODULES[specifier];+ if (!mod) {+ throw new Error(+ `cannot import "${specifier}" — a plugin may only import ${HOST_MODULE_NAMES.join(', ')} ` ++ `(bundle anything else into your plugin)`,+ );+ }+ return mod;+}++/**+ * Evaluate `code` and return its default export as a plugin object. Throws with+ * the plugin's own error if the module body throws, or a clear diagnostic if it+ * doesn't export the expected shape.+ */+export function evaluatePlugin(id: string, code: string): EditorPlugin {+ const module: { exports: Record<string, unknown> } = { exports: {} };+ // Named so a stack trace from inside the plugin points at the plugin, not at+ // an anonymous eval frame.+ const factory = new Function(+ 'module',+ 'exports',+ 'require',+ `${code}\n//# sourceURL=estella-plugin:${id}`,+ ) as (m: typeof module, e: Record<string, unknown>, r: typeof hostRequire) => void;++ factory(module, module.exports, hostRequire);++ const exported = (module.exports.default ?? module.exports) as Partial<EditorPlugin>;+ if (!exported || typeof exported !== 'object') {+ throw new Error('plugin entry must default-export a plugin object (see definePlugin)');+ }+ if (typeof exported.activate !== 'function') {+ throw new Error('plugin entry default-exports an object with no `activate(ctx)` function');+ }+ return exported as EditorPlugin;+}diff --git a/desktop/src/plugins/manifest.ts b/desktop/src/plugins/manifest.tsnew file mode 100644index 000000000..0cfe8f936--- /dev/null+++ b/desktop/src/plugins/manifest.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file manifest.ts+ * @brief The `plugin.json` contract and its validation — shared by the main+ * process (which reads it off disk) and the renderer (which shows it and+ * activates from it), so the two can never disagree about what a valid+ * plugin is. Pure: no Node, no Electron, no React.+ *+ * Validation NEVER throws and never silently drops: a plugin whose manifest is+ * malformed still appears in the list, carrying the reason. Dropping a file the+ * user wrote is worse than naming what's wrong with it — the same posture+ * electron/platformCatalog.ts takes for project platform profiles.+ */++// LocalizedString is owned by the public type surface (types.ts) — one spelling+// for the manifest and for every contribution a plugin registers.+import type { LocalizedString } from './types';++export type { LocalizedString };++/** Declared side effects, shown to the user at the trust prompt. */+export type PluginCapability = 'fs:project' | 'net' | 'shell' | 'process';++export const PLUGIN_CAPABILITIES: readonly PluginCapability[] = ['fs:project', 'net', 'shell', 'process'];++export interface PluginManifest {+ /** Stable, namespaced: `<publisher>.<name>` by convention. */+ id: string;+ name: LocalizedString;+ version: string;+ description?: LocalizedString;+ publisher?: string;+ /** Editor version range this plugin claims to work with (e.g. `^0.33`). */+ engines?: { editor?: string };+ /** Entry points, project-relative to the plugin dir. `editor` runs in the+ * renderer; `node` (a later phase) in the main process. */+ main?: { editor?: string; node?: string };+ /** Declared capabilities — disclosure at the trust prompt, and what the+ * convenience APIs on the plugin context are gated on. */+ capabilities?: PluginCapability[];+}++/** Resolve a localized string for a locale, falling back to `en` then any value. */+export function resolveLocalized(value: LocalizedString | undefined, locale: string): string {+ if (value === undefined) return '';+ if (typeof value === 'string') return value;+ return value[locale] ?? value.en ?? Object.values(value)[0] ?? '';+}++/** Ids must be filesystem- and namespace-safe, and readable in a command palette. */+const ID_RE = /^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/;++const isLocalized = (v: unknown): boolean =>+ typeof v === 'string'+ ? v.length > 0+ : !!v && typeof v === 'object' && typeof (v as { en?: unknown }).en === 'string';++/**+ * Validate a parsed `plugin.json`. Returns the typed manifest, or the first+ * problem as a human sentence (which is what the Plugins panel shows).+ */+export function validateManifest(raw: unknown): { manifest: PluginManifest } | { error: string } {+ if (!raw || typeof raw !== 'object') return { error: 'plugin.json must contain a JSON object' };+ const m = raw as Record<string, unknown>;++ if (typeof m.id !== 'string' || !ID_RE.test(m.id)) {+ return { error: '`id` must be a dotted, lowercase name like "acme.level-tools"' };+ }+ if (!isLocalized(m.name)) {+ return { error: '`name` must be a non-empty string, or an object with an `en` string' };+ }+ if (typeof m.version !== 'string' || !/^\d+\.\d+\.\d+/.test(m.version)) {+ return { error: '`version` must be a semver string like "1.0.0"' };+ }+ if (m.description !== undefined && !isLocalized(m.description)) {+ return { error: '`description` must be a string, or an object with an `en` string' };+ }+ const main = m.main as Record<string, unknown> | undefined;+ if (main !== undefined && (typeof main !== 'object' || main === null)) {+ return { error: '`main` must be an object like { "editor": "src/editor.ts" }' };+ }+ if (main?.editor !== undefined && typeof main.editor !== 'string') {+ return { error: '`main.editor` must be a path relative to the plugin folder' };+ }+ if (main?.node !== undefined && typeof main.node !== 'string') {+ return { error: '`main.node` must be a path relative to the plugin folder' };+ }+ if (!main?.editor && !main?.node) {+ return { error: 'plugin has no entry point — set `main.editor` (e.g. "src/editor.ts")' };+ }+ if (main?.editor && !main.node && typeof main.editor === 'string' && main.editor.includes('..')) {+ return { error: '`main.editor` must stay inside the plugin folder' };+ }+ if (m.capabilities !== undefined) {+ if (!Array.isArray(m.capabilities)) return { error: '`capabilities` must be an array of strings' };+ const bad = m.capabilities.find((c) => !PLUGIN_CAPABILITIES.includes(c as PluginCapability));+ if (bad !== undefined) {+ return { error: `unknown capability ${JSON.stringify(bad)} (known: ${PLUGIN_CAPABILITIES.join(', ')})` };+ }+ }+ const engines = m.engines as Record<string, unknown> | undefined;+ if (engines?.editor !== undefined && typeof engines.editor !== 'string') {+ return { error: '`engines.editor` must be a version range string like "^0.33"' };+ }+ return { manifest: raw as PluginManifest };+}++/**+ * Whether `version` satisfies `range`. Deliberately supports only the three+ * spellings a plugin should need — `*`, `^x.y[.z]`, and `>=x.y[.z]` — and REJECTS+ * anything else rather than guessing: a range we silently misread would load a+ * plugin against an API it wasn't written for.+ */+export function satisfiesEditorRange(version: string, range: string): { ok: true } | { ok: false; reason: string } {+ const parse = (v: string): [number, number, number] | null => {+ const m = /^(\d+)\.(\d+)(?:\.(\d+))?/.exec(v.trim());+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : null;+ };+ const current = parse(version);+ if (!current) return { ok: false, reason: `cannot read editor version "${version}"` };++ const r = range.trim();+ if (r === '*') return { ok: true };++ const op = r.startsWith('^') ? '^' : r.startsWith('>=') ? '>=' : '=';+ const wanted = parse(r.replace(/^(\^|>=)/, ''));+ if (!wanted) return { ok: false, reason: `cannot read version range "${range}" (use "*", "^0.33", or ">=0.33")` };++ const cmp = current[0] - wanted[0] || current[1] - wanted[1] || current[2] - wanted[2];+ if (op === '>=') {+ return cmp >= 0 ? { ok: true } : { ok: false, reason: `needs editor >= ${r.slice(2)}, running ${version}` };+ }+ if (op === '=') {+ return cmp === 0 ? { ok: true } : { ok: false, reason: `needs editor ${r}, running ${version}` };+ }+ // Caret. Below 1.0.0 the MINOR is the breaking-change axis (npm semantics), and+ // the editor is pre-1.0 — so ^0.33 must not match 0.34.+ if (cmp < 0) return { ok: false, reason: `needs editor ${r}, running ${version}` };+ const sameMajorLine = wanted[0] === 0 ? current[0] === 0 && current[1] === wanted[1] : current[0] === wanted[0];+ return sameMajorLine ? { ok: true } : { ok: false, reason: `needs editor ${r}, running ${version}` };+}diff --git a/desktop/src/plugins/paths.ts b/desktop/src/plugins/paths.tsnew file mode 100644index 000000000..10ca50f96--- /dev/null+++ b/desktop/src/plugins/paths.ts@@ -0,0 +1,18 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file paths.ts — where a project keeps its plugins, spelled ONCE.+ *+ * Both processes need it and neither can own it: main resolves it against the OS+ * separator to read the folder, while the renderer matches watcher paths (always+ * posix) against it. Two literals would drift the day one of them changed.+ */++/** Project-relative plugin folder, posix — the form watcher paths come in. */+export const PROJECT_PLUGIN_REL = '.esengine/plugins';++/** Folder (under the plugin dir) the editor writes plugin API typings into. */+export const PLUGIN_TYPES_DIR = '.types';++/** The generated typings file plugin tsconfigs point at. */+export const PLUGIN_TYPES_FILE = `${PROJECT_PLUGIN_REL}/${PLUGIN_TYPES_DIR}/editor-api.d.ts`;diff --git a/desktop/src/plugins/types.ts b/desktop/src/plugins/types.tsnew file mode 100644index 000000000..2d6c3f0ad--- /dev/null+++ b/desktop/src/plugins/types.ts@@ -0,0 +1,277 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file types.ts — THE public type surface of the editor plugin API.+ *+ * Deliberately SELF-CONTAINED (types only, zero imports): the editor copies this+ * file's text verbatim into a project's `.esengine/plugins/.types/editor-api.d.ts`,+ * so plugin authors get full typings with no package to install and no copy that+ * can go stale. An import here would break that, so keep every shape local — and+ * that constraint is a feature: it forces the surface to stay small and explicit+ * rather than leaking the editor's whole internal vocabulary.+ *+ * What a plugin gets is a CURATED subset, not the editor's internals. `scene` in+ * particular exposes the model write door (undoable, transactional) and omits the+ * verification/headless machinery on the internal control surface, which plugins+ * have no business driving.+ */++/** A human string a plugin supplies, per locale (falling back to `en`). */+export type LocalizedString = string | { en: string; [locale: string]: string };++/** Retracts one registration. Push it on `ctx.subscriptions` to tie it to unload. */+export interface Disposable {+ dispose(): void;+}++/** A scene entity's stable id (a source id — survives play/stop rebuilds). */+export type EntityId = number;++/** Values a component field can hold through the plugin write door. */+export type FieldValue = number | boolean | string | number[];++/** A node of the scene tree as plugins read it. */+export interface SceneNode {+ id: EntityId;+ name: string;+ children?: SceneNode[];+}++// =============================================================================+// Contributions+// =============================================================================++/** Keybinding chord, e.g. `mod+alt+b`. `mod` is ⌘ on macOS, Ctrl elsewhere. */+export type Keybinding = string | string[];++export interface CommandContribution {+ /** Namespace with your plugin id, e.g. `acme.bakeOcclusion`. */+ id: string;+ title: LocalizedString;+ /** Grouping shown in the command palette. */+ category?: LocalizedString;+ keybinding?: Keybinding;+ /**+ * Menu to place this command in. `tools` is the default home for plugin+ * commands; the other menu bar ids are available for a command that genuinely+ * belongs beside its built-in siblings.+ */+ menu?: 'tools' | 'file' | 'edit' | 'entity' | 'view' | 'build' | 'window' | 'help';+ run(): void;+ /** Greys the row out when false (default: always enabled). */+ isEnabled?(): boolean;+ /** Drives a checkmark for a toggle command. */+ isChecked?(): boolean;+}++/** Where a contributed panel docks the first time it opens. */+export type PanelPlacement = 'document' | 'side-left' | 'side-right' | 'bottom';++export interface PanelContribution {+ /** Namespace with your plugin id, e.g. `acme.budget`. */+ id: string;+ title: LocalizedString;+ placement?: PanelPlacement;+ /** `side-*` panels: initial column width in CSS px. */+ width?: number;+ /**+ * Build the panel's contents into `host`, and return a teardown function. Called+ * when the panel mounts, torn down when it closes or the plugin unloads.+ *+ * The host element is inside the editor's own dock frame, so the theme CSS+ * variables (`--bg`, `--text`, `--accent`, …) are in scope: style against those+ * and the panel matches the editor in both light and dark.+ */+ mount(host: HTMLElement): () => void;+}++export interface SettingContributionBase {+ /** Namespace with your plugin id, e.g. `acme.budget.warnAt`. */+ id: string;+ label: LocalizedString;+ description?: LocalizedString;+}++export interface BooleanSettingContribution extends SettingContributionBase {+ type: 'boolean';+ default: boolean;+}++export interface NumberSettingContribution extends SettingContributionBase {+ type: 'number';+ default: number;+ min?: number;+ max?: number;+ step?: number;+}++export interface StringSettingContribution extends SettingContributionBase {+ type: 'string';+ default: string;+ placeholder?: string;+}++export interface EnumSettingContribution extends SettingContributionBase {+ type: 'enum';+ default: string;+ options: { value: string; label: LocalizedString }[];+}++export type SettingContribution =+ | BooleanSettingContribution+ | NumberSettingContribution+ | StringSettingContribution+ | EnumSettingContribution;++// =============================================================================+// Editor APIs+// =============================================================================++/**+ * The scene write/read door. Every mutation here routes through the editor's+ * command layer, so it lands in the undo history and survives a play→stop rebuild.+ * Never reach around this to the live engine World: edits made there are dropped+ * the moment the scene is rebuilt from the model.+ */+export interface EditorSceneApi {+ /** The primary selected entity, or null. */+ getSelection(): EntityId | null;+ /** The full multi-selection. */+ getSelectionIds(): EntityId[];+ select(id: EntityId | null): void;+ selectMany(ids: EntityId[], primary: EntityId): void;++ /** The scene tree (roots, each with children). */+ getSceneTree(): SceneNode[];+ /** An entity's name + the component types on it, or null if it's gone. */+ getEntity(id: EntityId): { name: string; components: string[] } | null;+ /** A single component field's current value, or null if absent. */+ getFieldValue(entity: EntityId, component: string, key: string): FieldValue | null;++ addEntity(): EntityId | null;+ deleteEntity(id: EntityId): void;+ duplicateEntity(id: EntityId): EntityId | null;+ renameEntity(id: EntityId, name: string): void;+ setParent(id: EntityId, parent: EntityId | null): void;+ /** Write a component field. Throws if the component or key doesn't exist. */+ setField(entity: EntityId, component: string, key: string, value: FieldValue): void;+ addComponent(entity: EntityId, component: string): void;+ removeComponent(entity: EntityId, component: string): void;+ setEntityXY(id: EntityId, x: number, y: number): void;++ /** Run `fn` as ONE undo step (committed on return, rolled back if it throws). */+ transact(label: string, fn: () => void): void;++ undo(): void;+ redo(): void;+}++export interface EditorProjectApi {+ /** Absolute path of the open project root, or null when none is open. */+ root(): string | null;+ /** Project-relative path of the open scene, or null. */+ currentScene(): string | null;+ /** Save the open scene. */+ save(): Promise<void>;+ /** Project-relative paths of every asset the editor knows about. */+ listAssets(): string[];+ /** Re-scan the asset registry; resolves when a new ref is resolvable. */+ refreshAssets(): Promise<void>;+}++/** Files a plugin may read/write. Paths are relative to the plugin's own folder+ * unless the plugin declared the `fs:project` capability and uses `project*`. */+export interface PluginFs {+ read(relPath: string): Promise<string>;+ write(relPath: string, contents: string): Promise<void>;+ /** Requires the `fs:project` capability; paths are project-relative. */+ readProject(relPath: string): Promise<string>;+ /** Requires the `fs:project` capability; paths are project-relative. */+ writeProject(relPath: string, contents: string): Promise<void>;+}++/** Editor events a plugin can observe. Handlers are dropped on unload. */+export interface EditorEvents {+ on(event: 'selectionChanged' | 'sceneChanged' | 'playStateChanged', handler: () => void): Disposable;+}++// =============================================================================+// Context+// =============================================================================++/**+ * Everything a plugin is handed. Every `register` here is attributed to THIS+ * plugin, which is what makes unload, disable, and hot reload possible: the editor+ * retracts the whole set in one operation rather than trusting cleanup code.+ */+export interface PluginContext {+ readonly id: string;+ readonly version: string;+ /** Disposables retracted on unload — the simplest correct cleanup. */+ readonly subscriptions: Disposable[];++ /** Log lines, attributed to this plugin in the Output Log. */+ readonly log: {+ info(...args: unknown[]): void;+ warn(...args: unknown[]): void;+ error(...args: unknown[]): void;+ };+ /** Transient user-facing notices. */+ readonly ui: {+ toast(message: string, level?: 'info' | 'success' | 'warn' | 'error'): void;+ };+ /** Persisted per-plugin key/value state (per user, not in the project). */+ readonly state: {+ get<T>(key: string, fallback: T): T;+ set(key: string, value: unknown): void;+ };++ readonly commands: {+ register(command: CommandContribution): Disposable;+ /** Run any editor command by id — including built-ins. */+ run(id: string): void;+ };+ readonly panels: {+ register(panel: PanelContribution): Disposable;+ /** Open (or bring forward) a panel by id. */+ open(id: string): void;+ };+ readonly settings: {+ register(setting: SettingContribution): Disposable;+ /** Current value of one of YOUR settings. */+ get<T extends boolean | number | string>(id: string): T | undefined;+ };++ readonly scene: EditorSceneApi;+ readonly project: EditorProjectApi;+ readonly fs: PluginFs;+ readonly events: EditorEvents;+}++/** What a plugin's entry module default-exports. */+export interface EditorPlugin {+ /** Called once when the plugin loads. May be async. */+ activate(ctx: PluginContext): void | Promise<void>;+ /** Optional extra teardown; registrations and `subscriptions` are retracted+ * automatically, so most plugins don't need this. */+ deactivate?(): void | Promise<void>;+}++// =============================================================================+// Runtime exports of `@estella/editor-api`+//+// Declared (not defined) here so this file remains the WHOLE public surface — the+// copy shipped to plugin authors has to describe the functions they can import,+// not just the shapes. api.ts implements these and is type-checked against these+// declarations, so the two cannot drift.+// =============================================================================++/**+ * Declare a plugin. An identity function whose only job is to type-check the object+ * literal at the definition site, so a typo in `activate` is a compile error in your+ * editor rather than a load failure in ours.+ */+export declare function definePlugin(plugin: EditorPlugin): EditorPlugin;++/** Resolve a {@link LocalizedString} for a locale, falling back to `en`. */+export declare function localize(value: LocalizedString | undefined, locale: string): string;diff --git a/desktop/src/project/fsWatch.ts b/desktop/src/project/fsWatch.tsindex 8237772bc..97d6d6c99 100644--- a/desktop/src/project/fsWatch.ts+++ b/desktop/src/project/fsWatch.ts@@ -10,6 +10,7 @@*/import { ProjectStore } from './ProjectStore';import { PlayRealm, PlayRealms } from '../engine/PlayRealm';+import { pluginPathsChanged, isPluginPath } from '../plugins/init';const listeners = new Set<() => void>();let version = 0;@@ -40,6 +41,8 @@ let sceneDebounce: ReturnType<typeof setTimeout> | null = null;// filename unknown) forces a full rescan for the window.let pendingPaths = new Set<string>();let sawOverflow = false;+let pluginDebounce: ReturnType<typeof setTimeout> | null = null;+let pendingPluginPaths = new Set<string>();// A project source module under src/ — a change here can alter a project// component's field schema, so the inspector must re-extract (esbuild, ~100ms).@@ -67,10 +70,16 @@ async function rebuildScriptsAndReloadPlay(): Promise<void> {export function initFsWatch(): void {if (inited || !window.estella?.fs?.onChange) return;inited = true;- window.estella.fs.onChange((paths) => {+ window.estella.fs.onChange((allPaths) => {+ // Plugin sources are watched but are NOT project content: they must never+ // reach the asset registry (which would try to index them) — they only drive+ // plugin hot reload. Split them off before anything else looks at the batch.+ const paths = allPaths.filter((p) => !isPluginPath(p));+ const pluginPaths = allPaths.filter(isPluginPath);+// Coalesce back-to-back bursts; one incremental update + one bump per quiet// window. Accumulate the precise paths so none is lost across bursts.- if (paths.length === 0) sawOverflow = true;+ if (allPaths.length === 0) sawOverflow = true;else for (const p of paths) pendingPaths.add(p);if (debounce) clearTimeout(debounce);debounce = setTimeout(() => {@@ -93,6 +102,19 @@ export function initFsWatch(): void {sceneDebounce = setTimeout(() => void ProjectStore.reloadOpenSceneFromDisk(), 120);}+ // An editor-plugin source edit → recompile + re-activate that plugin. Its own+ // window (a plugin's save burst is unrelated to the asset registry's), and its+ // own accumulation so a path isn't lost between bursts.+ if (pluginPaths.length > 0) {+ for (const p of pluginPaths) pendingPluginPaths.add(p);+ if (pluginDebounce) clearTimeout(pluginDebounce);+ pluginDebounce = setTimeout(() => {+ const batch = [...pendingPluginPaths];+ pendingPluginPaths = new Set();+ pluginPathsChanged(batch);+ }, 200);+ }+// A component-source edit → re-extract schemas so the inspector reflects the// new fields live (separate, longer window: extraction bundles with esbuild).if (paths.some(isSourceModule)) {@@ -112,10 +134,11 @@ export function initFsWatch(): void {/** Drop pending debounced work + accumulated paths. Call on project switch so a* burst captured for the old project can't flush against the new one. */export function resetFsWatch(): void {- for (const t of [debounce, schemaDebounce, scriptsDebounce, sceneDebounce]) {+ for (const t of [debounce, schemaDebounce, scriptsDebounce, sceneDebounce, pluginDebounce]) {if (t) clearTimeout(t);}- debounce = schemaDebounce = scriptsDebounce = sceneDebounce = null;+ debounce = schemaDebounce = scriptsDebounce = sceneDebounce = pluginDebounce = null;pendingPaths = new Set();+ pendingPluginPaths = new Set();sawOverflow = false;}diff --git a/desktop/src/theme/plugins.css b/desktop/src/theme/plugins.cssnew file mode 100644index 000000000..c57f7a247--- /dev/null+++ b/desktop/src/theme/plugins.css@@ -0,0 +1,43 @@+/* SPDX-License-Identifier: Apache-2.0 */+/* SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team */++/* Plugins panel (PluginsPanel): what's installed, what's running, what broke —+ plus the trust gate. Built from the same surface/border/radius tokens the other+ panels use, so it reads as part of the editor rather than a settings page. */+.plug-panel { display: flex; flex-direction: column; height: 100%; overflow: hidden; }+.plug-toolbar { display: flex; align-items: center; gap: 6px; padding: 6px 8px; border-bottom: 1px solid var(--border); }+.plug-list { display: flex; flex-direction: column; gap: 8px; padding: 8px; overflow-y: auto; }++.plug-row { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; background: var(--srf-3); border: 1px solid var(--border); border-radius: var(--r-sm); }+.plug-row__head { display: flex; align-items: center; gap: 8px; }+.plug-row__name { font-size: var(--fs-xs); font-weight: 600; color: var(--text-hi); }+.plug-row__version { font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-faint); }+.plug-row__scope { font-size: var(--fs-2xs); color: var(--text-faint); padding: 1px 6px; border: 1px solid var(--border); border-radius: 999px; }+.plug-row__spacer { flex: 1; }+.plug-row__desc { font-size: var(--fs-2xs); color: var(--text-dim); line-height: 1.5; }+.plug-row__detail { display: flex; align-items: flex-start; gap: 5px; font-size: var(--fs-2xs); color: #e0a35a; line-height: 1.5; }+.plug-row__detail.is-warn { color: var(--text-dim); }+.plug-row__actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 2px; }++/* Status chip. Only "active" gets colour — a list of green badges would make the+ one row that needs attention harder to find, not easier. */+.plug-chip { font-size: var(--fs-2xs); padding: 1px 7px; border-radius: 999px; border: 1px solid var(--border); color: var(--text-dim); white-space: nowrap; }+.plug-chip.is-active { color: #7fbf8f; border-color: #7fbf8f; }+.plug-chip.is-failed, .plug-chip.is-incompatible { color: #e0736a; border-color: #e0736a; }+.plug-chip.is-needs-trust { color: #e0a35a; border-color: #e0a35a; }+.plug-chip.is-disabled, .plug-chip.is-shadowed { color: var(--text-faint); }++/* Trust gate — inset and bordered so it reads as a decision, not a description. */+.plug-trust { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; margin: 2px 0; background: var(--srf-2); border: 1px solid var(--border); border-left: 2px solid #e0a35a; border-radius: var(--r-sm); }+.plug-trust__title { display: flex; align-items: center; gap: 6px; font-size: var(--fs-xs); font-weight: 600; color: var(--text-hi); }+.plug-trust__body { font-size: var(--fs-2xs); color: var(--text-dim); line-height: 1.55; margin: 0; }+.plug-trust__caps { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }+.plug-trust__capsLabel { font-size: var(--fs-2xs); color: var(--text-faint); }+.plug-cap { font-size: var(--fs-2xs); color: var(--text); padding: 1px 6px; background: var(--srf-4); border-radius: var(--r-sm); }+.plug-muted { font-size: var(--fs-2xs); color: var(--text-faint); line-height: 1.5; margin: 0; }+.plug-trust .btn-soft { align-self: flex-start; margin-top: 2px; }++/* A contributed panel's host element. The plugin owns everything inside; the frame+ only guarantees it fills the tab and scrolls, and that the theme tokens are in+ scope so a plugin styling against them matches the editor. */+.plugin-panel { width: 100%; height: 100%; overflow: auto; }diff --git a/desktop/tests/content-policy.test.ts b/desktop/tests/content-policy.test.tsnew file mode 100644index 000000000..e1e22eb10--- /dev/null+++ b/desktop/tests/content-policy.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The single authority on what counts as project content, and the separate+ * question of what the watcher reports. These came apart when editor plugins+ * landed: plugin sources live under `.esengine/` (so they are NOT content —+ * they must stay out of the Content Browser and the asset scan) but they DO+ * need watching, because they drive plugin hot reload.+ *+ * The loop hazard is what makes this worth pinning: the editor writes its own+ * caches and the generated plugin typings under `.esengine/`, and reporting+ * those would make the editor retrigger itself forever.+ */+import { describe, it, expect } from 'vitest';+import { isContentDir, isContentFile, isNonContentPath, isPluginSourcePath, isWatchedPath } from '../electron/contentPolicy';++describe('content classification', () => {+ it('excludes dot entries, dependency and build dirs', () => {+ expect(isContentDir('assets')).toBe(true);+ expect(isContentDir('.esengine')).toBe(false);+ expect(isContentDir('node_modules')).toBe(false);+ expect(isContentDir('dist')).toBe(false);+ expect(isContentFile('hero.png')).toBe(true);+ expect(isContentFile('hero.png.meta')).toBe(false);+ expect(isContentFile('.DS_Store')).toBe(false);+ });++ it('treats any dot or build segment in a path as leaving content space', () => {+ expect(isNonContentPath('assets/hero.png')).toBe(false);+ expect(isNonContentPath('.esengine/cache/assets.json')).toBe(true);+ expect(isNonContentPath('src/node_modules/x.ts')).toBe(true);+ expect(isNonContentPath('assets\\sub\\hero.png')).toBe(false); // windows separators+ });+});++describe('plugin sources are watched but are not content', () => {+ const pluginEntry = '.esengine/plugins/acme.tools/src/editor.ts';++ it('recognizes a plugin source path', () => {+ expect(isPluginSourcePath(pluginEntry)).toBe(true);+ expect(isPluginSourcePath('.esengine/plugins/acme.tools/plugin.json')).toBe(true);+ expect(isPluginSourcePath('.esengine/plugins')).toBe(false); // the dir itself+ expect(isPluginSourcePath('.esengine/cache/assets.json')).toBe(false);+ expect(isPluginSourcePath('assets/hero.png')).toBe(false);+ });++ it('keeps plugin sources OUT of content space', () => {+ // If this flipped, plugin sources would show up in the Content Browser and be+ // scanned as assets.+ expect(isNonContentPath(pluginEntry)).toBe(true);+ });++ it('reports plugin sources to the watcher anyway', () => {+ expect(isWatchedPath(pluginEntry)).toBe(true);+ expect(isWatchedPath('assets/hero.png')).toBe(true);+ });++ it('never watches the editor`s own writes under .esengine', () => {+ // Each of these is written BY the editor; watching one would loop.+ expect(isWatchedPath('.esengine/cache/assets.json')).toBe(false);+ expect(isWatchedPath('.esengine/cache/scripts.mjs')).toBe(false);+ expect(isWatchedPath('.esengine/workspace.json')).toBe(false);+ // The generated plugin typings sit INSIDE the plugin dir, so they need the+ // dot-prefix rule specifically — the plugin-source allowance would otherwise+ // let the editor's own write retrigger a plugin reload.+ expect(isWatchedPath('.esengine/plugins/.types/editor-api.d.ts')).toBe(false);+ expect(isPluginSourcePath('.esengine/plugins/.types/editor-api.d.ts')).toBe(false);+ });++ it('handles windows separators in plugin paths', () => {+ expect(isPluginSourcePath('.esengine\\plugins\\acme.tools\\src\\editor.ts')).toBe(true);+ });+});diff --git a/desktop/tests/menu-registry.test.ts b/desktop/tests/menu-registry.test.tsindex ea8bafd55..47c4530b9 100644--- a/desktop/tests/menu-registry.test.ts+++ b/desktop/tests/menu-registry.test.ts@@ -47,7 +47,9 @@ describe('menu registry', () => {'view.toggleCoordSpace', 'view.togglePivotMode', 'view.toggleSnapping',]);expect(layout('build')).toEqual(['project.export', null, 'build.scripts', 'project.extractSchemas']);- expect(layout('window')).toEqual(['view.resetLayout', null, 'project.close']);+ // `plugins.open` joined the layout group after the migration — the Plugins panel+ // is opened on demand, so a menu row is how it's reached.+ expect(layout('window')).toEqual(['view.resetLayout', 'plugins.open', null, 'project.close']);expect(layout('help')).toEqual(['help.about', 'help.checkUpdates', null, 'palette.open', 'help.shortcuts', null, 'help.openLogs',]);diff --git a/desktop/tests/plugin-api-surface.test.ts b/desktop/tests/plugin-api-surface.test.tsnew file mode 100644index 000000000..c10667667--- /dev/null+++ b/desktop/tests/plugin-api-surface.test.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The plugin API's two self-consistency rules.+ *+ * 1. `types.ts` must describe the WHOLE public surface, runtime functions included.+ * It is copied verbatim into a project as `editor-api.d.ts`, so a runtime export+ * that isn't declared there is a function authors can call but cannot type —+ * exactly the gap `definePlugin` fell into.+ *+ * 2. `types.ts` must stay import-free. One import and the copied file stops being+ * valid standalone typings, silently breaking every plugin's tsconfig.+ */+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import * as api from '@/plugins/api';++const TYPES_FILE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../src/plugins/types.ts');+const source = readFileSync(TYPES_FILE, 'utf8');++describe('plugin API surface', () => {+ it('declares every runtime export of @estella/editor-api', () => {+ const runtimeExports = Object.keys(api).filter((k) => typeof (api as Record<string, unknown>)[k] === 'function');+ expect(runtimeExports.length).toBeGreaterThan(0);+ for (const name of runtimeExports) {+ expect(+ new RegExp(`export declare (function|const) ${name}\\b`).test(source),+ `types.ts does not declare runtime export "${name}" — authors can call it but cannot type it`,+ ).toBe(true);+ }+ });++ it('keeps types.ts import-free so the shipped .d.ts stands alone', () => {+ const imports = source+ .split('\n')+ .filter((line) => /^\s*import\b/.test(line) && !line.trim().startsWith('*'));+ expect(imports, 'types.ts must not import anything (it ships as standalone typings)').toEqual([]);+ });++ it('exposes definePlugin as an identity function', () => {+ const plugin = { activate: () => {} };+ expect(api.definePlugin(plugin)).toBe(plugin);+ });++ it('localize falls back to en, then to any value', () => {+ expect(api.localize({ en: 'Tools', 'zh-CN': '工具' }, 'zh-CN')).toBe('工具');+ expect(api.localize({ en: 'Tools' }, 'de')).toBe('Tools');+ expect(api.localize('plain', 'de')).toBe('plain');+ expect(api.localize(undefined, 'en')).toBe('');+ });+});diff --git a/desktop/tests/plugin-loader.test.ts b/desktop/tests/plugin-loader.test.tsnew file mode 100644index 000000000..1a5573b16--- /dev/null+++ b/desktop/tests/plugin-loader.test.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Main-process plugin discovery + compilation, driven against the REAL+ * sample plugin in examples/, so the sample is a fixture that can't silently+ * rot: if the example stops compiling or its manifest stops validating, this+ * fails.+ *+ * Also covers the two discovery behaviours that matter most — a broken plugin is+ * reported rather than dropped, and a project plugin shadows a user one of the same+ * id (with the shadowed one still listed, so the user can see why it isn't running).+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { discoverPlugins, compilePlugin, PROJECT_PLUGIN_DIR } from '../electron/pluginHost';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const SAMPLE_PROJECT = path.resolve(HERE, '../../examples/sprite-animation');+const SAMPLE_ID = 'estella.scene-report';++let scratch: string;+/** A throwaway userData dir, so the real one is never read or written. */+let userData: string;++const writePlugin = (root: string, folder: string, manifest: unknown, entry?: string): string => {+ const dir = path.join(root, PROJECT_PLUGIN_DIR, folder);+ mkdirSync(path.join(dir, 'src'), { recursive: true });+ writeFileSync(path.join(dir, 'plugin.json'), typeof manifest === 'string' ? manifest : JSON.stringify(manifest));+ if (entry !== undefined) writeFileSync(path.join(dir, 'src', 'editor.ts'), entry);+ return dir;+};++beforeAll(() => {+ scratch = mkdtempSync(path.join(tmpdir(), 'estella-plugins-'));+ userData = mkdtempSync(path.join(tmpdir(), 'estella-userdata-'));+});+afterAll(() => {+ rmSync(scratch, { recursive: true, force: true });+ rmSync(userData, { recursive: true, force: true });+});++describe('plugin discovery', () => {+ it('finds the sample plugin shipped with the sprite-animation example', async () => {+ const found = await discoverPlugins(SAMPLE_PROJECT, userData);+ const sample = found.find((p) => p.id === SAMPLE_ID);+ expect(sample, 'sample plugin missing from examples/sprite-animation').toBeDefined();+ expect(sample!.error).toBeUndefined();+ expect(sample!.scope).toBe('project');+ expect(sample!.manifest?.main?.editor).toBe('src/editor.ts');+ });++ it('reports a broken manifest instead of dropping the folder', async () => {+ writePlugin(scratch, 'broken-json', '{ not json');+ writePlugin(scratch, 'no-id', { name: 'x', version: '1.0.0', main: { editor: 'src/editor.ts' } });+ mkdirSync(path.join(scratch, PROJECT_PLUGIN_DIR, 'not-a-plugin'), { recursive: true });++ const found = await discoverPlugins(scratch, userData);+ const byFolder = new Map(found.map((p) => [path.basename(p.dir), p]));+ expect(byFolder.get('broken-json')?.error).toMatch(/not valid JSON/);+ expect(byFolder.get('no-id')?.error).toMatch(/`id`/);+ expect(byFolder.get('not-a-plugin')?.error).toMatch(/no plugin.json/);+ // Reported, every one of them — that's the point.+ expect(found.length).toBeGreaterThanOrEqual(3);+ });++ it('ignores dot-prefixed folders (the generated typings sidecar)', async () => {+ mkdirSync(path.join(scratch, PROJECT_PLUGIN_DIR, '.types'), { recursive: true });+ const found = await discoverPlugins(scratch, userData);+ expect(found.some((p) => path.basename(p.dir) === '.types')).toBe(false);+ });++ it('lets a project plugin shadow a user plugin of the same id, and says so', async () => {+ const shared = { id: 'acme.dup', name: 'Dup', version: '1.0.0', main: { editor: 'src/editor.ts' } };+ writePlugin(scratch, 'dup', shared, 'export default { activate() {} }');+ const userDir = path.join(userData, 'plugins', 'dup');+ mkdirSync(userDir, { recursive: true });+ writeFileSync(path.join(userDir, 'plugin.json'), JSON.stringify(shared));++ const found = await discoverPlugins(scratch, userData);+ const dups = found.filter((p) => p.id === 'acme.dup');+ expect(dups).toHaveLength(2); // both listed+ expect(dups.find((p) => p.scope === 'project')!.shadowedBy).toBeUndefined();+ expect(dups.find((p) => p.scope === 'user')!.shadowedBy).toBe('project');+ });++ it('returns nothing (rather than throwing) with no project open', async () => {+ await expect(discoverPlugins(null, path.join(userData, 'absent'))).resolves.toEqual([]);+ });+});++describe('plugin compilation', () => {+ it('compiles the sample plugin to a CJS module with host imports left external', async () => {+ const dir = path.join(SAMPLE_PROJECT, PROJECT_PLUGIN_DIR, SAMPLE_ID);+ const built = await compilePlugin(dir, 'src/editor.ts');+ expect(built.errors).toEqual([]);+ expect(built.ok).toBe(true);+ // CJS, because the renderer evaluates it with an injected `require` — that's+ // how React and the SDK stay the HOST's instances.+ expect(built.code).toMatch(/module\.exports|exports\./);+ // The API import must survive as a require, not be bundled in.+ expect(built.code).toMatch(/require\("@estella\/editor-api"\)/);+ }, 30_000);++ it('reports a syntax error rather than throwing', async () => {+ const dir = writePlugin(scratch, 'bad-syntax', { id: 'acme.bad', name: 'Bad', version: '1.0.0', main: { editor: 'src/editor.ts' } }, 'export default {{{');+ const built = await compilePlugin(dir, 'src/editor.ts');+ expect(built.ok).toBe(false);+ expect(built.errors.join(' ')).toMatch(/Expected|Unexpected/);+ }, 30_000);++ it('reports a missing entry file', async () => {+ const dir = writePlugin(scratch, 'no-entry', { id: 'acme.noentry', name: 'NE', version: '1.0.0', main: { editor: 'src/editor.ts' } });+ const built = await compilePlugin(dir, 'src/nope.ts');+ expect(built.ok).toBe(false);+ expect(built.errors[0]).toMatch(/entry not found/);+ });+});diff --git a/desktop/tests/plugin-manifest.test.ts b/desktop/tests/plugin-manifest.test.tsnew file mode 100644index 000000000..9ca5596ed--- /dev/null+++ b/desktop/tests/plugin-manifest.test.ts@@ -0,0 +1,111 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file plugin.json validation + the `engines.editor` range check. Both are the+ * gate between "a folder the user wrote" and "code the editor runs", so the+ * rules that matter here are: a bad manifest is NAMED not dropped, and an+ * unreadable version range is refused rather than guessed at.+ */+import { describe, it, expect } from 'vitest';+import { validateManifest, satisfiesEditorRange, resolveLocalized } from '@/plugins/manifest';++const ok = (raw: unknown) => {+ const r = validateManifest(raw);+ if ('error' in r) throw new Error(`expected valid, got: ${r.error}`);+ return r.manifest;+};+const err = (raw: unknown): string => {+ const r = validateManifest(raw);+ if (!('error' in r)) throw new Error('expected an error');+ return r.error;+};++const base = {+ id: 'acme.tools',+ name: 'Acme Tools',+ version: '1.0.0',+ main: { editor: 'src/editor.ts' },+};++describe('validateManifest', () => {+ it('accepts a minimal manifest', () => {+ expect(ok(base).id).toBe('acme.tools');+ });++ it('accepts localized name + description', () => {+ const m = ok({ ...base, name: { en: 'Acme', 'zh-CN': '顶针' }, description: { en: 'd' } });+ expect(resolveLocalized(m.name, 'zh-CN')).toBe('顶针');+ expect(resolveLocalized(m.name, 'de')).toBe('Acme'); // falls back to en+ });++ it('requires a dotted lowercase id', () => {+ expect(err({ ...base, id: 'Tools' })).toMatch(/dotted, lowercase/);+ expect(err({ ...base, id: 'tools' })).toMatch(/dotted, lowercase/); // needs a namespace+ expect(err({ ...base, id: 'acme..tools' })).toMatch(/dotted, lowercase/);+ expect(ok({ ...base, id: 'acme.level-tools.extra' }).id).toBe('acme.level-tools.extra');+ });++ it('requires a name, a semver version, and an entry point', () => {+ expect(err({ ...base, name: '' })).toMatch(/`name`/);+ expect(err({ ...base, name: { zh: 'x' } })).toMatch(/`en` string/);+ expect(err({ ...base, version: '1.0' })).toMatch(/`version`/);+ expect(err({ ...base, main: {} })).toMatch(/no entry point/);+ expect(err({ ...base, main: { editor: 42 } })).toMatch(/`main.editor`/);+ });++ it('refuses an entry that escapes the plugin folder', () => {+ expect(err({ ...base, main: { editor: '../../elsewhere.ts' } })).toMatch(/stay inside/);+ });++ it('rejects an unknown capability by name', () => {+ expect(err({ ...base, capabilities: ['fs:project', 'gpu'] })).toMatch(/unknown capability "gpu"/);+ expect(ok({ ...base, capabilities: ['fs:project', 'net'] }).capabilities).toEqual(['fs:project', 'net']);+ });++ it('reports a non-object manifest instead of throwing', () => {+ expect(err(null)).toMatch(/JSON object/);+ expect(err('nope')).toMatch(/JSON object/);+ expect(err([])).toMatch(/`id`/); // an array is an object, so it fails on id+ });+});++describe('satisfiesEditorRange', () => {+ it('accepts * always', () => {+ expect(satisfiesEditorRange('0.33.0', '*').ok).toBe(true);+ });++ it('treats MINOR as the breaking axis below 1.0 (npm caret semantics)', () => {+ // The editor is pre-1.0, so ^0.33 must NOT match 0.34 — that's exactly the+ // case where a plugin written against an older API would silently load.+ expect(satisfiesEditorRange('0.33.0', '^0.33').ok).toBe(true);+ expect(satisfiesEditorRange('0.33.7', '^0.33').ok).toBe(true);+ expect(satisfiesEditorRange('0.34.0', '^0.33').ok).toBe(false);+ expect(satisfiesEditorRange('0.32.9', '^0.33').ok).toBe(false);+ });++ it('treats MAJOR as the breaking axis at 1.0 and above', () => {+ expect(satisfiesEditorRange('1.4.0', '^1.2').ok).toBe(true);+ expect(satisfiesEditorRange('2.0.0', '^1.2').ok).toBe(false);+ });++ it('supports >= and exact', () => {+ expect(satisfiesEditorRange('0.34.0', '>=0.33').ok).toBe(true);+ expect(satisfiesEditorRange('0.32.0', '>=0.33').ok).toBe(false);+ expect(satisfiesEditorRange('0.33.0', '0.33.0').ok).toBe(true);+ expect(satisfiesEditorRange('0.33.1', '0.33.0').ok).toBe(false);+ });++ it('refuses a range it cannot read rather than guessing', () => {+ // Guessing at "~0.33" or "0.33.x" would load a plugin against an API it was+ // not written for; saying so is the only safe answer.+ const r = satisfiesEditorRange('0.33.0', '~0.33');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toMatch(/cannot read version range/);+ });++ it('explains itself when it says no', () => {+ const r = satisfiesEditorRange('0.34.0', '^0.33');+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toBe('needs editor ^0.33, running 0.34.0');+ });+});diff --git a/examples/sprite-animation/.esengine/plugins/estella.scene-report/plugin.json b/examples/sprite-animation/.esengine/plugins/estella.scene-report/plugin.jsonnew file mode 100644index 000000000..b07e03c87--- /dev/null+++ b/examples/sprite-animation/.esengine/plugins/estella.scene-report/plugin.json@@ -0,0 +1,12 @@+{+ "id": "estella.scene-report",+ "name": { "en": "Scene Report", "zh-CN": "场景报告" },+ "version": "1.0.0",+ "publisher": "estella",+ "description": {+ "en": "A worked example of an editor plugin: a command, a panel, and a setting.",+ "zh-CN": "编辑器插件的完整示例:一条命令、一个面板、一项设置。"+ },+ "engines": { "editor": "^0.33" },+ "main": { "editor": "src/editor.ts" }+}diff --git a/examples/sprite-animation/.esengine/plugins/estella.scene-report/src/editor.ts b/examples/sprite-animation/.esengine/plugins/estella.scene-report/src/editor.tsnew file mode 100644index 000000000..163586acd--- /dev/null+++ b/examples/sprite-animation/.esengine/plugins/estella.scene-report/src/editor.ts@@ -0,0 +1,141 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * Scene Report — a worked example of an Estella editor plugin.+ *+ * It shows the three contribution kinds a plugin usually needs, and the two rules+ * that matter:+ *+ * - Register through `ctx`, never through a global. Every registration is+ * attributed to this plugin, which is what lets the editor unload or reload it+ * cleanly (try editing this file — the editor recompiles and re-activates it).+ *+ * - Mutate the scene through `ctx.scene`. Those writes go through the editor's+ * command layer, so they land in the undo history and survive Play → Stop.+ * Reaching around it to the live engine would lose both.+ *+ * Written in TypeScript with no build step: the editor compiles it, and the typings+ * come from `.esengine/plugins/.types/editor-api.d.ts`, which the editor keeps in+ * sync with itself (see tsconfig.json next to this file).+ */+import { definePlugin, type PluginContext } from '@estella/editor-api';++/** Count entities and how often each component type appears. */+function summarize(ctx: PluginContext): { entities: number; components: Map<string, number> } {+ const components = new Map<string, number>();+ let entities = 0;+ const walk = (nodes: ReturnType<PluginContext['scene']['getSceneTree']>): void => {+ for (const node of nodes) {+ entities++;+ for (const type of ctx.scene.getEntity(node.id)?.components ?? []) {+ components.set(type, (components.get(type) ?? 0) + 1);+ }+ if (node.children?.length) walk(node.children);+ }+ };+ walk(ctx.scene.getSceneTree());+ return { entities, components };+}++export default definePlugin({+ activate(ctx: PluginContext) {+ // — A command. Lands in the command palette and in the Tools menu; its label,+ // shortcut, and enablement all come from this one declaration. —+ ctx.commands.register({+ id: 'estella.scene-report.logSummary',+ title: { en: 'Log Scene Summary', 'zh-CN': '输出场景摘要' },+ category: { en: 'Scene Report', 'zh-CN': '场景报告' },+ menu: 'tools',+ run: () => {+ const { entities, components } = summarize(ctx);+ ctx.log.info(`${entities} entities, ${components.size} distinct component types`);+ ctx.ui.toast(`Scene has ${entities} entities`, 'info');+ },+ });++ // — A command that WRITES. One transact() call is one undo step, however many+ // edits it makes: ⌘Z takes all of it back together. —+ ctx.commands.register({+ id: 'estella.scene-report.nameUnnamed',+ title: { en: 'Name Unnamed Entities', 'zh-CN': '命名未命名实体' },+ category: { en: 'Scene Report', 'zh-CN': '场景报告' },+ menu: 'tools',+ isEnabled: () => ctx.scene.getSceneTree().length > 0,+ run: () => {+ ctx.scene.transact('Name Unnamed Entities', () => {+ let n = 0;+ for (const node of ctx.scene.getSceneTree()) {+ if (/^entity$/i.test(node.name)) ctx.scene.renameEntity(node.id, `Entity ${++n}`);+ }+ });+ },+ });++ // — A setting. Appears under Settings ▸ Plugins ▸ Scene Report. —+ ctx.settings.register({+ id: 'estella.scene-report.showComponents',+ type: 'boolean',+ default: true,+ label: { en: 'Show component breakdown', 'zh-CN': '显示组件明细' },+ description: {+ en: 'List component counts in the Scene Report panel.',+ 'zh-CN': '在场景报告面板中列出组件数量。',+ },+ });++ // — A panel. `mount` gets a plain host element and returns its teardown; the+ // editor owns the tab, the dirty dot, the error boundary, and pop-out. Style+ // against the editor's CSS variables and it matches the surrounding chrome. —+ ctx.panels.register({+ id: 'estella.scene-report.panel',+ title: { en: 'Scene Report', 'zh-CN': '场景报告' },+ placement: 'bottom',+ mount: (host) => {+ const root = document.createElement('div');+ root.style.cssText = 'padding:10px;display:flex;flex-direction:column;gap:8px;font-size:11px;color:var(--text)';+ host.append(root);++ const render = (): void => {+ const { entities, components } = summarize(ctx);+ const showComponents = ctx.settings.get<boolean>('estella.scene-report.showComponents') ?? true;+ const selection = ctx.scene.getSelection();+ const selected = selection != null ? ctx.scene.getEntity(selection) : null;++ root.replaceChildren();+ const line = (label: string, value: string): void => {+ const row = document.createElement('div');+ row.style.cssText = 'display:flex;gap:8px';+ const k = document.createElement('span');+ k.style.cssText = 'color:var(--text-dim);min-width:110px';+ k.textContent = label;+ const v = document.createElement('span');+ v.style.cssText = 'color:var(--text-hi);font-weight:600';+ v.textContent = value;+ row.append(k, v);+ root.append(row);+ };++ line('Entities', String(entities));+ line('Scene', ctx.project.currentScene() ?? '—');+ line('Selected', selected ? `${selected.name} (${selected.components.length} components)` : '—');+ if (showComponents) {+ const list = [...components].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));+ for (const [type, count] of list) line(` ${type}`, String(count));+ }+ };++ render();+ // Re-render on the events that change what's displayed. Both handlers are+ // retracted when the plugin unloads, so no listener outlives it.+ const offSelection = ctx.events.on('selectionChanged', render);+ const offScene = ctx.events.on('sceneChanged', render);+ return () => {+ offSelection.dispose();+ offScene.dispose();+ };+ },+ });++ ctx.log.info('scene report ready');+ },+});diff --git a/examples/sprite-animation/.esengine/plugins/estella.scene-report/tsconfig.json b/examples/sprite-animation/.esengine/plugins/estella.scene-report/tsconfig.jsonnew file mode 100644index 000000000..ea31ee9d8--- /dev/null+++ b/examples/sprite-animation/.esengine/plugins/estella.scene-report/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2020", "DOM"],+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "jsx": "react-jsx",+ // The editor writes these typings and keeps them matching the running version,+ // so there is nothing to install and no copy that can go stale.+ "paths": {+ "@estella/editor-api": ["../.types/editor-api.d.ts"]+ }+ },+ "include": ["src"]+}