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): a plugin can be a package the project depends on
yhh5c325305df11
diff --git a/desktop/electron/pluginHost.ts b/desktop/electron/pluginHost.tsindex d2f448523..895881e9a 100644--- a/desktop/electron/pluginHost.ts+++ b/desktop/electron/pluginHost.ts@@ -6,11 +6,12 @@** 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.+ * 1. DISCOVERY. Plugins live on disk in three scopes — inside the project+ * (`.esengine/plugins/`, versioned with it, shared by the team), installed+ * from npm (a direct dependency shipping a `plugin.json`), and per-user+ * (`<userData>/plugins/`, personal tools across projects). On an id collision+ * the higher-priority scope wins 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@@ -41,8 +42,9 @@ 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';+/** Which scope a plugin was found in. On an id collision the first of+ * project → package → user wins, and the others say who took it. */+export type PluginScope = 'project' | 'package' | 'user';/*** What kind of project-supplied code an entry is.@@ -86,6 +88,23 @@ const EDITOR_EXTERNALS = ['react', 'react-dom', 'react-dom/client', 'react/jsx-r// Discovery// =============================================================================+/** One plugin folder read into a record. `fallbackId` names it while the manifest+ * cannot: an unreadable plugin still has to appear, carrying the reason. */+async function readOnePlugin(pluginDir: string, scope: PluginScope, fallbackId: string): Promise<DiscoveredPlugin> {+ const base = { kind: 'plugin' as const, scope, dir: pluginDir };+ const manifestFile = path.join(pluginDir, 'plugin.json');+ if (!existsSync(manifestFile)) return { ...base, id: fallbackId, error: 'folder has no plugin.json' };+ try {+ const parsed: unknown = JSON.parse(await readFile(manifestFile, 'utf8'));+ const result = validateManifest(parsed);+ return 'error' in result+ ? { ...base, id: fallbackId, error: result.error }+ : { ...base, id: result.manifest.id, manifest: result.manifest };+ } catch (e) {+ return { ...base, id: fallbackId, error: `plugin.json is not valid JSON (${String(e)})` };+ }+}+async function readPluginDir(dir: string, scope: PluginScope): Promise<DiscoveredPlugin[]> {if (!existsSync(dir)) return [];let names: string[];@@ -99,25 +118,32 @@ async function readPluginDir(dir: string, scope: PluginScope): Promise<Discovere} catch {return [];}+ return Promise.all(names.map((name) => readOnePlugin(path.join(dir, name), scope, name)));+}++/**+ * Plugins the project installed from npm. Only DIRECT dependencies count: editor+ * code arriving because something else depends on it is not something the project+ * asked for. A `plugin.json` is the test, not the `estella-plugin-` name, which no+ * scoped package could satisfy.+ */+async function readPackagePlugins(root: string): Promise<DiscoveredPlugin[]> {+ let names: string[];+ try {+ const pkg = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')) as {+ dependencies?: Record<string, string>;+ devDependencies?: Record<string, string>;+ };+ names = [...new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})])].sort();+ } catch {+ return []; // no package.json, or unreadable — a project with no npm dependencies+ }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, kind: 'plugin', 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, kind: 'plugin', scope, dir: pluginDir, error: result.error });- } else {- out.push({ id: result.manifest.id, kind: 'plugin', scope, dir: pluginDir, manifest: result.manifest });- }- } catch (e) {- out.push({ id: name, kind: 'plugin', scope, dir: pluginDir, error: `plugin.json is not valid JSON (${String(e)})` });- }+ const dir = path.join(root, 'node_modules', ...name.split('/'));+ // An ordinary dependency is not a broken plugin, so it is skipped in silence.+ if (!existsSync(path.join(dir, 'plugin.json'))) continue;+ out.push(await readOnePlugin(dir, 'package', name));}return out;}@@ -161,20 +187,25 @@ async function readPlatformProfiles(root: string): Promise<DiscoveredPlugin[]> {}/**- * Every piece of project-supplied code 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.+ * Every piece of project-supplied code visible right now, most specific scope+ * first: a folder in this project beats a package it depends on, and both beat a+ * personal one installed for every project. A shadowed plugin is listed carrying+ * `shadowedBy` rather than dropped, so the UI can say why it isn't running.*/export async function discoverPlugins(root: string | null, userDataDir: string): Promise<DiscoveredPlugin[]> {const project = root ? await readPluginDir(path.join(root, PROJECT_PLUGIN_DIR), 'project') : [];const platforms = root ? await readPlatformProfiles(root) : [];+ const packages = root ? await readPackagePlugins(root) : [];const user = await readPluginDir(path.join(userDataDir, USER_PLUGIN_DIR), 'user');- const claimed = new Set(project.map((p) => p.id));- return [- ...project,- ...platforms,- ...user.map((p) => (claimed.has(p.id) ? { ...p, shadowedBy: 'project' as PluginScope } : p)),- ];+ const claimed = new Map(project.map((p) => [p.id, p.scope]));+ const resolve = (list: DiscoveredPlugin[]): DiscoveredPlugin[] =>+ list.map((p) => {+ const by = claimed.get(p.id);+ if (by !== undefined) return { ...p, shadowedBy: by };+ claimed.set(p.id, p.scope);+ return p;+ });+ return [...project, ...platforms, ...resolve(packages), ...resolve(user)];}// =============================================================================diff --git a/desktop/src/i18n/messages/plugins.ts b/desktop/src/i18n/messages/plugins.tsindex ef147af09..84eb0a965 100644--- a/desktop/src/i18n/messages/plugins.ts+++ b/desktop/src/i18n/messages/plugins.ts@@ -37,6 +37,7 @@ export const pluginMessages = defineMessages({'plug.phase.shadowed': { en: 'Shadowed', zh: '被遮蔽' },'plug.scope.project': { en: 'project', zh: '项目' },+ 'plug.scope.package': { en: 'package', zh: '依赖包' },'plug.scope.user': { en: 'user', zh: '用户' },// The trust gate. Deliberately plain about what loading a plugin means: it runsdiff --git a/desktop/src/panels/PluginsPanel.tsx b/desktop/src/panels/PluginsPanel.tsxindex ee2ad2768..773077794 100644--- a/desktop/src/panels/PluginsPanel.tsx+++ b/desktop/src/panels/PluginsPanel.tsx@@ -39,6 +39,12 @@ const PHASE_LABEL: Record<PluginPhase, MsgKey> = {shadowed: 'plug.phase.shadowed',};+const SCOPE_LABEL: Record<PluginRecord['scope'], MsgKey> = {+ project: 'plug.scope.project',+ package: 'plug.scope.package',+ user: 'plug.scope.user',+};+const CAPABILITY_LABEL: Record<string, MsgKey> = {'fs:project': 'plug.cap.fsProject',net: 'plug.cap.net',@@ -150,7 +156,7 @@ function PluginRow({ record }: { record: PluginRecord }) {<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__scope">{t(SCOPE_LABEL[record.scope])}</span><span className="plug-row__spacer" /><PhaseChip phase={record.phase} /></div>diff --git a/desktop/src/plugins/PluginHost.ts b/desktop/src/plugins/PluginHost.tsindex 9c5fd6f2c..5f98abde3 100644--- a/desktop/src/plugins/PluginHost.ts+++ b/desktop/src/plugins/PluginHost.ts@@ -68,7 +68,7 @@ export interface PluginRecord {/** What kind of project-supplied code this is. A `project-platform` row has no* activation — approving it only permits the export pipeline to import it. */kind: 'plugin' | 'project-platform';- scope: 'project' | 'user';+ scope: 'project' | 'package' | 'user';dir: string;phase: PluginPhase;/** Why it's failed / incompatible / shadowed. */diff --git a/desktop/tests/build-scripts.test.ts b/desktop/tests/build-scripts.test.tsindex 3dfc272bf..a604916ce 100644--- a/desktop/tests/build-scripts.test.ts+++ b/desktop/tests/build-scripts.test.ts@@ -55,6 +55,42 @@ describe('buildProjectScripts (E8-1)', () => {expect(out).toContain('amplitude');});+ it('bundles a plugin installed from npm, sharing the one engine instance', async () => {+ // A plugin's runtime half is an ordinary dependency, but it has to reach+ // the same engine the game runs on: a copy bundled inside the package is a+ // second component registry, and its systems register into nothing.+ const proj = mkdtempSync(path.join(tmpdir(), 'estella-pkgruntime-'));+ try {+ const pkg = path.join(proj, 'node_modules', 'estella-plugin-demo');+ mkdirSync(path.join(pkg, 'runtime'), { recursive: true });+ writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify({ name: 'estella-plugin-demo', version: '1.0.0', type: 'module', main: 'runtime/index.js' }),+ );+ writeFileSync(+ path.join(pkg, 'runtime', 'index.js'),+ `import { defineComponent } from 'esengine';\n`+ + `export const DemoService = defineComponent('DemoService', { level: 1 });\n`,+ );+ mkdirSync(path.join(proj, 'src'), { recursive: true });+ // The entry imports ONLY the package, so a surviving bare `esengine`+ // import can only have come from inside it.+ writeFileSync(+ path.join(proj, 'src', 'main.ts'),+ `import { DemoService } from 'estella-plugin-demo';\nvoid DemoService;\n`,+ );++ const res = await buildProjectScripts(proj);+ expect(res.errors).toEqual([]);+ expect(res.ok).toBe(true);+ const out = readFileSync(res.outputPath!, 'utf8');+ expect(out).toContain('DemoService'); // the package's code is IN the bundle+ expect(out).toMatch(/from\s*["']esengine["']/); // …and its engine import is not+ } finally {+ rmSync(proj, { recursive: true, force: true });+ }+ });+it('reports a clean failure when the entry is missing', async () => {const empty = mkdtempSync(path.join(tmpdir(), 'estella-empty-'));try {diff --git a/desktop/tests/plugin-loader.test.ts b/desktop/tests/plugin-loader.test.tsindex 1a5573b16..871eb1c33 100644--- a/desktop/tests/plugin-loader.test.ts+++ b/desktop/tests/plugin-loader.test.ts@@ -11,7 +11,7 @@* 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 { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -22,6 +22,8 @@ const SAMPLE_PROJECT = path.resolve(HERE, '../../examples/sprite-animation');const SAMPLE_ID = 'estella.scene-report';let scratch: string;+/** A second project, for the npm-installed plugins (its own package.json). */+let pkgRoot: string;/** A throwaway userData dir, so the real one is never read or written. */let userData: string;@@ -35,11 +37,11 @@ const writePlugin = (root: string, folder: string, manifest: unknown, entry?: stbeforeAll(() => {scratch = mkdtempSync(path.join(tmpdir(), 'estella-plugins-'));+ pkgRoot = mkdtempSync(path.join(tmpdir(), 'estella-pkgplugins-'));userData = mkdtempSync(path.join(tmpdir(), 'estella-userdata-'));});afterAll(() => {- rmSync(scratch, { recursive: true, force: true });- rmSync(userData, { recursive: true, force: true });+ for (const dir of [scratch, pkgRoot, userData]) rmSync(dir, { recursive: true, force: true });});describe('plugin discovery', () => {@@ -91,6 +93,82 @@ describe('plugin discovery', () => {});});+describe('plugins installed from npm', () => {+ /** A package in the project's node_modules, optionally declared as a dependency. */+ const writePackage = (root: string, name: string, manifest: unknown, declared = true): string => {+ const dir = path.join(root, 'node_modules', ...name.split('/'));+ mkdirSync(dir, { recursive: true });+ if (manifest !== undefined) {+ writeFileSync(path.join(dir, 'plugin.json'), typeof manifest === 'string' ? manifest : JSON.stringify(manifest));+ }+ writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, version: '1.0.0' }));+ if (declared) {+ const file = path.join(root, 'package.json');+ const pkg = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as { dependencies?: Record<string, string> }) : {};+ pkg.dependencies = { ...pkg.dependencies, [name]: '^1.0.0' };+ writeFileSync(file, JSON.stringify(pkg));+ }+ return dir;+ };+ const manifest = (id: string) => ({ id, name: id, version: '1.0.0', main: { editor: 'editor/index.js' } });++ it('finds a plugin the project depends on', async () => {+ writePackage(pkgRoot, 'estella-plugin-tiled', manifest('estella.tiled'));+ const found = await discoverPlugins(pkgRoot, userData);+ const hit = found.find((p) => p.id === 'estella.tiled');+ expect(hit?.scope).toBe('package');+ expect(hit?.error).toBeUndefined();+ expect(hit?.manifest?.main?.editor).toBe('editor/index.js');+ });++ it('finds one under a scope, which a name convention could not', async () => {+ writePackage(pkgRoot, '@acme/estella-plugin-yarn', manifest('acme.yarn'));+ const found = await discoverPlugins(pkgRoot, userData);+ expect(found.find((p) => p.id === 'acme.yarn')?.scope).toBe('package');+ });++ it('passes over an ordinary dependency in silence', async () => {+ // Most dependencies are not plugins. Reporting each one as a broken plugin+ // would bury the list under everything the project happens to install.+ writePackage(pkgRoot, 'left-pad', undefined);+ const found = await discoverPlugins(pkgRoot, userData);+ expect(found.some((p) => p.dir.endsWith('left-pad'))).toBe(false);+ });++ it('will not run a plugin the project never asked for', async () => {+ // Installed as somebody else's transitive dependency. Editor code arriving+ // because a package you did depend on depends on it is not a decision the+ // project made.+ writePackage(pkgRoot, 'estella-plugin-sneaky', manifest('sneaky.tools'), false);+ const found = await discoverPlugins(pkgRoot, userData);+ expect(found.some((p) => p.id === 'sneaky.tools')).toBe(false);+ });++ it('reports a package whose manifest is broken', async () => {+ writePackage(pkgRoot, 'estella-plugin-broken', '{ not json');+ const found = await discoverPlugins(pkgRoot, userData);+ const hit = found.find((p) => p.dir.endsWith('estella-plugin-broken'));+ expect(hit?.error).toMatch(/not valid JSON/);+ // Named by its package, since the manifest could not name it.+ expect(hit?.id).toBe('estella-plugin-broken');+ });++ it('is shadowed by a plugin folder in the project, and shadows a user one', async () => {+ const shared = 'acme.both';+ writePackage(pkgRoot, 'estella-plugin-both', manifest(shared));+ writePlugin(pkgRoot, 'both', { ...manifest(shared), main: { editor: 'src/editor.ts' } }, 'export default { activate() {} }');+ const userDir = path.join(userData, 'plugins', 'both');+ mkdirSync(userDir, { recursive: true });+ writeFileSync(path.join(userDir, 'plugin.json'), JSON.stringify(manifest(shared)));++ const found = (await discoverPlugins(pkgRoot, userData)).filter((p) => p.id === shared);+ expect(found).toHaveLength(3); // all three listed+ expect(found.find((p) => p.scope === 'project')!.shadowedBy).toBeUndefined();+ expect(found.find((p) => p.scope === 'package')!.shadowedBy).toBe('project');+ expect(found.find((p) => p.scope === 'user')!.shadowedBy).toBe('project');+ });+});+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);diff --git a/docs/astro/src/content/docs/extending/editor-plugins.mdx b/docs/astro/src/content/docs/extending/editor-plugins.mdxindex 243be9740..aaf4ffb06 100644--- a/docs/astro/src/content/docs/extending/editor-plugins.mdx+++ b/docs/astro/src/content/docs/extending/editor-plugins.mdx@@ -134,6 +134,47 @@ Approval covers that version from that folder. A new version, or a differentfolder claiming the same id, asks again.</Aside>+## From npm++A plugin can also be an npm package the project depends on:++```bash+npm install estella-plugin-tiled+```++Any **direct** dependency that ships a `plugin.json` at its root is a plugin. The+editor lists it like any other, needing trust the same way — and because approval+covers a version, an update asks again.++A package is also the way to ship a plugin's two halves together: the editor half+the manifest points at, and runtime code the game imports itself.++<FileTree>+- node_modules/estella-plugin-tiled/+ - package.json+ - plugin.json `"main": { "editor": "editor/index.js" }`+ - editor/+ - index.js+ - runtime/+ - index.js+</FileTree>++```ts title="src/main.ts"+import { TiledPlugin } from 'estella-plugin-tiled';++app.use(TiledPlugin);+```++The runtime half needs no mechanism of its own — it is an ordinary module, bundled+into your game like the rest of `src/`. Declare `esengine` as a **peer**+dependency, never a regular one: the project's bundler leaves every `esengine`+import external so the whole game shares one engine instance, and a copy vendored+inside your package would be a second component registry whose systems register+into nothing.++Only direct dependencies are considered. A package that arrives because something+else depends on it is not something the project asked to run in its editor.+## TypingsThe editor writes `@estella/editor-api`'s typings into your project at@@ -349,8 +390,11 @@ mysterious.- **`<project>/.esengine/plugins/<id>/`** — versioned with the project and sharedwith your team. This is the usual place.-- **`<userData>/plugins/<id>/`** — your own tools, across every project. A project- plugin with the same id takes precedence, and the shadowed one says so.+- **an npm package the project depends on** — see [From npm](#from-npm) above.+- **`<userData>/plugins/<id>/`** — your own tools, across every project.++On an id collision the first of those three wins, and the others are listed saying+who took it.## Project platform profilesdiff --git a/docs/astro/src/content/docs/zh-cn/extending/editor-plugins.mdx b/docs/astro/src/content/docs/zh-cn/extending/editor-plugins.mdxindex 8133f5025..25dd8ae57 100644--- a/docs/astro/src/content/docs/zh-cn/extending/editor-plugins.mdx+++ b/docs/astro/src/content/docs/zh-cn/extending/editor-plugins.mdx@@ -118,6 +118,44 @@ export default definePlugin({批准只对应那个版本、那个目录。新版本,或另一个目录声称同一 id,都会重新询问。</Aside>+## 来自 npm++插件也可以是项目依赖的一个 npm 包:++```bash+npm install estella-plugin-tiled+```++任何**直接依赖**,只要根目录带一个 `plugin.json`,就是一个插件。编辑器会像列出其它+插件一样列出它,同样需要授信——而授信是按版本记的,所以升级会重新询问。++一个包也是把插件两半一起发布的方式:清单指向的编辑器那半,和游戏自己 import 的运行+时那半。++<FileTree>+- node_modules/estella-plugin-tiled/+ - package.json+ - plugin.json `"main": { "editor": "editor/index.js" }`+ - editor/+ - index.js+ - runtime/+ - index.js+</FileTree>++```ts title="src/main.ts"+import { TiledPlugin } from 'estella-plugin-tiled';++app.use(TiledPlugin);+```++运行时那半不需要任何专门机制——它就是一个普通模块,和 `src/` 里的其余代码一起被打包+进你的游戏。把 `esengine` 声明为 **peer** 依赖,不要声明成普通依赖:项目的打包器会把+每一处 `esengine` import 留成 external,整个游戏共用一份引擎实例;而包里自带的那份副本+会是第二个组件注册表,它注册进去的系统等于注册进了虚空。++只有直接依赖会被考虑。因为别的包依赖它才被装进来的包,不是项目要求在自己编辑器里运行+的东西。+## 类型定义编辑器每次打开项目时,都会把 `@estella/editor-api` 的类型写进@@ -302,8 +340,10 @@ ctx.scene.transact('Rename Markers', () => {## 插件放在哪- **`<项目>/.esengine/plugins/<id>/`**——随项目版本管理,与团队共享。通常放这里。-- **`<userData>/plugins/<id>/`**——你个人的工具,跨所有项目。同 id 时项目里的那个- 优先,被遮蔽的那个会说明原因。+- **项目依赖的一个 npm 包**——见上面的 [来自 npm](#来自-npm)。+- **`<userData>/plugins/<id>/`**——你个人的工具,跨所有项目。++同 id 时,这三处按上面的顺序取第一个,其余的会列出来并说明是谁占了。## 项目平台配置