Skip to content

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.

feat(editor): a plugin can teach the editor to read a new file format

yhhc3848caed30f
diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.ts
index 5af396ede..9fa3a4e68 100644
--- a/desktop/src/i18n/messages/content.ts
+++ b/desktop/src/i18n/messages/content.ts
@@ -76,6 +76,7 @@ export const contentMessages = defineMessages({
'cb.menuNewAnimatorController': { en: 'New Animation Controller', zh: '新建动画控制器' },
'cb.menuNewBehaviorTree': { en: 'New Behavior Tree', zh: '新建行为树' },
'cb.menuShowInExplorer': { en: 'Show in Explorer', zh: '在资源管理器中显示' },
+ 'cb.menuReimport': { en: 'Reimport', zh: '重新导入' },
'cb.delivery': { en: 'Delivery', zh: '交付方式' },
'cb.deliveryLocal': { en: 'Local (in package)', zh: '本地(打进包)' },
'cb.deliverySubpackage': { en: 'Subpackage (on-demand)', zh: '分包(按需)' },
diff --git a/desktop/src/i18n/messages/plugins.ts b/desktop/src/i18n/messages/plugins.ts
index 84eb0a965..b7136174b 100644
--- a/desktop/src/i18n/messages/plugins.ts
+++ b/desktop/src/i18n/messages/plugins.ts
@@ -74,6 +74,7 @@ export const pluginMessages = defineMessages({
'plug.kind.overlay': { en: 'Gizmo', zh: 'Gizmo' },
'plug.kind.inspector': { en: 'Inspector', zh: '检视器' },
'plug.kind.assetType': { en: 'Asset type', zh: '资产类型' },
+ 'plug.kind.importer': { en: 'Importer', zh: '导入器' },
'plug.kind.entityTemplate': { en: 'Entity', zh: '实体' },
'plug.kind.contextMenu': { en: 'Menu item', zh: '菜单项' },
'plug.kind.agentTool': { en: 'Agent tool', zh: 'Agent 工具' },
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 43e641729..e227c407d 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -20,6 +20,7 @@ import { formatBytes } from '@/project/sizeBudget';
import { openAssetOfType } from '@/project/assetOpen';
import { assetTypeRegistry } from '@/project/assetTypes';
import { contributedContextRows } from '@/plugins/contextMenus';
+import { hasImporter, runImporters } from '@/plugins/importers';
import { syncAssetPaths } from '@/project/assetPathSync';
import { findAssetUsagesOfAll, type AssetUsage } from '@/project/assetUsages';
import { deleteAssets } from '@/project/deleteAssets';
@@ -1090,6 +1091,9 @@ export function ContentBrowser() {
...(ref ? [{ label: t('cb.menuCopyReference'), onClick: () => copy(ref, t('cb.copiedReference')) }] : []),
...(entry.isDir ? [] : [{ label: t('cb.menuFindUsages'), onClick: () => setUsagesPath(path) }]),
{ label: t('cb.menuShowInExplorer'), onClick: () => void showInExplorer(path) },
+ // Only where something claims to convert this file — a Reimport that reruns
+ // nothing would be a menu row promising work the editor cannot do.
+ ...(hasImporter(path) ? [{ label: t('cb.menuReimport'), onClick: () => void runImporters([path]) } as MenuItem] : []),
...contributedContextRows('content/item', { path }),
{ sep: true },
{ label: t('ui.delete'), danger: true, onClick: () => void remove(selectedAssets.has(path) && selectedAssets.size > 1 ? [...selectedAssets] : [path]) },
diff --git a/desktop/src/panels/PluginsPanel.tsx b/desktop/src/panels/PluginsPanel.tsx
index 773077794..f536b9456 100644
--- a/desktop/src/panels/PluginsPanel.tsx
+++ b/desktop/src/panels/PluginsPanel.tsx
@@ -60,6 +60,7 @@ const KIND_LABEL: Record<ContributionKind, MsgKey> = {
overlay: 'plug.kind.overlay',
inspector: 'plug.kind.inspector',
assetType: 'plug.kind.assetType',
+ importer: 'plug.kind.importer',
entityTemplate: 'plug.kind.entityTemplate',
contextMenu: 'plug.kind.contextMenu',
agentTool: 'plug.kind.agentTool',
diff --git a/desktop/src/plugins/context.ts b/desktop/src/plugins/context.ts
index 281956b21..dfaad356d 100644
--- a/desktop/src/plugins/context.ts
+++ b/desktop/src/plugins/context.ts
@@ -25,6 +25,7 @@ import { entitySourceRegistry, prefabFromSpecs } from '@/engine/entitySources';
import { overlayRegistry, viewportProjection } from './overlays';
import { inspectorRegistry } from './inspector';
import { contextMenuRegistry } from './contextMenus';
+import { importerRegistry, runImporters } from './importers';
import { localizePlugin as localize } from './localize';
import { settingsRegistry } from '@/settings/registry';
import { useSettings } from '@/store/settingsStore';
@@ -42,7 +43,7 @@ import type { PointerInput as CorePointerInput } from '@/tools/EditorTool';
import type { PluginManifest, PluginCapability } from './manifest';
import { agentToolProblem, registerAgentTool, publishAgentTools } from './agentTools';
import type {
- AgentToolContribution,
+ AgentToolContribution, AssetImporterContribution,
AssetTypeContribution, CommandContribution, ContextMenuContribution, Disposable, EditorEvents,
EditorPlugin, EditorProjectApi, EditorSceneApi, EntityTemplateContribution, FieldValue,
InspectorContribution, OverlayContribution, PanelContribution, PluginContext,
@@ -197,6 +198,7 @@ export type ContributionKind =
| 'overlay'
| 'inspector'
| 'assetType'
+ | 'importer'
| 'entityTemplate'
| 'contextMenu'
| 'agentTool';
@@ -370,6 +372,28 @@ export function buildPluginContext(
inspectorRegistry.register(owner, { ...section, id: `${id}.${section.id}` }),
);
+ // A plugin callback that may be async: `guard` catches a throw, and a rejection
+ // is routed back through it so both failure modes reach the same reporting.
+ const guardAsync = async (what: string, fn: () => void | Promise<void>): Promise<void> => {
+ try {
+ await fn();
+ } catch (e) {
+ guard(what, () => { throw e; }, undefined);
+ }
+ };
+
+ const registerImporter = (importer: AssetImporterContribution): Disposable =>
+ noted(
+ 'importer',
+ `${id}.${importer.id}`,
+ importer.extensions.map((e) => `.${e}`).join(' '),
+ importerRegistry.register(owner, {
+ id: `${id}.${importer.id}`,
+ extensions: importer.extensions,
+ run: (path) => guardAsync(`import ${path}`, () => importer.import(path)),
+ }),
+ );
+
const registerAssetType = (type: AssetTypeContribution): Disposable =>
noted(
'assetType',
@@ -467,7 +491,11 @@ export function buildPluginContext(
},
overlays: { register: registerOverlay },
inspector: { register: registerInspector },
- assets: { registerType: registerAssetType },
+ assets: {
+ registerType: registerAssetType,
+ registerImporter,
+ reimport: (path: string) => runImporters([path]),
+ },
entities: { registerTemplate },
contextMenus: { register: registerContextMenuItem },
agentTools: { register: registerAgentToolContribution },
diff --git a/desktop/src/plugins/importers.ts b/desktop/src/plugins/importers.ts
new file mode 100644
index 000000000..f41f4a3e1
--- /dev/null
+++ b/desktop/src/plugins/importers.ts
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file importers.ts — contributed converters from a file the engine cannot read
+ * into assets it can.
+ *
+ * What they produce is ordinary project files, so nothing downstream — the
+ * registry, the inspector, cooking, the shipped build — learns a second format.
+ */
+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';
+
+/** An importer as the host holds it: the declaration, plus the already-guarded
+ * call, so a failure is attributed to its plugin wherever it is run from. */
+export interface RegisteredImporter {
+ id: string;
+ extensions: readonly string[];
+ run(path: string): Promise<void>;
+}
+
+const contrib = new ContributionRegistry<RegisteredImporter>('asset importer');
+
+const extensionOf = (path: string): string => {
+ const dot = path.lastIndexOf('.');
+ return dot < 0 ? '' : path.slice(dot + 1).toLowerCase();
+};
+
+export const importerRegistry = {
+ register: (owner: Owner, importer: RegisteredImporter): Disposable => contrib.register(owner, importer),
+ disposeOwner: (owner: Owner): void => contrib.disposeOwner(owner),
+ all: (): readonly RegisteredImporter[] => contrib.all(),
+
+ /** The importers claiming this path's extension, in registration order. */
+ forPath(path: string): RegisteredImporter[] {
+ const ext = extensionOf(path);
+ return ext === '' ? [] : contrib.all().filter((i) => i.extensions.some((e) => e.toLowerCase() === ext));
+ },
+};
+
+/** Whether any importer claims this path — the watcher's cheap pre-filter. */
+export const hasImporter = (path: string): boolean => importerRegistry.forPath(path).length > 0;
+
+// An importer writes files, and those writes come back through the same watcher.
+// A converter that produced its own source extension would otherwise re-enter
+// forever; one run per path at a time ends that without forbidding anything.
+const running = new Set<string>();
+
+/** Run every importer claiming each path. Failures are reported against their
+ * plugin and never stop the others. */
+export async function runImporters(paths: readonly string[]): Promise<void> {
+ for (const path of paths) {
+ for (const importer of importerRegistry.forPath(path)) {
+ const key = `${importer.id} -> ${path}`;
+ if (running.has(key)) continue;
+ running.add(key);
+ try {
+ await importer.run(path);
+ } finally {
+ running.delete(key);
+ }
+ }
+ }
+}
diff --git a/desktop/src/plugins/types.ts b/desktop/src/plugins/types.ts
index 55a0d4f44..326dc28d1 100644
--- a/desktop/src/plugins/types.ts
+++ b/desktop/src/plugins/types.ts
@@ -312,6 +312,25 @@ export interface AssetTypeContribution {
create?: { label: LocalizedString; run(dir: string): Promise<string | void> | string | void };
}
+// — Asset importers ————————————————————————————————————————————————————————————
+
+/**
+ * Turns a file the engine cannot read into assets it can.
+ *
+ * The editor calls `import` when a claimed file appears or changes, and on a
+ * reimport. Write the result with `ctx.fs.writeProject` (so declare `fs:project`):
+ * it is then an ordinary asset, and nothing downstream learns your format.
+ */
+export interface AssetImporterContribution {
+ /** Namespaced id, e.g. `acme.ldtk`. */
+ id: string;
+ /** Source extensions (lower-case, no dot) this converts. */
+ extensions: readonly string[];
+ /** Convert one source file, project-relative. Throwing (or rejecting) reports
+ * the failure against your plugin; the other importers still run. */
+ import(path: string): void | Promise<void>;
+}
+
// — Entity templates ——————————————————————————————————————————————————————————
/** One component of a template: its type, and any non-default field values. */
@@ -547,6 +566,11 @@ export interface PluginContext {
};
readonly assets: {
registerType(type: AssetTypeContribution): Disposable;
+ /** Convert a foreign file into engine assets. See {@link AssetImporterContribution}. */
+ registerImporter(importer: AssetImporterContribution): Disposable;
+ /** Re-run the importers claiming `path` (project-relative), as the Content
+ * Browser's Reimport does. Resolves when they have finished. */
+ reimport(path: string): Promise<void>;
};
readonly entities: {
registerTemplate(template: EntityTemplateContribution): Disposable;
diff --git a/desktop/src/project/fsWatch.ts b/desktop/src/project/fsWatch.ts
index 4f33a3f55..d2c4cdbc3 100644
--- a/desktop/src/project/fsWatch.ts
+++ b/desktop/src/project/fsWatch.ts
@@ -14,6 +14,7 @@ import { fsRefresh } from './fsRefresh';
import { projectReplacing } from './projectReplacing';
import { PlayRealm, PlayRealms } from '../engine/PlayRealm';
import { pluginPathsChanged, isPluginPath } from '../plugins/init';
+import { hasImporter, runImporters } from '../plugins/importers';
let inited = false;
let debounce: ReturnType<typeof setTimeout> | null = null;
@@ -28,6 +29,8 @@ let pendingPaths = new Set<string>();
let sawOverflow = false;
let pluginDebounce: ReturnType<typeof setTimeout> | null = null;
let pendingPluginPaths = new Set<string>();
+let importDebounce: ReturnType<typeof setTimeout> | null = null;
+let pendingImports = 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).
@@ -81,6 +84,20 @@ export function initFsWatch(): void {
fsRefresh.bump();
}, 60);
+ // A file a contributed importer claims appeared or changed → convert it. Its
+ // own window because an import WRITES, and converting on the registry's beat
+ // would race the scan that has to see the output.
+ const importable = paths.filter(hasImporter);
+ if (importable.length > 0) {
+ for (const p of importable) pendingImports.add(p);
+ if (importDebounce) clearTimeout(importDebounce);
+ importDebounce = setTimeout(() => {
+ const batch = [...pendingImports];
+ pendingImports = new Set();
+ void runImporters(batch);
+ }, 200);
+ }
+
// The open document — a scene, or the prefab being edited in Prefab Mode —
// changed on disk (external edit, git, build output) → reload it.
if (ProjectStore.isOpenDocumentPath(paths)) {
@@ -121,12 +138,13 @@ export function initFsWatch(): void {
* old project can't flush against the new one. Subscribed to the project swap
* below rather than called by the store — the watcher owns this state. */
function resetFsWatch(): void {
- for (const t of [debounce, schemaDebounce, scriptsDebounce, sceneDebounce, pluginDebounce]) {
+ for (const t of [debounce, schemaDebounce, scriptsDebounce, sceneDebounce, pluginDebounce, importDebounce]) {
if (t) clearTimeout(t);
}
- debounce = schemaDebounce = scriptsDebounce = sceneDebounce = pluginDebounce = null;
+ debounce = schemaDebounce = scriptsDebounce = sceneDebounce = pluginDebounce = importDebounce = null;
pendingPaths = new Set();
pendingPluginPaths = new Set();
+ pendingImports = new Set();
sawOverflow = false;
}
diff --git a/desktop/tests/plugin-api-surface.test.ts b/desktop/tests/plugin-api-surface.test.ts
index c10667667..c35f97631 100644
--- a/desktop/tests/plugin-api-surface.test.ts
+++ b/desktop/tests/plugin-api-surface.test.ts
@@ -16,6 +16,7 @@ import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as api from '@/plugins/api';
+import { importsAnotherModule } from '../../tools/lib/moduleImports.mjs';
const TYPES_FILE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../src/plugins/types.ts');
const source = readFileSync(TYPES_FILE, 'utf8');
@@ -33,10 +34,18 @@ describe('plugin API surface', () => {
});
it('keeps types.ts import-free so the shipped .d.ts stands alone', () => {
+ // The push gate refuses the same thing, through this same predicate — two
+ // regexes for one rule is how one of them ends up accepting what the other
+ // refuses (a method named `import(` was exactly that).
const imports = source
.split('\n')
- .filter((line) => /^\s*import\b/.test(line) && !line.trim().startsWith('*'));
+ .filter((line) => importsAnotherModule(line) && !line.trim().startsWith('*'));
expect(imports, 'types.ts must not import anything (it ships as standalone typings)').toEqual([]);
+ for (const line of ["import x from 'y';", "import{a}from'y'", 'import * as y from "y"', "import 'y'",
+ ' import type { A } from "y"', "export * from './x'", "export { a } from './x'"]) {
+ expect(importsAnotherModule(line), `${line} must count as an import`).toBe(true);
+ }
+ expect(importsAnotherModule(' import(path: string): void;')).toBe(false);
});
it('exposes definePlugin as an identity function', () => {
diff --git a/desktop/tests/plugin-importers.test.ts b/desktop/tests/plugin-importers.test.ts
new file mode 100644
index 000000000..20da86053
--- /dev/null
+++ b/desktop/tests/plugin-importers.test.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Contributed importers: what runs, for which file, and what a failing one
+ * costs the rest.
+ *
+ * An importer is the one contribution the editor calls on its own — the others
+ * wait for a click. So the claims that matter are about the CALL: it reaches
+ * exactly the importers that claim the extension, a throw or a rejection is
+ * reported against its plugin rather than escaping into the watcher, and a
+ * retracted importer stops being called.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import { buildPluginContext } from '@/plugins/context';
+import { hasImporter, runImporters } from '@/plugins/importers';
+import type { PluginManifest } from '@/plugins/manifest';
+
+const MANIFEST: PluginManifest = {
+ id: 'acme.tools',
+ name: 'Acme Tools',
+ version: '1.0.0',
+ main: { editor: 'src/editor.ts' },
+};
+
+let built: ReturnType<typeof buildPluginContext> | null = null;
+let failures: string[] = [];
+
+/** PluginHost's policy, as far as a contribution can tell: a throw is recorded
+ * and the caller gets the fallback. */
+const guard = <T,>(what: string, fn: () => T, fallback: T): T => {
+ try {
+ return fn();
+ } catch (e) {
+ failures.push(`${what}: ${e instanceof Error ? e.message : String(e)}`);
+ return fallback;
+ }
+};
+
+const build = () => {
+ failures = [];
+ built = buildPluginContext(MANIFEST, '/tmp/acme.tools', 'plugin:acme.tools', guard);
+ return built;
+};
+
+afterEach(() => {
+ built?.dispose();
+ built = null;
+});
+
+describe('a contributed importer', () => {
+ it('is called for the extensions it claims, and for nothing else', () => {
+ const seen: string[] = [];
+ const { ctx } = build();
+ ctx.assets.registerImporter({ id: 'ldtk', extensions: ['ldtk'], import: (p) => void seen.push(p) });
+
+ expect(hasImporter('levels/world.ldtk')).toBe(true);
+ expect(hasImporter('levels/world.tmj')).toBe(false);
+ expect(hasImporter('levels/ldtk')).toBe(false); // an extensionless file named like one
+ });
+
+ it('matches the extension whatever it is spelled like on disk', async () => {
+ const seen: string[] = [];
+ const { ctx } = build();
+ ctx.assets.registerImporter({ id: 'ldtk', extensions: ['LDtk'], import: (p) => void seen.push(p) });
+ await runImporters(['levels/World.LDTK']);
+ expect(seen).toEqual(['levels/World.LDTK']);
+ });
+
+ it('runs every importer that claims the file', async () => {
+ const seen: string[] = [];
+ const { ctx } = build();
+ ctx.assets.registerImporter({ id: 'a', extensions: ['ldtk'], import: () => void seen.push('a') });
+ ctx.assets.registerImporter({ id: 'b', extensions: ['ldtk'], import: () => void seen.push('b') });
+ await runImporters(['w.ldtk']);
+ expect(seen).toEqual(['a', 'b']);
+ });
+
+ it('reports a failure against its plugin and still runs the others', async () => {
+ const seen: string[] = [];
+ const { ctx } = build();
+ ctx.assets.registerImporter({ id: 'boom', extensions: ['ldtk'], import: () => { throw new Error('bad json'); } });
+ ctx.assets.registerImporter({ id: 'ok', extensions: ['ldtk'], import: () => void seen.push('ok') });
+ await runImporters(['w.ldtk']);
+ expect(failures.join(' ')).toMatch(/import w\.ldtk: bad json/);
+ expect(seen).toEqual(['ok']);
+ });
+
+ it('reports a REJECTION the same way — an importer is allowed to be async', async () => {
+ const { ctx } = build();
+ ctx.assets.registerImporter({
+ id: 'boom',
+ extensions: ['ldtk'],
+ import: () => Promise.reject(new Error('write failed')),
+ });
+ await runImporters(['w.ldtk']);
+ expect(failures.join(' ')).toMatch(/write failed/);
+ });
+
+ it('waits for an async import before the next change re-enters it', async () => {
+ // An import writes, and those writes come back through the watcher. Re-entering
+ // while the first run is still writing would convert half-written output.
+ let running = 0;
+ let overlapped = false;
+ let release = () => {};
+ const { ctx } = build();
+ ctx.assets.registerImporter({
+ id: 'slow',
+ extensions: ['ldtk'],
+ import: async () => {
+ if (running > 0) overlapped = true;
+ running++;
+ await new Promise<void>((r) => { release = r; });
+ running--;
+ },
+ });
+ const first = runImporters(['w.ldtk']);
+ const second = runImporters(['w.ldtk']); // the same file changed again
+ release();
+ await Promise.all([first, second]);
+ expect(overlapped).toBe(false);
+ });
+
+ it('stops being called once it is retracted', async () => {
+ const seen: string[] = [];
+ const { ctx } = build();
+ const handle = ctx.assets.registerImporter({ id: 'ldtk', extensions: ['ldtk'], import: () => void seen.push('ran') });
+ await runImporters(['w.ldtk']);
+ handle.dispose();
+ await runImporters(['w.ldtk']);
+ expect(seen).toEqual(['ran']);
+ expect(hasImporter('w.ldtk')).toBe(false);
+ });
+
+ it('reimport through the API is the same call the editor makes', async () => {
+ const seen: string[] = [];
+ const { ctx } = build();
+ ctx.assets.registerImporter({ id: 'ldtk', extensions: ['ldtk'], import: (p) => void seen.push(p) });
+ await ctx.assets.reimport('levels/w.ldtk');
+ expect(seen).toEqual(['levels/w.ldtk']);
+ });
+});
diff --git a/desktop/tests/plugin-inventory.test.ts b/desktop/tests/plugin-inventory.test.ts
index e44f7e748..3a375743b 100644
--- a/desktop/tests/plugin-inventory.test.ts
+++ b/desktop/tests/plugin-inventory.test.ts
@@ -63,6 +63,7 @@ function registerAll(ctx: PluginContext): Record<string, { dispose(): void }> {
build: () => {},
}),
assetType: ctx.assets.registerType({ id: 'acme.dialogue', extensions: ['dlg'] }),
+ importer: ctx.assets.registerImporter({ id: 'ldtk', extensions: ['ldtk'], import: () => {} }),
entityTemplate: ctx.entities.registerTemplate({ id: 'acme.turret', label: 'Turret', components: [] }),
contextMenu: ctx.contextMenus.register({
id: 'acme.reveal',
@@ -85,7 +86,7 @@ describe('contribution inventory', () => {
const kinds = b.contributions().map((c) => c.kind);
const expected: ContributionKind[] = [
'command', 'panel', 'setting', 'tool', 'overlay',
- 'inspector', 'assetType', 'entityTemplate', 'contextMenu',
+ 'inspector', 'assetType', 'importer', 'entityTemplate', 'contextMenu',
];
// Every kind present, and nothing registered twice.
expect([...kinds].sort()).toEqual([...expected].sort());
@@ -103,6 +104,8 @@ describe('contribution inventory', () => {
expect(byKind.get('inspector')?.id).toBe('acme.tools.audit');
// An asset type has no title of its own; its extensions are the useful label.
expect(byKind.get('assetType')?.label).toBe('.dlg');
+ // Same for an importer: what it converts is what identifies it in the list.
+ expect(byKind.get('importer')).toMatchObject({ id: 'acme.tools.ldtk', label: '.ldtk' });
// An overlay has neither — and must NOT fall back to its id, or the panel row
// prints the same string in the label column and the id column.
expect(byKind.get('overlay')).toMatchObject({ id: 'acme.gizmo', label: '' });
@@ -117,11 +120,11 @@ describe('contribution inventory', () => {
it('drops a contribution from the list when it is retracted', () => {
const b = build();
const handles = registerAll(b.ctx);
- expect(b.contributions()).toHaveLength(9);
+ expect(b.contributions()).toHaveLength(10);
handles.panel.dispose();
const after = b.contributions();
- expect(after).toHaveLength(8);
+ expect(after).toHaveLength(9);
expect(after.some((c) => c.kind === 'panel')).toBe(false);
// The others are untouched — retraction is per contribution, not per plugin.
expect(after.some((c) => c.kind === 'command')).toBe(true);
@@ -138,6 +141,6 @@ describe('contribution inventory', () => {
const b = build();
registerAll(b.ctx);
b.contributions().length = 0;
- expect(b.contributions()).toHaveLength(9);
+ expect(b.contributions()).toHaveLength(10);
});
});
diff --git a/docs/astro/src/content/docs/extending/editor-plugins.mdx b/docs/astro/src/content/docs/extending/editor-plugins.mdx
index aaf4ffb06..44b02709a 100644
--- a/docs/astro/src/content/docs/extending/editor-plugins.mdx
+++ b/docs/astro/src/content/docs/extending/editor-plugins.mdx
@@ -307,6 +307,31 @@ ctx.tools.activate('acme.measure');
- `ctx.contextMenus.register(…)` — a row in the Outliner or Content Browser
right-click menu, gated by the thing that was clicked.
+### Importers
+
+An importer turns a file the engine cannot read into assets it can. The editor
+calls it when a claimed file appears or changes, and on **Reimport** in the
+Content Browser:
+
+```typescript
+ctx.assets.registerImporter({
+ id: 'ldtk', // becomes acme.level-tools.ldtk
+ extensions: ['ldtk'],
+ async import(path) {
+ const level = JSON.parse(await ctx.fs.readProject(path));
+ await ctx.fs.writeProject(path.replace(/\.ldtk$/, '.tmj'), toTiled(level));
+ },
+});
+```
+
+What you write is an ordinary project asset, so nothing downstream — the
+registry, the inspector, cooking, the shipped build — learns your format. Declare
+the `fs:project` capability, or there is nowhere to put the output.
+
+Throwing (or rejecting) reports the failure against your plugin in the Output Log
+and leaves the other importers running. A file is never imported twice at once, so
+an import that takes a while cannot be re-entered by the writes it is making.
+
### Lending the agent a tool
The built-in agent's entire vocabulary is the tool catalog. A plugin that adds a
diff --git a/docs/astro/src/content/docs/zh-cn/extending/editor-plugins.mdx b/docs/astro/src/content/docs/zh-cn/extending/editor-plugins.mdx
index 25dd8ae57..ba94f3628 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
@@ -284,6 +284,28 @@ ctx.tools.activate('acme.measure');
- `ctx.contextMenus.register(…)`——大纲或内容浏览器右键菜单里的一行,可按被点击
的对象决定是否出现。
+### 导入器
+
+导入器把引擎读不懂的文件转成它读得懂的资产。被认领的文件出现或改变时,以及在内容
+浏览器里点**重新导入**时,编辑器会调用它:
+
+```typescript
+ctx.assets.registerImporter({
+ id: 'ldtk', // 最终是 acme.level-tools.ldtk
+ extensions: ['ldtk'],
+ async import(path) {
+ const level = JSON.parse(await ctx.fs.readProject(path));
+ await ctx.fs.writeProject(path.replace(/\.ldtk$/, '.tmj'), toTiled(level));
+ },
+});
+```
+
+你写出来的就是普通的项目资产,所以下游的一切——注册表、检查器、cook、发行包——都不
+需要认识你的格式。记得声明 `fs:project` 能力,否则没有地方放输出。
+
+抛异常(或 reject)会把这次失败记在你的插件名下(输出日志里),其余导入器照常运行。
+同一个文件不会被同时导入两次,所以一次耗时较久的导入不会被它自己写出的文件重新触发。
+
### 借一个工具给 Agent
内置 Agent 的全部词汇就是工具目录。**插件加了能力却没加工具,等于只给人加了、没给 Agent 加**——所以如果你的插件能烘焙遮蔽,就把它教给 Agent:
diff --git a/tools/check-plugin-api-contract.mjs b/tools/check-plugin-api-contract.mjs
index f876957da..e958919e1 100644
--- a/tools/check-plugin-api-contract.mjs
+++ b/tools/check-plugin-api-contract.mjs
@@ -23,6 +23,7 @@
import { readFileSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { importsAnotherModule } from './lib/moduleImports.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -139,7 +140,7 @@ for (const [kind, claims] of [['verdict', VERDICT], ['promise', PROMISES]]) {
*/
const imports = whole.typings.split('\n')
.map((l, i) => [i + 1, l])
- .filter(([, l]) => /^\s*(import\b|export\s+(\*|\{[^}]*\})\s+from\b)/.test(l));
+ .filter(([, l]) => importsAnotherModule(l));
for (const [line, l] of imports) {
failures.push(`${SURFACES.typings.path}:${line} imports — the file ships verbatim as the author's .d.ts, so it must stay self-contained`
+ `\n ${l.trim()}`);
diff --git a/tools/lib/moduleImports.d.mts b/tools/lib/moduleImports.d.mts
new file mode 100644
index 000000000..976b4e121
--- /dev/null
+++ b/tools/lib/moduleImports.d.mts
@@ -0,0 +1,3 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export function importsAnotherModule(line: string): boolean;
diff --git a/tools/lib/moduleImports.mjs b/tools/lib/moduleImports.mjs
new file mode 100644
index 000000000..0b180dbd2
--- /dev/null
+++ b/tools/lib/moduleImports.mjs
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file moduleImports.mjs — does this line make the file depend on another module?
+ *
+ * The plugin typings ship as TEXT, copied verbatim into an author's project, so
+ * being import-free is load-bearing rather than a style preference. Two checks
+ * enforce it — the push gate and the editor's unit suite — and each carrying its
+ * own regex is how one of them ends up accepting what the other refuses.
+ */
+
+/**
+ * True for a module import or re-export: `import x`, `import{x}`, `import*`,
+ * `import'side-effect'`, `export * from`, `export {…} from`.
+ *
+ * NOT for a method named `import(`, which an importer contribution declares and
+ * which pulls in nothing.
+ */
+export const importsAnotherModule = (line) =>
+ /^\s*(import\s*(?![(])|export\s+(\*|\{[^}]*\})\s+from\b)/.test(line);