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.

fix(minigame): a hot update reaches a mini-game, and survives its next launch offline

esenginedf16612c288f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9459bf781..3ca192e80 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,8 @@ published separately; it ships inside the editor.
### Fixed
+- A hot update reports how far it got — verified, applied, stored for the next launch, cached for offline — instead of one `ok`; two updates at once no longer both commit or lose the newer one; and an update stored by an older build no longer covers a newer one the player installed.
+- A hot update on a mini-game is stored for the next launch and its assets are cached on the device, so the updated game starts offline; before, a mini-game went back to what shipped.
- A Douyin recording the host ends on its own keeps its video, and an interruption is not counted as recorded time.
## [0.72.0] - 2026-09-24
diff --git a/docs/astro/src/content/docs/publishing/hot-update.mdx b/docs/astro/src/content/docs/publishing/hot-update.mdx
index 1777b52ce..e45d5b683 100644
--- a/docs/astro/src/content/docs/publishing/hot-update.mdx
+++ b/docs/astro/src/content/docs/publishing/hot-update.mdx
@@ -244,6 +244,7 @@ The hot-update surface lives on the `Assets` resource (`Res(Assets)`):
| `checkForUpdate(options)` | `Promise<UpdatePlan>` | Fetch a candidate manifest, diff it against the active one, and stage it. Downloads no assets. |
| `applyUpdate(onProgress?)` | `Promise<ApplyUpdateResult>` | Apply the staged update **atomically**: download + verify every changed asset, then swap the manifest, rebind live handles, and persist. `onProgress(loaded, total)` reports download progress. |
| `restorePersistedUpdate(key)` | `boolean` | At boot, restore the manifest a prior `applyUpdate` persisted under `key`. The runtime calls this for you when `persistUpdateKey` is set. |
+| `updateStatus()` | `UpdateStatus` | `{ revision, persistedRevision, staged, applying }` — for a diagnostics screen. |
| `setRemoteRoot(url?)` | `void` | Point remote-group resolution at a CDN root (`undefined` clears it → same-origin). The runtime sets this from the build's `remoteRoot`. |
| `remoteRoot` | `string \| undefined` | The active CDN root (getter). |
| `onInvalidate(listener)` | `() => void` | Subscribe to invalidations. The listener receives `{ ref, type, oldValue }` (for custom rebinding); returns an unsubscribe function. |
@@ -275,6 +276,23 @@ The hot-update surface lives on the `Assets` resource (`Res(Assets)`):
| `ok` | `boolean` | True only when every changed asset downloaded + verified and the manifest was swapped. |
| `updated` | `number` | How many assets were applied (`0` on failure). |
| `failed` | `AssetDownloadFailure[]` | Why it rolled back — each `{ path, reason: 'fetch' \| 'integrity' }`. |
+| `stages` | `UpdateStages` | How far it got — see below. `ok` alone does not say whether the next launch keeps the update. |
+| `revision` | `string \| null` | The revision this session runs on afterwards. |
+| `uncached` | `string[]` | Changed assets the disk cache refused, by url — what the next launch fetches again. |
+| `reason` | `'nothing-staged'` *(optional)* | Nothing was attempted: no update is staged (none was checked, or another `applyUpdate` already took it). |
+
+**`UpdateStages`** — each is its own answer:
+
+| Field | Type | Description |
+| --- | --- | --- |
+| `verified` | `boolean` | Every changed asset downloaded and matched its content hash. |
+| `applied` | `boolean` | This session runs on the new manifest, and its assets have settled on it. |
+| `persisted` | `boolean \| null` | The next launch starts on it: stored and read back. `false` when storage refused (a full quota); `null` with no persistence key. |
+| `cached` | `boolean \| null` | Every changed remote asset is in the disk cache, so the next launch reads it without the network. `null` where the platform keeps no cache (web). |
+
+`updateStatus()` answers the same questions at any time: the revision running now,
+the one the next launch starts on, what is staged and what it would download, and
+whether an apply is in progress.
## On-demand groups (DLC)
@@ -327,17 +345,24 @@ half-applied update is impossible.
When `persistUpdateKey` is set (the export does this automatically), `applyUpdate`
saves the applied manifest to platform storage. At the next boot the runtime calls
`restorePersistedUpdate(key)` and the player starts **directly on the updated
-content — even with no network**. On native and mini-game targets the verified
-bytes are also written to a content-addressed **disk cache**, so updated assets
-load offline without re-hitting the CDN.
+content**. On targets with a disk cache the verified bytes are also written to it,
+so updated assets load **without the network**; `stages.cached` says whether they
+all made it.
+
+A stored update belongs to the package it was applied to. When the player installs
+a newer build (a new web deploy, an app-store update), the stored update is older
+than what shipped, so it is dropped and the game starts on the new package.
+
+Applies run one at a time. An update found while another is downloading stays
+staged, and applying it downloads only what the first one did not already bring.
## Platform support
| Target | Manifest + diff | CDN fetch | Persist | Disk cache |
| --- | --- | --- | --- | --- |
-| **Web** | ✅ | ✅ (CORS/CSP apply) | `localStorage` | browser HTTP cache |
+| **Web** | ✅ | ✅ (CORS/CSP apply) | `localStorage` | — (the next launch refetches from the CDN) |
| **Desktop** | ✅ | ✅ | ✅ | ✅ (content-addressed) |
-| **WeChat MiniGame** | ✅ | ✅ | ✅ | ✅ |
+| **Mini-games** (WeChat, Douyin, …) | ✅ | ✅ | ✅ | ✅ (the host's user data directory) |
| **Native (iOS / Android)** | ✅ | ✅ | ✅ | ✅ |
The manifest diff is pure and platform-agnostic; only the fetch, storage, and
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 448b35bc0..ad1092529 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 103,
- "experimental": 2110,
+ "experimental": 2113,
"deprecated": 3
},
- "total": 2328,
+ "total": 2331,
"subsystems": [
{
"id": "ecs",
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index e737cba9f..765dc94b0 100644
--- a/pipeline/src/export/exportGame.ts
+++ b/pipeline/src/export/exportGame.ts
@@ -25,12 +25,12 @@ import { runtimeHostEntry } from '../bundle/runtimeHosts';
import { writeFile, readFile, mkdir, cp, readdir, rm } from 'node:fs/promises';
import { existsSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
-import { cookAssets, loadAssetGroups, type CookManifest, type Inclusion } from '../assets/cookAssets';
+import { cookAssets, type CookManifest, type Inclusion } from '../assets/cookAssets';
import { cookWorlds, streamedScenes } from '../world/cookWorld';
import { buildAddressableManifest } from '../assets/addressableManifest';
-import { activeRemoteRoot } from '../../../sdk/src/asset/assetGroups';
import type { DebugChannelConfig, PackagedGameConfig } from 'esengine';
import { packagedDebugChannel } from './debugChannel';
+import { packagedHotUpdate } from './hotUpdateConfig';
import {
DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, type RuntimeProjectConfig,
} from '../project/runtimeConfig';
@@ -709,6 +709,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
runtime,
minify: opts.minify,
debugChannel: opts.debugChannel,
+ hotUpdate: opts.hotUpdate,
emcc: opts.emcc,
aotMode: opts.aotMode,
contentAddressed: opts.contentAddressed,
@@ -749,6 +750,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
runtime,
minify: opts.minify,
debugChannel: opts.debugChannel,
+ hotUpdate: opts.hotUpdate,
emcc: opts.emcc,
aotMode: opts.aotMode,
contentAddressed: opts.contentAddressed,
@@ -899,15 +901,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// asset model in the package — the mini-game export has always done this.
await rm(path.join(payloadDir, 'assets.manifest.json'), { force: true });
- // 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;
+ const hotUpdate = await packagedHotUpdate(opts.root, opts.hotUpdate);
// What wasm this project's content pulls in — evidence for the plan below, and
// the filter the runtime tree is copied through further down.
diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.ts
index f4d891b47..336cf1316 100644
--- a/pipeline/src/export/exportMiniGame.ts
+++ b/pipeline/src/export/exportMiniGame.ts
@@ -30,6 +30,7 @@
*/
import type { DebugChannelConfig } from 'esengine';
import { packagedDebugChannel } from './debugChannel';
+import { packagedHotUpdate } from './hotUpdateConfig';
import { loadEsbuild } from '../bundle/esbuildRuntime';
import type { ProjectFeatures, ProjectPackaging } from '../project/format';
import {
@@ -291,6 +292,8 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
runtime?: RuntimeProjectConfig;
minify?: boolean;
debugChannel?: DebugChannelConfig | null;
+ /** Overrides the project's own CDN root / persistence key (see `packagedHotUpdate`). */
+ hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };
/**
* Where emcc is, for the systems a project marked `@compiled`
* (docs/REARCH_AOT.md). Absent ⇒ found from the environment; a project that
@@ -482,6 +485,8 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
.join('');
const debugChannel = packagedDebugChannel(opts);
const debugArg = debugChannel ? `, debugChannel: ${JSON.stringify(debugChannel)}` : '';
+ const hotUpdate = await packagedHotUpdate(opts.root, opts.hotUpdate);
+ const hotUpdateArg = hotUpdate ? `, hotUpdate: ${JSON.stringify(hotUpdate)}` : '';
// esengine/minigame installs no platform until a host is named, so boot() names
// one: a built-in points at a shipped module, a project vendor at a file beside
// its own platform. Unjoined, the package builds and throws on the device.
@@ -545,7 +550,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
`export function boot(engineFactory, sideModuleFactories) {\n` +
(profile.platformInit ? ` ${profile.platformInit}();\n` : '') +
(installsPlatform ? ` installMiniGamePlatform(__platformProfile);\n` : '') +
- ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}${runtimeLayout.sideModuleSuffix === '.wasm' ? '' : `, sideModuleSuffix: ${JSON.stringify(runtimeLayout.sideModuleSuffix)}`}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${runtimeArgs}${projectDeclarations.length > 0 ? `, sideModules: ${JSON.stringify(projectDeclarations)}` : ''}${aotArg}${debugArg} });\n` +
+ ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}${runtimeLayout.sideModuleSuffix === '.wasm' ? '' : `, sideModuleSuffix: ${JSON.stringify(runtimeLayout.sideModuleSuffix)}`}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${runtimeArgs}${projectDeclarations.length > 0 ? `, sideModules: ${JSON.stringify(projectDeclarations)}` : ''}${aotArg}${debugArg}${hotUpdateArg} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
/** What each subsystem costs in the bundle — empty if esbuild wrote no metafile. */
diff --git a/pipeline/src/export/hotUpdateConfig.ts b/pipeline/src/export/hotUpdateConfig.ts
new file mode 100644
index 000000000..c83e1d418
--- /dev/null
+++ b/pipeline/src/export/hotUpdateConfig.ts
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file hotUpdateConfig.ts — the hot-update delivery a package carries.
+ */
+import { loadAssetGroups } from '../assets/cookAssets';
+import { activeRemoteRoot } from '../../../sdk/src/asset/assetGroups';
+
+/**
+ * Hot-update delivery a package carries: the active build profile's CDN root (an
+ * explicit override wins), plus a persistence key so a returning player boots on
+ * already-updated content. Only when a CDN root is configured — a project with no
+ * remote groups ships nothing extra. Every packaged target asks this one function.
+ */
+export async function packagedHotUpdate(
+ root: string, override?: { remoteRoot?: string; persistUpdateKey?: string },
+): Promise<{ remoteRoot?: string; persistUpdateKey?: string } | undefined> {
+ const remoteRoot = override?.remoteRoot ?? activeRemoteRoot(await loadAssetGroups(root));
+ const persistUpdateKey = override?.persistUpdateKey ?? (remoteRoot ? 'esengine:hotupdate' : undefined);
+ return remoteRoot || persistUpdateKey
+ ? { ...(remoteRoot ? { remoteRoot } : {}), ...(persistUpdateKey ? { persistUpdateKey } : {}) }
+ : undefined;
+}
+
diff --git a/pipeline/tests/export-wechat.test.ts b/pipeline/tests/export-wechat.test.ts
index 8e2869e8c..5586db2a4 100644
--- a/pipeline/tests/export-wechat.test.ts
+++ b/pipeline/tests/export-wechat.test.ts
@@ -256,6 +256,28 @@ describe('exportGame (wechat)', () => {
rmSync(path.join(root, '.esengine'), { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
}, 60_000);
+ it('carries the same hot-update delivery the web road does into the boot call', async () => {
+ const outWx = path.join(root, 'dist-wechat-hotupdate');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: outWx,
+ platform: 'wechat',
+ hotUpdate: { remoteRoot: 'https://cdn.example/v3', persistUpdateKey: 'game:updates' },
+ });
+ expect(res.ok).toBe(true);
+ // Without it a mini-game neither resolved remote groups against its CDN nor
+ // started on an update it had applied: the next launch was the shipped build.
+ const bundle = readFileSync(path.join(outWx, 'game-bundle.js'), 'utf8');
+ const declaration = bundle.match(/hotUpdate:\s*\{[^}]*\}/)?.[0] ?? '(no hotUpdate in the boot call)';
+ expect(declaration).toContain('https://cdn.example/v3');
+ expect(declaration).toContain('game:updates');
+ }, 60_000);
+
it('refuses to substitute a web build for a mini-game one', async () => {
// Serving the web glue would produce a package that builds clean and dies on
// a device — the failure this whole per-platform layout exists to prevent.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 74528bd7a..88b86da88 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: 115 public · 91 beta · 1496 experimental · 3 deprecated
+Symbols: 115 public · 91 beta · 1499 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -816,6 +816,17 @@ static new (): AppContext
static prototype: AppContext
```
+## ApplyUpdateResult — interface @experimental
+```
+failed: AssetDownloadFailure[]
+ok: boolean
+reason: "nothing-staged" | undefined
+revision: string | null
+stages: UpdateStages
+uncached: string[]
+updated: number
+```
+
## ArrayDataSource — class @experimental
```
append: (items: readonly T[]) => void
@@ -1037,6 +1048,7 @@ setRemoteRoot: (url: string | undefined) => void
setTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void
textureFormatReport: () => TextureFormatReport
texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]
+updateStatus: () => UpdateStatus
static create: (options: AssetsOptions) => AssetsClass
static new (options: AssetsOptions): AssetsClass
static prototype: AssetsClass
@@ -9184,6 +9196,22 @@ coverage: number
mesh: MeshData
```
+## UpdateStages — interface @experimental
+```
+applied: boolean
+cached: boolean | null
+persisted: boolean | null
+verified: boolean
+```
+
+## UpdateStatus — interface @experimental
+```
+applying: boolean
+persistedRevision: string | null
+revision: string | null
+staged: { revision: string | null; assets: number; bytes: number; } | null
+```
+
## UploadedGpuFormat — type @experimental
```
CompressedTextureFormat | 'rgba8'
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 380453da5..c27b65967 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 96 beta · 1515 experimental · 3 deprecated
+Symbols: 115 public · 96 beta · 1518 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -816,6 +816,17 @@ static new (): AppContext
static prototype: AppContext
```
+## ApplyUpdateResult — interface @experimental
+```
+failed: AssetDownloadFailure[]
+ok: boolean
+reason: "nothing-staged" | undefined
+revision: string | null
+stages: UpdateStages
+uncached: string[]
+updated: number
+```
+
## ArrayDataSource — class @experimental
```
append: (items: readonly T[]) => void
@@ -1037,6 +1048,7 @@ setRemoteRoot: (url: string | undefined) => void
setTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void
textureFormatReport: () => TextureFormatReport
texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]
+updateStatus: () => UpdateStatus
static create: (options: AssetsOptions) => AssetsClass
static new (options: AssetsOptions): AssetsClass
static prototype: AssetsClass
@@ -9377,6 +9389,22 @@ coverage: number
mesh: MeshData
```
+## UpdateStages — interface @experimental
+```
+applied: boolean
+cached: boolean | null
+persisted: boolean | null
+verified: boolean
+```
+
+## UpdateStatus — interface @experimental
+```
+applying: boolean
+persistedRevision: string | null
+revision: string | null
+staged: { revision: string | null; assets: number; bytes: number; } | null
+```
+
## UploadedGpuFormat — type @experimental
```
CompressedTextureFormat | 'rgba8'
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index f7bc02c2f..aa0f7643b 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: 115 public · 93 beta · 1495 experimental · 3 deprecated
+Symbols: 115 public · 93 beta · 1498 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -811,6 +811,17 @@ static new (): AppContext
static prototype: AppContext
```
+## ApplyUpdateResult — interface @experimental
+```
+failed: AssetDownloadFailure[]
+ok: boolean
+reason: "nothing-staged" | undefined
+revision: string | null
+stages: UpdateStages
+uncached: string[]
+updated: number
+```
+
## ArrayDataSource — class @experimental
```
append: (items: readonly T[]) => void
@@ -1032,6 +1043,7 @@ setRemoteRoot: (url: string | undefined) => void
setTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void
textureFormatReport: () => TextureFormatReport
texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]
+updateStatus: () => UpdateStatus
static create: (options: AssetsOptions) => AssetsClass
static new (options: AssetsOptions): AssetsClass
static prototype: AssetsClass
@@ -9179,6 +9191,22 @@ coverage: number
mesh: MeshData
```
+## UpdateStages — interface @experimental
+```
+applied: boolean
+cached: boolean | null
+persisted: boolean | null
+verified: boolean
+```
+
+## UpdateStatus — interface @experimental
+```
+applying: boolean
+persistedRevision: string | null
+revision: string | null
+staged: { revision: string | null; assets: number; bytes: number; } | null
+```
+
## UploadedGpuFormat — type @experimental
```
CompressedTextureFormat | 'rgba8'
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index e5023c226..bc746e636 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 91 beta · 1517 experimental · 3 deprecated
+Symbols: 115 public · 91 beta · 1520 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -811,6 +811,17 @@ static new (): AppContext
static prototype: AppContext
```
+## ApplyUpdateResult — interface @experimental
+```
+failed: AssetDownloadFailure[]
+ok: boolean
+reason: "nothing-staged" | undefined
+revision: string | null
+stages: UpdateStages
+uncached: string[]
+updated: number
+```
+
## ArrayDataSource — class @experimental
```
append: (items: readonly T[]) => void
@@ -1032,6 +1043,7 @@ setRemoteRoot: (url: string | undefined) => void
setTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void
textureFormatReport: () => TextureFormatReport
texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]
+updateStatus: () => UpdateStatus
static create: (options: AssetsOptions) => AssetsClass
static new (options: AssetsOptions): AssetsClass
static prototype: AssetsClass
@@ -5061,6 +5073,7 @@ createImage: () => MiniGameImage
createInnerAudioContext: () => MiniGameInnerAudioContext
createInterstitialAd: ((opts: { adUnitId: string; }) => MiniGameInterstitialAd) | undefined
createRewardedVideoAd: ((opts: { adUnitId: string; }) => MiniGameRewardedVideoAd) | undefined
+env: { USER_DATA_PATH?: string; } | undefined
getFileSystemManager: () => MiniGameFileSystemManager
getGameRecorder: (() => MiniGameWxRecorder) | undefined
getGameRecorderManager: (() => MiniGameTtRecorder) | undefined
@@ -5173,6 +5186,7 @@ onShareRequest: (provide: () => PlatformShareOptions) => void
onUnhandledError: (callback: (error: unknown) => void) => () => void
openDataCanvas: () => PlatformCanvas | null
openDataPostMessage: (message: Record<string, unknown>) => void
+readCacheFile: (key: string) => Promise<ArrayBuffer | null>
readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
removeStorageItem: (key: string) => void
@@ -5182,6 +5196,7 @@ setCloudKeyValues: (entries: Readonly<Record<string, string>>) => boolean
setStorageItem: (key: string, value: string) => void
share: (options: PlatformShareOptions) => void
unbindInputEvents: () => void
+writeCacheFile: (key: string, bytes: ArrayBuffer) => Promise<void>
static new (profile: MiniGameProfile): MiniGamePlatformAdapter
static prototype: MiniGamePlatformAdapter
```
@@ -5222,6 +5237,7 @@ depthLayers: number | undefined
engineFactory: (opts: unknown) => Promise<ESEngineModule>
engineWasmPath: string
firstScene: string
+hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
physicsConfig: Physics2DPluginConfig | undefined
physicsEnabled: boolean | undefined
runtimeConfig: RuntimeBuildConfig | undefined
@@ -9443,6 +9459,22 @@ coverage: number
mesh: MeshData
```
+## UpdateStages — interface @experimental
+```
+applied: boolean
+cached: boolean | null
+persisted: boolean | null
+verified: boolean
+```
+
+## UpdateStatus — interface @experimental
+```
+applying: boolean
+persistedRevision: string | null
+revision: string | null
+staged: { revision: string | null; assets: number; bytes: number; } | null
+```
+
## UploadedGpuFormat — type @experimental
```
CompressedTextureFormat | 'rgba8'
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 09eb61ab2..0a2e48be9 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: 115 public · 91 beta · 1508 experimental · 3 deprecated
+Symbols: 115 public · 91 beta · 1511 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -811,6 +811,17 @@ static new (): AppContext
static prototype: AppContext
```
+## ApplyUpdateResult — interface @experimental
+```
+failed: AssetDownloadFailure[]
+ok: boolean
+reason: "nothing-staged" | undefined
+revision: string | null
+stages: UpdateStages
+uncached: string[]
+updated: number
+```
+
## ArrayDataSource — class @experimental
```
append: (items: readonly T[]) => void
@@ -1032,6 +1043,7 @@ setRemoteRoot: (url: string | undefined) => void
setTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => void
textureFormatReport: () => TextureFormatReport
texturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]
+updateStatus: () => UpdateStatus
static create: (options: AssetsOptions) => AssetsClass
static new (options: AssetsOptions): AssetsClass
static prototype: AssetsClass
@@ -9186,6 +9198,22 @@ coverage: number
mesh: MeshData
```
+## UpdateStages — interface @experimental
+```
+applied: boolean
+cached: boolean | null
+persisted: boolean | null
+verified: boolean
+```
+
+## UpdateStatus — interface @experimental
+```
+applying: boolean
+persistedRevision: string | null
+revision: string | null
+staged: { revision: string | null; assets: number; bytes: number; } | null
+```
+
## UploadedGpuFormat — type @experimental
```
CompressedTextureFormat | 'rgba8'
@@ -9376,6 +9404,7 @@ depthLayers: number | undefined
engineFactory: (opts: unknown) => Promise<ESEngineModule>
engineWasmPath: string | undefined
firstScene: string
+hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
physicsConfig: Physics2DPluginConfig | undefined
physicsEnabled: boolean | undefined
runtimeConfig: RuntimeBuildConfig | undefined
diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.ts
index 412cad96c..e74442155 100644
--- a/sdk/src/platform/minigame/adapter.ts
+++ b/sdk/src/platform/minigame/adapter.ts
@@ -38,7 +38,8 @@ import type {
MiniGameOpenDataContext,
} from './api';
import { createPrimaryPointer } from '../primaryPointer';
-import { mgReadFileSync, mgReadTextFileSync, mgFileExistsSync } from './fs';
+import { mgReadFile, mgReadFileSync, mgReadTextFileSync, mgFileExistsSync } from './fs';
+import { cacheEntryName } from '../cacheEntryName';
import { mgLoadImagePixels } from './image';
import { mgFetch } from './fetch';
import { MiniGameAudioBackend } from '../../audio/MiniGameAudioBackend';
@@ -97,6 +98,28 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {
return mgFileExistsSync(this.fs(), path);
}
+ /** Hot update's content cache, flat under the host's user data directory and
+ * named as on every other platform. */
+ async readCacheFile(key: string): Promise<ArrayBuffer | null> {
+ const dir = this.g_.env?.USER_DATA_PATH;
+ if (!dir) return null;
+ try {
+ return await mgReadFile(this.fs(), `${dir}/${cacheEntryName(key)}`, this.profile_.hostLabel);
+ } catch {
+ return null;
+ }
+ }
+
+ writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {
+ const dir = this.g_.env?.USER_DATA_PATH;
+ if (!dir) return Promise.reject(new Error(`${this.profile_.hostLabel} names no user data directory`));
+ return new Promise((resolve, reject) => this.fs().writeFile({
+ filePath: `${dir}/${cacheEntryName(key)}`, data: bytes,
+ success: () => resolve(),
+ fail: (err) => reject(new Error(err.errMsg)),
+ }));
+ }
+
async loadImagePixels(path: string): Promise<ImageLoadResult> {
return mgLoadImagePixels(this.g_, path);
}
diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.ts
index 8321d96c6..cd4be58e7 100644
--- a/sdk/src/platform/minigame/api.ts
+++ b/sdk/src/platform/minigame/api.ts
@@ -249,6 +249,8 @@ export interface MiniGameSocketTask {
* time, so a vendor missing one degrades gracefully rather than throwing.
*/
export interface MiniGameGlobal {
+ /** The writable directory a game may keep files in (`wx.env.USER_DATA_PATH`). */
+ env?: { USER_DATA_PATH?: string };
createCanvas(): MiniGameCanvas;
createImage(): MiniGameImage;
getFileSystemManager(): MiniGameFileSystemManager;
diff --git a/sdk/src/runtime/miniGameRuntime.ts b/sdk/src/runtime/miniGameRuntime.ts
index f7d3b1e43..8bb2608ca 100644
--- a/sdk/src/runtime/miniGameRuntime.ts
+++ b/sdk/src/runtime/miniGameRuntime.ts
@@ -32,6 +32,7 @@ import type { Physics2DPluginConfig } from '../physics/PhysicsTypes';
import type { SceneData } from '../scene/scene';
import type { AotManifest } from '../ecs/aot/AotSystems';
import type { DebugChannelConfig } from './debugChannel';
+import type { PackagedGameConfig } from './packagedRuntime';
import { log } from '../util/logger';
import { Schedule, defineSystem } from '../ecs/system';
import type { App } from '../app/app';
@@ -164,6 +165,9 @@ export interface MiniGameRuntimeConfig {
*/
aot?: { module: string; manifest: AotManifest };
debugChannel?: DebugChannelConfig;
+ /** The CDN root remote groups resolve against, and the key an applied update
+ * is stored under — the same field every packaged runtime reads. */
+ hotUpdate?: PackagedGameConfig['hotUpdate'];
}
/**
@@ -299,6 +303,8 @@ export async function initMiniGameRuntime(config: MiniGameRuntimeConfig): Promis
aspectRatio: canvas.width / canvas.height,
...(config.aot ? { aot: config.aot } : {}),
...(config.debugChannel ? { debugChannel: config.debugChannel } : {}),
+ remoteRoot: config.hotUpdate?.remoteRoot,
+ persistUpdateKey: config.hotUpdate?.persistUpdateKey,
});
progress.reach('ready');
diff --git a/sdk/tests/minigame-content-cache.test.ts b/sdk/tests/minigame-content-cache.test.ts
new file mode 100644
index 000000000..98ab4c7ff
--- /dev/null
+++ b/sdk/tests/minigame-content-cache.test.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A mini-game keeps hot update's verified bytes under its user data
+ * directory, so an updated asset loads on the next launch without the CDN.
+ */
+import { describe, it, expect } from 'vitest';
+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';
+import { setPlatform, platformWriteCacheFile, platformReadCacheFile } from '../src/platform/base';
+import { cacheEntryName } from '../src/platform/cacheEntryName';
+import type { MiniGameGlobal, MiniGameProfile } from '../src/platform/minigame/api';
+
+const URL = 'https://cdn.example/v2/assets/0123456789abcdef.png';
+
+function host(opts: { dir?: string; refuses?: boolean } = {}) {
+ const files = new Map<string, ArrayBuffer>();
+ const fs = {
+ readFile: (o: { filePath: string; success?: (r: { data: ArrayBuffer }) => void; fail?: (e: { errMsg: string }) => void }) => {
+ const data = files.get(o.filePath);
+ if (data) o.success?.({ data });
+ else o.fail?.({ errMsg: 'readFile:fail no such file or directory' });
+ },
+ writeFile: (o: { filePath: string; data: ArrayBuffer; success?: () => void; fail?: (e: { errMsg: string }) => void }) => {
+ if (opts.refuses) { o.fail?.({ errMsg: 'writeFile:fail the maximum size of the file storage limit is exceeded' }); return; }
+ files.set(o.filePath, o.data);
+ o.success?.();
+ },
+ };
+ const profile: MiniGameProfile = {
+ id: 'wechat',
+ hostLabel: 'Test',
+ global: {
+ getSystemInfoSync: () => ({ pixelRatio: 1, screenWidth: 1, screenHeight: 1, platform: 'devtools', language: 'zh_CN' }),
+ getFileSystemManager: () => fs,
+ ...(opts.dir ? { env: { USER_DATA_PATH: opts.dir } } : {}),
+ } as unknown as MiniGameGlobal,
+ };
+ setPlatform(new MiniGamePlatformAdapter(profile));
+ return files;
+}
+
+describe('a mini-game content cache', () => {
+ it('stores under the user data directory, named as on every platform, and reads it back', async () => {
+ const files = host({ dir: 'wxfile://usr' });
+ const bytes = new Uint8Array([1, 2, 3, 4]).buffer;
+ expect(await platformWriteCacheFile(URL, bytes)).toBe('stored');
+ expect([...files.keys()]).toEqual([`wxfile://usr/${cacheEntryName(URL)}`]);
+ expect(new Uint8Array((await platformReadCacheFile(URL))!)).toEqual(new Uint8Array([1, 2, 3, 4]));
+ });
+
+ it('is a miss, not an error, for what was never stored', async () => {
+ host({ dir: 'wxfile://usr' });
+ expect(await platformReadCacheFile(URL)).toBeNull();
+ });
+
+ it('reports a write the host refused, so the update can say it is not cached', async () => {
+ host({ dir: 'wxfile://usr', refuses: true });
+ expect(await platformWriteCacheFile(URL, new ArrayBuffer(4))).toBe('failed');
+ });
+
+ it('reports a host with no user data directory as failed, not stored', async () => {
+ host();
+ expect(await platformWriteCacheFile(URL, new ArrayBuffer(4))).toBe('failed');
+ expect(await platformReadCacheFile(URL)).toBeNull();
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index c5f9d67d0..0b77e8d2d 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -1060,4 +1060,8 @@ export const NOTED = {
{ note: 'The Frame Debugger can capture and replay a frame of a development build running outside the editor — a browser or a mini-game host, on this machine or another on the network: export with the Development configuration and "Frame debugger connection", then pick the device in the panel. Native apps cannot connect yet.' },
'feat(frame-debugger): capture a frame from a development build running elsewhere':
{ note: 'The Frame Debugger can capture and replay a frame of a development build running outside the editor — a browser or a mini-game host, on this machine or another on the network: export with the Development configuration and "Frame debugger connection", then pick the device in the panel. Native apps cannot connect yet.' },
+ 'fix(hot-update): an update says which stages it reached, and the next launch starts on a whole version':
+ { note: 'A hot update reports how far it got — verified, applied, stored for the next launch, cached for offline — instead of one `ok`; two updates at once no longer both commit or lose the newer one; and an update stored by an older build no longer covers a newer one the player installed.' },
+ 'fix(minigame): a hot update reaches a mini-game, and survives its next launch offline':
+ { note: 'A hot update on a mini-game is stored for the next launch and its assets are cached on the device, so the updated game starts offline; before, a mini-game went back to what shipped.' },
};