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(assets): asset-delivery groups — config-driven CDN / subpackage

yhh1b919dd923ff
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index 8312dc88d..8ec267a90 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -25,6 +25,10 @@ import { packAtlas, decodePngImage, encodePagePng, type AtlasInputImage } from '
// no hand-mirrored copy — so the cook and the runtime agree by construction.
import { contentHashHex } from '../../sdk/src/asset/contentHash';
import { resolveRelativePath } from '../../sdk/src/tilemap/tiledPath';
+// Single source for the folder→delivery-group model, shared with the editor Play
+// realm (sdk/src/asset/assetGroups.ts) so cook and editor never disagree.
+import { resolveAssetGroup, type AssetGroupsConfig } from '../../sdk/src/asset/assetGroups';
+import type { BundleMode } from '../../sdk/src/asset/AddressableManifest';
const MANIFEST = 'assets.manifest.json';
@@ -35,10 +39,10 @@ const MANIFEST = 'assets.manifest.json';
* simply ignores these extra fields (it maps uuid→path); the AddressableManifest
* and content-addressed naming are what read them.
*/
-/** How an addressable group is delivered — the typed mode the folder convention
- * ({@link groupOf}) assigns and the AddressableManifest carries. `local` ships in
- * the main package; `lazy` in an on-demand subpackage; `remote` on a CDN (hot-update). */
-export type GroupDelivery = 'local' | 'lazy' | 'remote';
+/** How an addressable group is delivered — the typed mode {@link resolveAssetGroup}
+ * assigns and the AddressableManifest carries. Alias of the SDK's BundleMode:
+ * `local` (main package), `lazy` (subpackage), `remote` (CDN / hot-update). */
+export type GroupDelivery = BundleMode;
export interface CookManifestEntry extends AssetEntry {
/** XXH64 (16 hex) of the exact bytes staged — the asset's physical identity. */
@@ -99,36 +103,19 @@ export function atlasDirOf(projectRelPath: string): string | null {
* single source of truth for the grouping — cook (here), export layout, and the
* manifest all derive from it.
*/
-const SUBPACKAGE_RE = /^subpackages\/([^/]+)\//;
-export function subpackageOf(projectRelPath: string): string | null {
- const m = SUBPACKAGE_RE.exec(projectRelPath.replace(/\\/g, '/'));
- return m ? m[1] : null;
-}
-
-const REMOTE_RE = /^remote\/([^/]+)\//;
/**
- * Folder-convention remote-group detection: an asset under `remote/<name>/…`
- * belongs to CDN-delivered group `<name>` — shipped to a remote origin, NOT the
- * package, and fetched on demand / hot-updated. Null for package assets. Parallel
- * to {@link subpackageOf}; the two are mutually exclusive by folder.
+ * Load the project's asset-delivery config (`.esengine/asset-groups.json`) — the
+ * single authored source for which folders ship as remote (CDN) / subpackage
+ * groups. Absent or unparseable → null, and {@link resolveAssetGroup} falls back
+ * to the legacy `remote/`/`subpackages/` folder-name convention.
*/
-export function remoteGroupOf(projectRelPath: string): string | null {
- const m = REMOTE_RE.exec(projectRelPath.replace(/\\/g, '/'));
- return m ? m[1] : null;
-}
-
-/**
- * The addressable group + delivery an asset's folder assigns it — the single
- * source of truth cook staging, the export layout, and the manifest all derive
- * from. `subpackages/<name>/` → lazy `<name>`; `remote/<name>/` → remote `<name>`;
- * anything else → local `main`.
- */
-export function groupOf(projectRelPath: string): { name: string; delivery: GroupDelivery } {
- const sub = subpackageOf(projectRelPath);
- if (sub) return { name: sub, delivery: 'lazy' };
- const rem = remoteGroupOf(projectRelPath);
- if (rem) return { name: rem, delivery: 'remote' };
- return { name: 'main', delivery: 'local' };
+export async function loadAssetGroups(root: string): Promise<AssetGroupsConfig | null> {
+ try {
+ const raw = await readFile(path.join(root, '.esengine', 'asset-groups.json'), 'utf8');
+ return JSON.parse(raw) as AssetGroupsConfig;
+ } catch {
+ return null;
+ }
}
/** Content-addressed base dir for a group's delivery: main → `assets`,
@@ -253,6 +240,8 @@ export async function cookAssets(
const byUuid = new Map(index.entries.map((e) => [e.uuid, e]));
const byPath = new Map(index.entries.map((e) => [e.path, e]));
const warnings: string[] = [];
+ // Asset-delivery config: which folders are remote (CDN) / subpackage groups.
+ const groupsConfig = await loadAssetGroups(root);
// Seed reachability from the entry scenes (path → uuid)…
const reachable = new Set<string>();
@@ -276,9 +265,9 @@ export async function cookAssets(
// shared dep that lives outside subpackages/ resolves to group 'main' below, so
// it lands in the always-present main package, not duplicated per subpackage.
for (const e of index.entries) {
- // …and remote CDN / hot-update assets (remote/<name>/): never scene-
- // referenced, but must be cooked + staged for upload to the CDN root.
- if (subpackageOf(e.path) || remoteGroupOf(e.path)) seed(e.uuid);
+ // …and every non-local (subpackage / remote-CDN) asset: never scene-
+ // referenced, but must be cooked + staged for its group's delivery.
+ if (resolveAssetGroup(e.path, groupsConfig).delivery !== 'local') seed(e.uuid);
}
// Force-include locale string tables: translations load by code / plugin
// option (a scene never references them — Text carries KEYS, not paths), so
@@ -367,7 +356,7 @@ export async function cookAssets(
compressedFormats = COMPRESSED_TARGETS;
}
const pageHash = contentHashHex(pageBytes);
- const { name: group, delivery } = groupOf(`${dir}/`);
+ const { name: group, delivery } = resolveAssetGroup(`${dir}/`, groupsConfig);
const caBase = caBaseFor(group, delivery);
const pageOutRel = contentAddressed
? `${caBase}/${pageHash}${pageExt}`
@@ -399,7 +388,7 @@ export async function cookAssets(
// page's (hash/size of the bytes actually served for this ref).
const framePlan = atlasPlan.get(entry.path);
if (framePlan) {
- const fg = groupOf(entry.path);
+ const fg = resolveAssetGroup(entry.path, groupsConfig);
manifestEntries.push({
uuid: entry.uuid,
path: framePlan.pageOutRel,
@@ -507,7 +496,7 @@ export async function cookAssets(
// Group by folder convention. Lazy-subpackage assets must stay under their
// subpackage root (subpackages/<name>/…) so the root maps to a WeChat
// subPackage — including the content-addressed layout (root/assets/<hash>).
- const { name: group, delivery } = groupOf(entry.path);
+ const { name: group, delivery } = resolveAssetGroup(entry.path, groupsConfig);
const useCA = contentAddressed && entry.type !== 'scene';
const caBase = caBaseFor(group, delivery);
const outRel = useCA ? `${caBase}/${hash}${ext}` : swapExt(entry.path, ext);
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index d0201c59e..f0676b279 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -24,8 +24,9 @@ import { loadEsbuild } from './esbuildRuntime';
import { writeFile, mkdir, cp, readdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
-import { cookAssets } from './cookAssets';
+import { cookAssets, loadAssetGroups } from './cookAssets';
import { buildAddressableManifest } from './addressableManifest';
+import { activeRemoteRoot } from '../../sdk/src/asset/assetGroups';
import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';
import { exportWeChat } from './exportWeChat';
import { exportPlayable } from './exportPlayable';
@@ -402,6 +403,16 @@ export async function exportGame(opts: {
// still reads the flat manifest; this powers on-demand + hot-update delivery.
await writeFile(path.join(payloadDir, 'asset-manifest.json'), await buildAddressableManifest(payloadDir));
+ // Hot-update delivery baked into game.config.json: the active build profile's
+ // CDN root (an explicit opts.hotUpdate override wins), plus a persistence key so
+ // a returning player boots on already-updated content. Only emitted when a CDN
+ // root is configured — a project with no remote groups ships nothing extra.
+ const remoteRoot = opts.hotUpdate?.remoteRoot ?? activeRemoteRoot(await loadAssetGroups(opts.root));
+ const persistUpdateKey = opts.hotUpdate?.persistUpdateKey ?? (remoteRoot ? 'esengine:hotupdate' : undefined);
+ const hotUpdate = remoteRoot || persistUpdateKey
+ ? { ...(remoteRoot ? { remoteRoot } : {}), ...(persistUpdateKey ? { persistUpdateKey } : {}) }
+ : undefined;
+
try {
// 2. Game host — esengine EXTERNAL (resolved by the index.html import map),
// so the shipped game shares one SDK with the project bundle and runs
@@ -446,7 +457,7 @@ export async function exportGame(opts: {
...(opts.screenFit && opts.screenFit.scaleMode >= 0 ? { screenFit: opts.screenFit } : {}),
...(opts.uiTheme === 'light' ? { uiTheme: opts.uiTheme } : {}),
...(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? { uiThemeColors: opts.uiThemeColors } : {}),
- ...(opts.hotUpdate ? { hotUpdate: opts.hotUpdate } : {}),
+ ...(hotUpdate ? { hotUpdate } : {}),
},
null, 2,
) + '\n',
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 002ec0d8a..8eb67ba51 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1,9 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { createStore } from 'zustand/vanilla';
-import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';
+import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup } from 'esengine';
import { readTextureImportSettings } from './assetImporter';
-import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides, StaleOverride, PrefabOverride, AddressableManifest } from 'esengine';
+import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides, StaleOverride, PrefabOverride, AddressableManifest, AssetGroupsConfig } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
import { applyWidgetTheme } from '@/engine/widgetTheme';
import { bootProfiler } from '@/engine/bootProfiler';
@@ -332,6 +332,7 @@ class ProjectStoreImpl {
Toasts.push(t('proj.sdkTypesFailed', { message: opened.stagingError }), 'error');
}
this.adopt(opened);
+ await this.loadAssetGroupsConfig();
await window.estella.recents.add(opened.root, opened.manifest.name);
await this.refreshUserSchemas();
EngineHost.setSceneBootstrap(() => this.loadCurrentScene());
@@ -1359,12 +1360,28 @@ class ProjectStoreImpl {
* the lossless refs, not resolved handles — plus a uuid→url manifest the realm
* fetches over `estella://`. Null if no scene is loaded.
*/
+ /** The project's asset-delivery config, cached on open (see {@link loadAssetGroupsConfig}). */
+ private assetGroupsConfig: AssetGroupsConfig | null = null;
+
+ /** Cache `.esengine/asset-groups.json` so {@link buildPlayManifest} resolves
+ * groups synchronously. Absent → null, and resolveAssetGroup falls back to the
+ * legacy folder-name convention. */
+ private async loadAssetGroupsConfig(): Promise<void> {
+ try {
+ this.assetGroupsConfig = JSON.parse(
+ await window.estella.fs.read(`${WORKSPACE_DIR}/asset-groups.json`),
+ ) as AssetGroupsConfig;
+ } catch {
+ this.assetGroupsConfig = null;
+ }
+ }
+
/**
* Build the AddressableManifest for Play so `Assets.loadGroup` (remote / lazy
- * groups) works in the editor realm exactly as in a shipped build. The folder
- * convention mirrors the cook's `groupOf` (cookAssets.ts — the canonical
- * source): `remote/<name>/` → remote group, `subpackages/<name>/` → lazy, else
- * `main`/local. Types are inferred from the extension (the realm resolves each
+ * groups) works in the editor realm exactly as in a shipped build. Group
+ * membership comes from the SAME resolver the cook uses ({@link resolveAssetGroup}
+ * over the cached asset-groups config), so editor and shipped build never
+ * disagree. Types are inferred from the extension (the realm resolves each
* asset's url through the same uuid/path channel); `size` is 0 (unknown before a
* cook, and unused by loadGroup).
*/
@@ -1383,11 +1400,8 @@ class ProjectStoreImpl {
const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, Asset> }> = {};
for (const [uuid, raw] of this.uuidToPath) {
const path = raw.replace(/\\/g, '/');
- const sub = /^subpackages\/([^/]+)\//.exec(path);
- const rem = /^remote\/([^/]+)\//.exec(path);
- const name = sub?.[1] ?? rem?.[1] ?? 'main';
- const mode = sub ? 'lazy' : rem ? 'remote' : 'local';
- const g = (groups[name] ??= { bundleMode: mode, labels: [], assets: {} });
+ const { name, delivery } = resolveAssetGroup(path, this.assetGroupsConfig);
+ const g = (groups[name] ??= { bundleMode: delivery, labels: [], assets: {} });
g.assets[uuid.toLowerCase()] = { path, type: typeOfExt(path), size: 0, labels: [] };
}
groups.main ??= { bundleMode: 'local', labels: [], assets: {} };
diff --git a/desktop/tests/hotupdate-verify-fixture.test.ts b/desktop/tests/hotupdate-verify-fixture.test.ts
index a0eea52eb..5c98c9ebd 100644
--- a/desktop/tests/hotupdate-verify-fixture.test.ts
+++ b/desktop/tests/hotupdate-verify-fixture.test.ts
@@ -48,9 +48,16 @@ describe.skipIf(!process.env.ESTELLA_HOTUPDATE_FIXTURE)('hot-update verify fixtu
// runtime's diff sees exactly one changed asset.
cpSync(EXAMPLE, REDSRC, {
recursive: true,
- filter: (s) => !s.includes(`${path.sep}.esengine`) && !s.includes('node_modules'),
+ // Copy the project but drop generated / heavy trees. Keep the committed
+ // .esengine/asset-groups.json — it's what makes assets/cdn a remote group.
+ filter: (src) => {
+ const p = src.replace(/\\/g, '/');
+ if (p.includes('/node_modules') || p.includes('/dist')) return false;
+ const i = p.indexOf('/.esengine/');
+ return i < 0 || p.slice(i + '/.esengine/'.length).startsWith('asset-groups.json');
+ },
});
- writeFileSync(path.join(REDSRC, 'remote', 'cdn', 'art.png'), solidPng(64, 64, [220, 40, 40, 255]));
+ writeFileSync(path.join(REDSRC, 'assets', 'cdn', 'art.png'), solidPng(64, 64, [220, 40, 40, 255]));
const cdn = await exportGame(opts(REDSRC, CDN));
expect(cdn.ok, cdn.errors.join('; ')).toBe(true);
}, 180_000);
diff --git a/examples/hot-update-demo/.esengine/asset-groups.json b/examples/hot-update-demo/.esengine/asset-groups.json
new file mode 100644
index 000000000..4420ab104
--- /dev/null
+++ b/examples/hot-update-demo/.esengine/asset-groups.json
@@ -0,0 +1,11 @@
+{
+ "version": "1.0",
+ "groups": {
+ "cdn": { "folder": "assets/cdn", "mode": "remote" }
+ },
+ "activeProfile": "dev",
+ "profiles": {
+ "dev": { "remoteRoot": "" },
+ "prod": { "remoteRoot": "https://cdn.example.com/hot-update-demo" }
+ }
+}
diff --git a/examples/hot-update-demo/README.md b/examples/hot-update-demo/README.md
index 2a65736c1..eea4d164c 100644
--- a/examples/hot-update-demo/README.md
+++ b/examples/hot-update-demo/README.md
@@ -14,9 +14,21 @@ Nothing is ever overwritten, so a cache can never go stale.
### The pieces
-- **`remote/cdn/art.png`** — a texture in a **`remote` group**. The
- `remote/<name>/` folder convention tells the cook this asset is delivered from
- a CDN (bundle mode `remote`), not baked into the package.
+- **`assets/cdn/art.png`** — a texture assigned to a **`remote` group** by the
+ project's delivery config, so it's delivered from a CDN (bundle mode `remote`),
+ not baked into the package.
+- **`.esengine/asset-groups.json`** — the delivery config. `assets/cdn` is an
+ ordinarily-named folder; the config is what marks it a remote group, and build
+ profiles (`dev` / `prod`) carry the CDN root per environment:
+ ```json
+ {
+ "groups": { "cdn": { "folder": "assets/cdn", "mode": "remote" } },
+ "activeProfile": "dev",
+ "profiles": { "dev": { "remoteRoot": "" }, "prod": { "remoteRoot": "https://cdn.example.com/hot-update-demo" } }
+ }
+ ```
+ (The legacy `remote/<name>/` / `subpackages/<name>/` folder names still work as a
+ zero-config default when there is no `asset-groups.json`.)
- **`src/systems/hotUpdate.ts`** — on start, calls `Assets.loadGroup('cdn')` to
fetch the remote texture and stamps its handle onto the display sprite. It also
subscribes to `Assets.onInvalidate` so that when an update lands, it reloads the
diff --git a/examples/hot-update-demo/remote/cdn/art.png b/examples/hot-update-demo/assets/cdn/art.png
similarity index 100%
rename from examples/hot-update-demo/remote/cdn/art.png
rename to examples/hot-update-demo/assets/cdn/art.png
diff --git a/examples/hot-update-demo/remote/cdn/art.png.meta b/examples/hot-update-demo/assets/cdn/art.png.meta
similarity index 100%
rename from examples/hot-update-demo/remote/cdn/art.png.meta
rename to examples/hot-update-demo/assets/cdn/art.png.meta
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 40363a7a8..687fab122 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1305 stable · 17 beta · 0 deprecated
+Symbols: 1313 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -493,6 +493,25 @@ static prototype: ArrayDataSource<any>
'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller'
```
+## AssetGroupDef — interface
+```
+folder: string
+mode: AssetGroupMode
+```
+
+## AssetGroupMode — type
+```
+'local' | 'subpackage' | 'remote'
+```
+
+## AssetGroupsConfig — interface
+```
+activeProfile: string | undefined
+groups: Record<string, AssetGroupDef> | undefined
+profiles: Record<string, BuildProfile> | undefined
+version: string
+```
+
## AssetPlugin — class
```
build: (app: App) => void
@@ -1037,6 +1056,11 @@ origin: Vec2 | undefined
width: number
```
+## BuildProfile — interface
+```
+remoteRoot: string | undefined
+```
+
## BuiltinBridge — class
```
connect: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@@ -4526,8 +4550,10 @@ entrySceneName: string | undefined
extraScenes: { name: string; data?: SceneData; path?: string; }[] | undefined
manifest: AddressableManifest | null | undefined
module: ESEngineModule
+persistUpdateKey: string | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+remoteRoot: string | undefined
sceneData: SceneData
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
@@ -5174,6 +5200,12 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>
static prototype: ResMutInstance<any>
```
+## ResolvedAssetGroup — interface
+```
+delivery: BundleMode
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -5289,9 +5321,11 @@ catalog: Catalog | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule
+persistUpdateKey: string | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
physicsModule: PhysicsWasmModule | null | undefined
+remoteRoot: string | undefined
scenes: { name: string; data?: SceneData; path?: string; }[]
source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
@@ -7796,6 +7830,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## activeRemoteRoot — function
+```
+(config: AssetGroupsConfig | null | undefined): string | undefined
+```
+
## addAnimatorParam — function
```
(def: AnimatorControllerDef, name: string, type: AnimatorParamType): AnimatorControllerDef
@@ -9036,6 +9075,11 @@ Mesh2DPlugin
(raw: SceneData): SceneMigrationResult
```
+## modeToDelivery — function
+```
+(mode: AssetGroupMode): BundleMode
+```
+
## moveAnimatorState — function
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -9446,6 +9490,11 @@ ReplicationPlugin
(world: World, sceneData: SceneData): Map<number, Entity>
```
+## resolveAssetGroup — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 802230263..ea1513bf0 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1304 stable · 19 beta · 0 deprecated
+Symbols: 1312 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -488,6 +488,25 @@ static prototype: ArrayDataSource<any>
'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller'
```
+## AssetGroupDef — interface
+```
+folder: string
+mode: AssetGroupMode
+```
+
+## AssetGroupMode — type
+```
+'local' | 'subpackage' | 'remote'
+```
+
+## AssetGroupsConfig — interface
+```
+activeProfile: string | undefined
+groups: Record<string, AssetGroupDef> | undefined
+profiles: Record<string, BuildProfile> | undefined
+version: string
+```
+
## AssetPlugin — class
```
build: (app: App) => void
@@ -1032,6 +1051,11 @@ origin: Vec2 | undefined
width: number
```
+## BuildProfile — interface
+```
+remoteRoot: string | undefined
+```
+
## BuiltinBridge — class
```
connect: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@@ -4521,8 +4545,10 @@ entrySceneName: string | undefined
extraScenes: { name: string; data?: SceneData; path?: string; }[] | undefined
manifest: AddressableManifest | null | undefined
module: ESEngineModule
+persistUpdateKey: string | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+remoteRoot: string | undefined
sceneData: SceneData
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
@@ -5169,6 +5195,12 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>
static prototype: ResMutInstance<any>
```
+## ResolvedAssetGroup — interface
+```
+delivery: BundleMode
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -5284,9 +5316,11 @@ catalog: Catalog | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule
+persistUpdateKey: string | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
physicsModule: PhysicsWasmModule | null | undefined
+remoteRoot: string | undefined
scenes: { name: string; data?: SceneData; path?: string; }[]
source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
@@ -7791,6 +7825,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## activeRemoteRoot — function
+```
+(config: AssetGroupsConfig | null | undefined): string | undefined
+```
+
## addAnimatorParam — function
```
(def: AnimatorControllerDef, name: string, type: AnimatorParamType): AnimatorControllerDef
@@ -9036,6 +9075,11 @@ Mesh2DPlugin
(raw: SceneData): SceneMigrationResult
```
+## modeToDelivery — function
+```
+(mode: AssetGroupMode): BundleMode
+```
+
## moveAnimatorState — function
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -9451,6 +9495,11 @@ ReplicationPlugin
(world: World, sceneData: SceneData): Map<number, Entity>
```
+## resolveAssetGroup — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 33d74f54b..3e6d2ceb1 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1315 stable · 17 beta · 0 deprecated
+Symbols: 1323 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -488,6 +488,25 @@ static prototype: ArrayDataSource<any>
'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller'
```
+## AssetGroupDef — interface
+```
+folder: string
+mode: AssetGroupMode
+```
+
+## AssetGroupMode — type
+```
+'local' | 'subpackage' | 'remote'
+```
+
+## AssetGroupsConfig — interface
+```
+activeProfile: string | undefined
+groups: Record<string, AssetGroupDef> | undefined
+profiles: Record<string, BuildProfile> | undefined
+version: string
+```
+
## AssetPlugin — class
```
build: (app: App) => void
@@ -1032,6 +1051,11 @@ origin: Vec2 | undefined
width: number
```
+## BuildProfile — interface
+```
+remoteRoot: string | undefined
+```
+
## BuiltinBridge — class
```
connect: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@@ -4528,8 +4552,10 @@ entrySceneName: string | undefined
extraScenes: { name: string; data?: SceneData; path?: string; }[] | undefined
manifest: AddressableManifest | null | undefined
module: ESEngineModule
+persistUpdateKey: string | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+remoteRoot: string | undefined
sceneData: SceneData
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
@@ -5176,6 +5202,12 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>
static prototype: ResMutInstance<any>
```
+## ResolvedAssetGroup — interface
+```
+delivery: BundleMode
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -5291,9 +5323,11 @@ catalog: Catalog | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule
+persistUpdateKey: string | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
physicsModule: PhysicsWasmModule | null | undefined
+remoteRoot: string | undefined
scenes: { name: string; data?: SceneData; path?: string; }[]
source: RuntimeAssetSource
spineManager: SpineManager | null | undefined
@@ -7815,6 +7849,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## activeRemoteRoot — function
+```
+(config: AssetGroupsConfig | null | undefined): string | undefined
+```
+
## addAnimatorParam — function
```
(def: AnimatorControllerDef, name: string, type: AnimatorParamType): AnimatorControllerDef
@@ -9060,6 +9099,11 @@ Mesh2DPlugin
(raw: SceneData): SceneMigrationResult
```
+## modeToDelivery — function
+```
+(mode: AssetGroupMode): BundleMode
+```
+
## moveAnimatorState — function
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -9470,6 +9514,11 @@ ReplicationPlugin
(world: World, sceneData: SceneData): Map<number, Entity>
```
+## resolveAssetGroup — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/src/asset/assetGroups.ts b/sdk/src/asset/assetGroups.ts
new file mode 100644
index 000000000..2f83e5685
--- /dev/null
+++ b/sdk/src/asset/assetGroups.ts
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file assetGroups.ts
+ * @brief The project's asset-delivery configuration model + resolver.
+ *
+ * `.esengine/asset-groups.json` is the SINGLE authored source for *which assets
+ * ship where*: any folder can be marked a delivery group (local / subpackage /
+ * remote-CDN), decoupling the delivery decision from a magic folder NAME. Build
+ * profiles carry the CDN root per environment (dev / prod). This module is the
+ * pure model + resolver shared by BOTH the cook (staging + manifest) and the
+ * editor Play realm (its addressable manifest) — one implementation, so the two
+ * can never disagree about what group an asset is in.
+ *
+ * Pure and dependency-free (no fs / DOM); the fs load lives in the cook / editor.
+ */
+import type { BundleMode } from './AddressableManifest';
+
+/** User-facing delivery mode for a group. `subpackage` maps to the manifest's
+ * `lazy` bundle mode; `local`/`remote` map to themselves. */
+export type AssetGroupMode = 'local' | 'subpackage' | 'remote';
+
+/** One authored group: every asset under `folder` (recursively) joins it. */
+export interface AssetGroupDef {
+ /** Project-relative folder whose assets belong to this group. */
+ folder: string;
+ mode: AssetGroupMode;
+}
+
+/** A build environment's variables — currently just the CDN root remote groups
+ * are served from (dev vs prod differ; the export bakes the active one in). */
+export interface BuildProfile {
+ remoteRoot?: string;
+}
+
+/** The whole `.esengine/asset-groups.json` document. */
+export interface AssetGroupsConfig {
+ version: string;
+ /** groupName → definition. */
+ groups?: Record<string, AssetGroupDef>;
+ /** Which profile is active for a build (key into `profiles`). */
+ activeProfile?: string;
+ profiles?: Record<string, BuildProfile>;
+}
+
+/** The group + delivery an asset resolves to (delivery is the manifest's typed
+ * {@link BundleMode}, so cook staging / manifest / runtime all speak one type). */
+export interface ResolvedAssetGroup {
+ name: string;
+ delivery: BundleMode;
+}
+
+/** Map a user-facing mode to the manifest bundle mode (`subpackage` → `lazy`). */
+export function modeToDelivery(mode: AssetGroupMode): BundleMode {
+ return mode === 'subpackage' ? 'lazy' : mode;
+}
+
+const SUBPACKAGE_RE = /^subpackages\/([^/]+)\//;
+const REMOTE_RE = /^remote\/([^/]+)\//;
+
+/**
+ * The delivery group an asset belongs to, in priority order:
+ * 1. An explicit `config.groups` entry whose `folder` is (the longest) prefix
+ * of the asset's path — the modern, name-decoupled configuration.
+ * 2. The legacy folder-name convention (`subpackages/<name>/` → lazy,
+ * `remote/<name>/` → remote) — kept as a zero-config default / back-compat.
+ * 3. `main` / `local` — the eagerly-shipped default.
+ *
+ * Pure: `config` is the parsed document (or null when the project has none).
+ * The SINGLE resolver the cook and the editor Play realm both call.
+ */
+export function resolveAssetGroup(
+ projectRelPath: string,
+ config: AssetGroupsConfig | null | undefined,
+): ResolvedAssetGroup {
+ const path = projectRelPath.replace(/\\/g, '/');
+
+ if (config?.groups) {
+ let best: { name: string; mode: AssetGroupMode; len: number } | null = null;
+ for (const [name, def] of Object.entries(config.groups)) {
+ const folder = def.folder.replace(/\\/g, '/').replace(/\/+$/, '');
+ if (folder === '' ) continue;
+ if (path === folder || path.startsWith(`${folder}/`)) {
+ if (!best || folder.length > best.len) best = { name, mode: def.mode, len: folder.length };
+ }
+ }
+ if (best) return { name: best.name, delivery: modeToDelivery(best.mode) };
+ }
+
+ const sub = SUBPACKAGE_RE.exec(path);
+ if (sub) return { name: sub[1], delivery: 'lazy' };
+ const rem = REMOTE_RE.exec(path);
+ if (rem) return { name: rem[1], delivery: 'remote' };
+
+ return { name: 'main', delivery: 'local' };
+}
+
+/** The CDN root of the active build profile (the value the export bakes into the
+ * shipped `game.config.json` so `remote`-group assets resolve against it).
+ * Undefined when no profile / no root is set. */
+export function activeRemoteRoot(config: AssetGroupsConfig | null | undefined): string | undefined {
+ const active = config?.activeProfile;
+ if (!active) return undefined;
+ const root = config?.profiles?.[active]?.remoteRoot;
+ return root && root.trim() !== '' ? root.replace(/\/+$/, '') : undefined;
+}
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 9b4b8e3b4..dc4a30dda 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -12,6 +12,16 @@ export {
ManifestModel,
} from './AddressableManifest';
export { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';
+export {
+ resolveAssetGroup,
+ activeRemoteRoot,
+ modeToDelivery,
+ type AssetGroupMode,
+ type AssetGroupDef,
+ type BuildProfile,
+ type AssetGroupsConfig,
+ type ResolvedAssetGroup,
+} from './assetGroups';
export { xxh64, contentHashHex, contentHashOf } from './contentHash';
export { AsyncCache } from './AsyncCache';
export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index a23dd6d8c..946de2358 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -67,6 +67,14 @@ export {
BUNDLE_MODES,
normalizeBundleMode,
ManifestModel,
+ resolveAssetGroup,
+ activeRemoteRoot,
+ modeToDelivery,
+ type AssetGroupMode,
+ type AssetGroupDef,
+ type BuildProfile,
+ type AssetGroupsConfig,
+ type ResolvedAssetGroup,
type AssetsData,
type TextureInfo,
type SpineLoadResult,
diff --git a/sdk/tests/asset-groups.test.ts b/sdk/tests/asset-groups.test.ts
new file mode 100644
index 000000000..a54f74f38
--- /dev/null
+++ b/sdk/tests/asset-groups.test.ts
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import {
+ resolveAssetGroup,
+ activeRemoteRoot,
+ modeToDelivery,
+ type AssetGroupsConfig,
+} from '../src/asset/assetGroups';
+
+describe('modeToDelivery', () => {
+ it('maps subpackage → lazy, others to themselves', () => {
+ expect(modeToDelivery('subpackage')).toBe('lazy');
+ expect(modeToDelivery('remote')).toBe('remote');
+ expect(modeToDelivery('local')).toBe('local');
+ });
+});
+
+describe('resolveAssetGroup — explicit config decouples delivery from folder name', () => {
+ const config: AssetGroupsConfig = {
+ version: '1.0',
+ groups: {
+ dlc: { folder: 'assets/dlc', mode: 'remote' },
+ level2: { folder: 'assets/level2', mode: 'subpackage' },
+ hd: { folder: 'assets/dlc/hd', mode: 'subpackage' }, // nested, longer prefix
+ },
+ };
+
+ it('assigns an ordinarily-named folder to a remote group', () => {
+ expect(resolveAssetGroup('assets/dlc/boss.png', config)).toEqual({ name: 'dlc', delivery: 'remote' });
+ });
+
+ it('maps a subpackage-mode group to lazy delivery', () => {
+ expect(resolveAssetGroup('assets/level2/map.png', config)).toEqual({ name: 'level2', delivery: 'lazy' });
+ });
+
+ it('longest folder prefix wins for nested groups', () => {
+ expect(resolveAssetGroup('assets/dlc/hd/[email protected]', config)).toEqual({ name: 'hd', delivery: 'lazy' });
+ expect(resolveAssetGroup('assets/dlc/boss.png', config)).toEqual({ name: 'dlc', delivery: 'remote' });
+ });
+
+ it('unconfigured paths fall through to main/local', () => {
+ expect(resolveAssetGroup('assets/hero.png', config)).toEqual({ name: 'main', delivery: 'local' });
+ });
+
+ it('normalizes backslashes and a trailing folder slash', () => {
+ const cfg: AssetGroupsConfig = { version: '1.0', groups: { g: { folder: 'assets/g/', mode: 'remote' } } };
+ expect(resolveAssetGroup('assets\\g\\a.png', cfg)).toEqual({ name: 'g', delivery: 'remote' });
+ });
+});
+
+describe('resolveAssetGroup — legacy folder-name convention (fallback / back-compat)', () => {
+ it('still honors subpackages/<name>/ and remote/<name>/ with no config', () => {
+ expect(resolveAssetGroup('subpackages/level1/a.png', null)).toEqual({ name: 'level1', delivery: 'lazy' });
+ expect(resolveAssetGroup('remote/cdn/a.png', null)).toEqual({ name: 'cdn', delivery: 'remote' });
+ expect(resolveAssetGroup('assets/a.png', null)).toEqual({ name: 'main', delivery: 'local' });
+ });
+
+ it('explicit config takes priority over the folder-name convention', () => {
+ const cfg: AssetGroupsConfig = { version: '1.0', groups: { pack: { folder: 'remote/cdn', mode: 'subpackage' } } };
+ // The path is under remote/cdn/, but the config re-declares it a subpackage.
+ expect(resolveAssetGroup('remote/cdn/a.png', cfg)).toEqual({ name: 'pack', delivery: 'lazy' });
+ });
+});
+
+describe('activeRemoteRoot', () => {
+ const config: AssetGroupsConfig = {
+ version: '1.0',
+ activeProfile: 'dev',
+ profiles: {
+ dev: { remoteRoot: 'http://localhost:8080/' },
+ prod: { remoteRoot: 'https://cdn.mygame.com' },
+ },
+ };
+
+ it('returns the active profile CDN root, trailing slash trimmed', () => {
+ expect(activeRemoteRoot(config)).toBe('http://localhost:8080');
+ });
+
+ it('follows activeProfile when switched', () => {
+ expect(activeRemoteRoot({ ...config, activeProfile: 'prod' })).toBe('https://cdn.mygame.com');
+ });
+
+ it('undefined when no active profile / no root / no config', () => {
+ expect(activeRemoteRoot(null)).toBeUndefined();
+ expect(activeRemoteRoot({ version: '1.0' })).toBeUndefined();
+ expect(activeRemoteRoot({ version: '1.0', activeProfile: 'x', profiles: { x: {} } })).toBeUndefined();
+ expect(activeRemoteRoot({ version: '1.0', activeProfile: 'missing', profiles: { dev: { remoteRoot: 'u' } } })).toBeUndefined();
+ });
+});