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.

refactor(editor): the store stops importing its own dependents (4 cycles → 1)

esengine1a4003497689
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index d8000b88a..aa813024c 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -23,6 +23,7 @@ import { LogStore } from '@/store/LogStore';
import { t } from '@/i18n';
import { playProtocolMismatch } from './playProtocol';
import { bootProfiler } from './bootProfiler';
+import { projectReplacing } from '@/project/projectReplacing';
import type { PlayOutbound, PlayInbound, PlayPayload, PlaySnapshot, PlayStatsReply } from './playProtocol';
export type { PlayPayload, PlaySnapshot } from './playProtocol';
@@ -498,3 +499,8 @@ export const PlayRealms = new PlayRealmsManager();
/** The primary realm — the single-player surface every existing consumer
* (inspect, profiler, subsystems, viewport PIE) talks to. */
export const PlayRealm = PlayRealms.primary;
+
+// A realm warmed for the previous project holds its bundle + assets, so it
+// cold-resets when the project is replaced — subscribed here rather than called
+// by the project store, which has no business knowing the realm exists.
+projectReplacing.subscribe(() => PlayRealms.resetPrimary());
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 3d9979ef1..5073b58f8 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -14,7 +14,7 @@ import {
} from 'esengine';
import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
-import { projectDesignSeed, projectCameraFit } from './entitySources';
+import { projectDesignSeed, projectCameraFit } from './projectSeams';
import { SceneModel } from './SceneModel';
import {
type OBB,
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index 03bda8d6d..728f74ac8 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -14,6 +14,7 @@
* catalog tests assert over); pickers read {@link entitySources} so a contributed
* template shows up everywhere an entity can be born.
*/
+import { projectPrefabSources, projectDesignSeed } from './projectSeams';
import type { LucideIcon } from 'lucide-react';
import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput, Grid3x3, MapPin, Scan } from 'lucide-react';
import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, applyThemeToWorld, type PrefabData } from 'esengine';
@@ -177,33 +178,6 @@ function presetSource(id: string, label: string, category: string, icon: LucideI
return { id, label, category, icon, build: () => prefab };
}
-// Project reference resolution provider (ProjectStore wires this on open). A new
-// Canvas seeds its designResolution from it; injected rather than imported so
-// entitySources doesn't cycle with ProjectStore (as setPrefabBaseResolver does).
-let canvasDesignSeed: (() => { width: number; height: number }) | null = null;
-export function setCanvasDesignSeed(fn: () => { width: number; height: number }): void {
- canvasDesignSeed = fn;
-}
-
-/** The project's reference (design) resolution, from the same provider that seeds new
- * Canvases. Read by the editor's design/device preview so it works without a UI Canvas —
- * exposed here (rather than importing ProjectStore) to keep the engine modules acyclic. */
-export function projectDesignSeed(): { width: number; height: number } {
- return canvasDesignSeed?.() ?? { width: 1920, height: 1080 };
-}
-
-// Project camera fit provider (ProjectStore wires this). `scaleMode` is a CanvasScaleMode
-// (0..4) or -1 (off). Same injection pattern as canvasDesignSeed — the device preview
-// reads it so its letterbox matches the runtime fit (WYSIWYG), without importing ProjectStore.
-let projectCameraFitSeed: (() => { scaleMode: number; matchWidthOrHeight: number }) | null = null;
-export function setProjectCameraFit(fn: () => { scaleMode: number; matchWidthOrHeight: number }): void {
- projectCameraFitSeed = fn;
-}
-/** The project's camera fit (scaleMode -1 ⇒ off). Read by ViewportController.screenInfo. */
-export function projectCameraFit(): { scaleMode: number; matchWidthOrHeight: number } {
- return projectCameraFitSeed?.() ?? { scaleMode: -1, matchWidthOrHeight: 0.5 };
-}
-
const UI_WIDGET_ICON: Record<string, LucideIcon> = {
Button: SquareMousePointer,
Toggle: ToggleLeft,
@@ -298,7 +272,7 @@ export const ENTITY_SOURCES: EntitySource[] = [
category: 'UI',
icon: LayoutPanelTop,
build: () => {
- const d = canvasDesignSeed?.() ?? { width: 1920, height: 1080 };
+ const d = projectDesignSeed();
return preset('Canvas', ['Transform', ['Canvas', { designResolution: { x: d.width, y: d.height } }], 'UINode']);
},
},
@@ -375,13 +349,6 @@ export function allEntitySources(): EntitySource[] {
return [...entitySources(), ...userComponentSources(), ...projectPrefabSources()];
}
-/** Project prefab sources, injected by ProjectStore (which owns the asset registry)
- * so this module stays free of a project dependency. */
-let projectPrefabSources: () => EntitySource[] = () => [];
-export function setProjectPrefabSources(fn: () => EntitySource[]): void {
- projectPrefabSources = fn;
-}
-
/** The source with this id, or null — over the SAME list the pickers offer, so an
* id that appears in a catalog can always be spawned. */
export function sourceById(id: string): EntitySource | null {
diff --git a/desktop/src/engine/projectSeams.ts b/desktop/src/engine/projectSeams.ts
new file mode 100644
index 000000000..201b977c6
--- /dev/null
+++ b/desktop/src/engine/projectSeams.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The project settings the ENGINE layer reads, published by the store.
+ *
+ * The engine modules must not import ProjectStore — the store is built on top of
+ * them — so the handful of project facts they legitimately need arrive by
+ * injection: the store calls each `set*` as it opens a project, and the engine
+ * side reads the getter. Each has a defined answer before (and without) a
+ * project, so a module that reads one works in a bare editor, in a test, and in
+ * a headless boot.
+ *
+ * They lived in entitySources, which is about CREATING entities and has nothing
+ * to do with camera fit or design resolution: reading one from the viewport
+ * dragged in the whole entity-source registry, and through it the scene commands
+ * that call back into the viewport — a dependency cycle grown out of a seam
+ * parked in the nearest file rather than its own.
+ */
+import type { EntitySource } from './entitySources';
+
+// -- The project's reference (design) resolution ------------------------------
+// A new Canvas seeds its designResolution from it, and the editor's design /
+// device preview reads it so the preview works without a UI Canvas at all.
+
+let canvasDesignSeed: (() => { width: number; height: number }) | null = null;
+
+export function setCanvasDesignSeed(fn: () => { width: number; height: number }): void {
+ canvasDesignSeed = fn;
+}
+
+export function projectDesignSeed(): { width: number; height: number } {
+ return canvasDesignSeed?.() ?? { width: 1920, height: 1080 };
+}
+
+// -- The project's camera fit -------------------------------------------------
+// `scaleMode` is a CanvasScaleMode (0..4) or -1 (off). The device preview reads
+// it so its letterbox matches what the runtime will do (WYSIWYG).
+
+let projectCameraFitSeed: (() => { scaleMode: number; matchWidthOrHeight: number }) | null = null;
+
+export function setProjectCameraFit(fn: () => { scaleMode: number; matchWidthOrHeight: number }): void {
+ projectCameraFitSeed = fn;
+}
+
+export function projectCameraFit(): { scaleMode: number; matchWidthOrHeight: number } {
+ return projectCameraFitSeed?.() ?? { scaleMode: -1, matchWidthOrHeight: 0.5 };
+}
+
+// -- The project's own prefabs, as entity sources ------------------------------
+// Injected by the store, which owns the asset registry; they join the one list
+// every "create an entity" surface offers (see allEntitySources).
+
+let projectPrefabSourcesFn: () => EntitySource[] = () => [];
+
+export function setProjectPrefabSources(fn: () => EntitySource[]): void {
+ projectPrefabSourcesFn = fn;
+}
+
+export function projectPrefabSources(): EntitySource[] {
+ return projectPrefabSourcesFn();
+}
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 233bbb0dd..725594e39 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -32,7 +32,7 @@ import { createMaterialInstance } from '@/material/openMaterial';
import { NEW_ASSET_TYPES, type CreateAsset } from '@/project/newAssetTypes';
import { ASSET_GROUP_MODES, type AssetGroupMode } from 'esengine';
import { onAssetReveal } from '@/project/assetReveal';
-import { fsRefresh } from '@/project/fsWatch';
+import { fsRefresh } from '@/project/fsRefresh';
import { t, type MsgKey } from '@/i18n';
import type { DirEntry } from '@/project/format';
import type { AssetType } from '@/types';
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 1860c2d28..c42d29638 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -54,7 +54,7 @@ import { EventBindingSection } from '@/events/EventBindingSection';
import { COMP_COLLIDER_SHAPE, type ColliderShapeKind } from '@/engine/colliderConvert';
import { AudioWavePreview } from '@/components/AudioWavePreview';
import { NineSliceEditor } from '@/components/NineSliceEditor';
-import { fsRefresh } from '@/project/fsWatch';
+import { fsRefresh } from '@/project/fsRefresh';
import { Toasts } from '@/store/Toasts';
import { baseName, IMAGE_RE } from '@/project/assetMeta';
import { BUILTIN_PLATFORMS, type BuiltinPlatform } from '@/project/platforms';
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 9e6790190..f877b97aa 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -16,7 +16,8 @@ import { EditorHistory } from '@/engine/EditorHistory';
import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
import { SceneCommands } from '@/engine/SceneCommands';
import { Boxes } from 'lucide-react';
-import { spritePrefab, setCanvasDesignSeed, setProjectCameraFit, setProjectPrefabSources, sourceById, type EntitySource } from '@/engine/entitySources';
+import { spritePrefab, sourceById, type EntitySource } from '@/engine/entitySources';
+import { setCanvasDesignSeed, setProjectCameraFit, setProjectPrefabSources } from '@/engine/projectSeams';
import { needsUIHost, hostPrefab, authoredEntities, type DocumentEntity } from '@/engine/prefabEnvironment';
import { setPrefabBaseResolver } from '@/engine/SceneQuery';
import { setUserSchemas, userSchema, setBitmaskSource, setEnumSource, type UserComponentSchema } from '@/engine/schema';
@@ -40,10 +41,10 @@ import { ASSET_SLOTS, metaTypeToSlot } from '@/project/assetSlots';
import type { AssetType } from '@/types';
import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, resolveScripts, DEFAULT_SCRIPTS, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type ProjectScripts, type WorkspaceState, type DesignResolution, type ScreenPreset, type ScreenOrientation, type CameraScaleMode, type ExportPlatform } from './format';
import { useEditorMode } from '@/store/editorModeStore';
-import { PlayRealms } from '@/engine/PlayRealm';
import { PlayInspect } from '@/engine/PlayInspect';
import { useEditorStore } from '@/store/editorStore';
-import { resetFsWatch, fsRefresh } from './fsWatch';
+import { projectReplacing } from './projectReplacing';
+import { fsRefresh } from './fsRefresh';
import type { DocSnapshot } from '@/document/DirtyRegistry';
/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */
@@ -278,7 +279,7 @@ class ProjectStoreImpl {
setEnumSource('sortingLayers', () => this.sortingLayerOptions());
installDragonBonesEnumSources();
installSpineEnumSources();
- installLocaleKeyEnumSource();
+ installLocaleKeyEnumSource(() => this.listAssets('locale'));
// A skeleton re-exported outside the editor declares different animations —
// drop what was parsed from the old file so the next render re-reads it.
fsRefresh.subscribe(() => clearDragonBonesNameCache());
@@ -458,11 +459,11 @@ class ProjectStoreImpl {
// late populateRegistry must not clobber this project's registry).
this.projectGeneration++;
this.revalidating = false;
- // Drop any file-watch burst still queued for the previous project.
- resetFsWatch();
- // A play realm warmed for the PREVIOUS project holds its bundle + assets;
- // cold-reset so the next prewarm/Play stages this project.
- PlayRealms.resetPrimary();
+ // Anything the PREVIOUS project left in flight drops itself here: the
+ // file-watch burst still queued, the play realm warmed with its bundle and
+ // assets. Announced rather than phoned around, so a subsystem with
+ // in-flight state subscribes instead of being remembered by this method.
+ projectReplacing.announce();
this.store.setState({
project: {
root: opened.root,
diff --git a/desktop/src/project/fsRefresh.ts b/desktop/src/project/fsRefresh.ts
new file mode 100644
index 000000000..657b12a1f
--- /dev/null
+++ b/desktop/src/project/fsRefresh.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The "something on disk changed" signal.
+ *
+ * Deliberately its own module with NO imports: everything that wants to re-read
+ * after a disk change subscribes here — panels, the asset store, caches keyed by
+ * file content. It lived inside fsWatch, which meant a panel that only wanted
+ * the signal pulled in the watcher, the project store and the plugin host with
+ * it, and made the store↔watcher edge a dependency cycle.
+ *
+ * The signal says only THAT something changed, never what: a subscriber
+ * re-reads whatever it holds. `get()` is the version counter, for a subscriber
+ * that memoizes across renders.
+ */
+
+const listeners = new Set<() => void>();
+let version = 0;
+
+/** A re-read signal shared by every mounted `useDir` (no prop/context threading). */
+export const fsRefresh = {
+ bump: (): void => {
+ version++;
+ for (const l of listeners) l();
+ },
+ subscribe: (fn: () => void): (() => void) => {
+ listeners.add(fn);
+ return () => {
+ listeners.delete(fn);
+ };
+ },
+ get: (): number => version,
+};
diff --git a/desktop/src/project/fsWatch.ts b/desktop/src/project/fsWatch.ts
index 97d6d6c99..ada614641 100644
--- a/desktop/src/project/fsWatch.ts
+++ b/desktop/src/project/fsWatch.ts
@@ -3,33 +3,18 @@
/**
* @file Live filesystem ↔ editor-asset sync (renderer side).
*
- * `fsRefresh` is a bump signal every `useDir` subscribes to (re-read directories).
* `initFsWatch` subscribes ONCE to the main-process watcher so changes on disk —
* including edits made OUTSIDE the editor (Finder, git, build output, cooking) —
* refresh the asset registry + Content Browser, not just the editor's own ops.
+ * The signal subscribers listen to is {@link fsRefresh}, which lives on its own
+ * so listening costs nothing but the signal.
*/
import { ProjectStore } from './ProjectStore';
+import { fsRefresh } from './fsRefresh';
+import { projectReplacing } from './projectReplacing';
import { PlayRealm, PlayRealms } from '../engine/PlayRealm';
import { pluginPathsChanged, isPluginPath } from '../plugins/init';
-const listeners = new Set<() => void>();
-let version = 0;
-
-/** A re-read signal shared by every mounted `useDir` (no prop/context threading). */
-export const fsRefresh = {
- bump: () => {
- version++;
- for (const l of listeners) l();
- },
- subscribe: (fn: () => void) => {
- listeners.add(fn);
- return () => {
- listeners.delete(fn);
- };
- },
- get: () => version,
-};
-
let inited = false;
let debounce: ReturnType<typeof setTimeout> | null = null;
let schemaDebounce: ReturnType<typeof setTimeout> | null = null;
@@ -131,9 +116,10 @@ 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 {
+/** Drop pending debounced work + accumulated paths, so a burst captured for the
+ * 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]) {
if (t) clearTimeout(t);
}
@@ -142,3 +128,7 @@ export function resetFsWatch(): void {
pendingPluginPaths = new Set();
sawOverflow = false;
}
+
+// The watcher drops its own in-flight burst when the project is replaced; the
+// store announces the swap without knowing who is listening.
+projectReplacing.subscribe(resetFsWatch);
diff --git a/desktop/src/project/localeKeys.ts b/desktop/src/project/localeKeys.ts
index 71893abc9..64c821fff 100644
--- a/desktop/src/project/localeKeys.ts
+++ b/desktop/src/project/localeKeys.ts
@@ -21,18 +21,22 @@ import { parseLocaleTable } from 'esengine';
import { setEnumSource } from '@/engine/schema';
import { SceneStore } from '@/engine/SceneStore';
import type { EnumOption } from '@/types';
-import { ProjectStore } from './ProjectStore';
-import { fsRefresh } from './fsWatch';
+
+import { fsRefresh } from './fsRefresh';
import { editorLocale } from '@/i18n';
let options: EnumOption[] = [];
let stale = true;
let scanning = false;
+/** Where the locale tables are, supplied at install time — see
+ * {@link installLocaleKeyEnumSource}. */
+let listLocaleAssets: () => ReadonlyArray<{ path: string }> = () => [];
+
async function scan(): Promise<EnumOption[]> {
// key → per-locale preview text (plural entries preview their `other` form).
const previews = new Map<string, Map<string, string>>();
- for (const { path } of ProjectStore.listAssets('locale')) {
+ for (const { path } of listLocaleAssets()) {
// Deleted between the listing and the read — the next bump rescans.
const text = await window.estella.fs.readOptional(path);
if (text === null) continue;
@@ -75,8 +79,17 @@ function kickScan(): void {
// render (or directory re-read) kicks the rescan.
fsRefresh.subscribe(() => { stale = true; });
-/** Register the `Text.i18nKey` picker's source. Called once, beside the others. */
-export function installLocaleKeyEnumSource(): void {
+/**
+ * Register the `Text.i18nKey` picker's source. Called once, beside the others.
+ *
+ * The locale tables are handed in rather than read from the project store: this
+ * module is one of the store's CONSUMERS, and importing it back to ask for a
+ * list made the two a dependency cycle for the sake of a single call.
+ */
+export function installLocaleKeyEnumSource(
+ listAssets: () => ReadonlyArray<{ path: string }>,
+): void {
+ listLocaleAssets = listAssets;
setEnumSource('localeKeys', () => {
kickScan();
return options;
diff --git a/desktop/src/project/projectReplacing.ts b/desktop/src/project/projectReplacing.ts
new file mode 100644
index 000000000..3bc380332
--- /dev/null
+++ b/desktop/src/project/projectReplacing.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file "The open project is being replaced" — announced, not phoned around.
+ *
+ * Opening a project has to invalidate whatever the PREVIOUS one left in flight:
+ * a debounced file-watch burst, a warmed play realm. The store used to call each
+ * subsystem by name, which made it depend on its own dependents (a cycle) and
+ * meant every new subsystem with in-flight state had to be added to that list by
+ * whoever remembered.
+ *
+ * Announced SYNCHRONOUSLY, before the new project's state lands, so a subscriber
+ * that drops queued work is guaranteed to run before anything can act on the new
+ * project. No imports, for the same reason as fsRefresh: subscribing costs
+ * nothing but the signal.
+ */
+
+const listeners = new Set<() => void>();
+
+export const projectReplacing = {
+ subscribe: (fn: () => void): (() => void) => {
+ listeners.add(fn);
+ return () => {
+ listeners.delete(fn);
+ };
+ },
+ /** Announced by the project store as it swaps projects. A throwing subscriber
+ * must not strand the others, or the rest of the old project stays live. */
+ announce: (): void => {
+ for (const l of [...listeners]) {
+ try {
+ l();
+ } catch (e) {
+ console.error('[project] a projectReplacing subscriber threw', e);
+ }
+ }
+ },
+};
diff --git a/desktop/tests/project-display.test.ts b/desktop/tests/project-display.test.ts
index 79165964b..a56043b72 100644
--- a/desktop/tests/project-display.test.ts
+++ b/desktop/tests/project-display.test.ts
@@ -9,7 +9,8 @@
import { describe, it, expect, afterEach } from 'vitest';
import '@/settings';
import { settingsRegistry } from '@/settings/registry';
-import { ENTITY_SOURCES, setCanvasDesignSeed } from '@/engine/entitySources';
+import { ENTITY_SOURCES } from '@/engine/entitySources';
+import { setCanvasDesignSeed } from '@/engine/projectSeams';
import { ProjectStore } from '@/project/ProjectStore';
async function canvasDesign(): Promise<{ x: number; y: number }> {
diff --git a/tools/check-cycles.mjs b/tools/check-cycles.mjs
index 670cb8010..33b2836c4 100644
--- a/tools/check-cycles.mjs
+++ b/tools/check-cycles.mjs
@@ -25,12 +25,19 @@ import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-// Lower these as cycles are broken; never raise them. 0 is the goal for both.
-// The editor's four are all inside one subsystem each (EngineHost/Reconciler,
-// ProjectStore/fsWatch) rather than across layers — real, but contained.
+// Lower these as cycles are broken; never raise them.
+//
+// The editor's remaining one is EngineHost → SceneLoader → Reconciler →
+// EngineHost, and it is PRINCIPLED rather than pending: the three are one
+// collaboration around the live World — the host owns it, the loader loads into
+// it, the reconciler projects the scene model into it. Breaking it means either
+// leaking the App out of EngineHost (worse encapsulation, for one caller) or
+// threading a world argument through six modules of call sites. Both are worse
+// than the cycle. Judge a NEW cycle on its own merits; do not read this budget
+// as permission for one.
const BUDGETS = [
{ name: 'sdk', entry: 'sdk/src/index.ts', extensions: ['ts'], budget: 0 },
- { name: 'editor', entry: 'desktop/src/main.tsx', extensions: ['ts', 'tsx'], budget: 4 },
+ { name: 'editor', entry: 'desktop/src/main.tsx', extensions: ['ts', 'tsx'], budget: 1 },
];
let failed = false;