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(platform): DOM-free PlatformAdapter + native platform identity

yhh9dafe9df8f1d
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 06cf851f6..3cb872247 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: 1316 stable · 17 beta · 0 deprecated
+Symbols: 1320 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4427,8 +4427,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
clearStorage: (prefix: string) => void
createAudioBackend: () => PlatformAudioBackend
-createCanvas: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas
-createImage: () => HTMLImageElement
+createCanvas: (width: number, height: number) => PlatformCanvas
+createImage: () => PlatformImage
createSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined
createVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined
devicePixelRatio: () => number
@@ -4439,7 +4439,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Impor
language: (() => string) | undefined
loadImagePixels: (path: string) => Promise<ImageLoadResult>
loadSubpackage: ((name: string) => Promise<void>) | undefined
-name: "web" | "wechat" | "douyin" | "node"
+name: "web" | "wechat" | "douyin" | "node" | "native"
now: () => number
onMemoryWarning: ((callback: () => void) => () => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -4466,6 +4466,36 @@ suspend: () => void
unloadBuffer: (handle: AudioBufferHandle) => void
```
+## PlatformCanvas — interface
+```
+getContext: (contextId: "2d", options?: PlatformCanvasContextAttributes) => PlatformCanvas2DContext | null
+height: number
+width: number
+```
+
+## PlatformCanvas2DContext — interface
+```
+clearRect: (x: number, y: number, w: number, h: number) => void
+drawImage: (image: PlatformImageSource, dx: number, dy: number) => void
+fillStyle: PlatformCanvasPaint
+fillText: (text: string, x: number, y: number) => void
+font: string
+getImageData: (sx: number, sy: number, sw: number, sh: number) => PlatformImageData
+measureText: (text: string) => PlatformTextMetrics
+textAlign: string
+textBaseline: string
+```
+
+## PlatformImage — interface
+```
+crossOrigin: string | null | undefined
+height: number
+onerror: PlatformImageEventHandler
+onload: PlatformImageEventHandler
+src: string
+width: number
+```
+
## PlatformRequestOptions — interface
```
body: string | ArrayBuffer | undefined
@@ -8363,7 +8393,7 @@ Plugin
## decodeImageBitmap — function
```
-(src: ImageBitmapSource, flip: boolean): Promise<ImageBitmap>
+(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
```
## decodeImagePixels — function
@@ -8936,6 +8966,11 @@ InputRouter
(ext: string): boolean
```
+## isNative — function
+```
+(): boolean
+```
+
## isNonOrthogonal — function
```
(orientation: number): boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 50f74c36b..a406d136a 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: 1315 stable · 19 beta · 0 deprecated
+Symbols: 1319 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -4422,8 +4422,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
clearStorage: (prefix: string) => void
createAudioBackend: () => PlatformAudioBackend
-createCanvas: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas
-createImage: () => HTMLImageElement
+createCanvas: (width: number, height: number) => PlatformCanvas
+createImage: () => PlatformImage
createSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined
createVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined
devicePixelRatio: () => number
@@ -4434,7 +4434,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Impor
language: (() => string) | undefined
loadImagePixels: (path: string) => Promise<ImageLoadResult>
loadSubpackage: ((name: string) => Promise<void>) | undefined
-name: "web" | "wechat" | "douyin" | "node"
+name: "web" | "wechat" | "douyin" | "node" | "native"
now: () => number
onMemoryWarning: ((callback: () => void) => () => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -4461,6 +4461,36 @@ suspend: () => void
unloadBuffer: (handle: AudioBufferHandle) => void
```
+## PlatformCanvas — interface
+```
+getContext: (contextId: "2d", options?: PlatformCanvasContextAttributes) => PlatformCanvas2DContext | null
+height: number
+width: number
+```
+
+## PlatformCanvas2DContext — interface
+```
+clearRect: (x: number, y: number, w: number, h: number) => void
+drawImage: (image: PlatformImageSource, dx: number, dy: number) => void
+fillStyle: PlatformCanvasPaint
+fillText: (text: string, x: number, y: number) => void
+font: string
+getImageData: (sx: number, sy: number, sw: number, sh: number) => PlatformImageData
+measureText: (text: string) => PlatformTextMetrics
+textAlign: string
+textBaseline: string
+```
+
+## PlatformImage — interface
+```
+crossOrigin: string | null | undefined
+height: number
+onerror: PlatformImageEventHandler
+onload: PlatformImageEventHandler
+src: string
+width: number
+```
+
## PlatformRequestOptions — interface
```
body: string | ArrayBuffer | undefined
@@ -8358,7 +8388,7 @@ Plugin
## decodeImageBitmap — function
```
-(src: ImageBitmapSource, flip: boolean): Promise<ImageBitmap>
+(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
```
## decodeImagePixels — function
@@ -8931,6 +8961,11 @@ InputRouter
(ext: string): boolean
```
+## isNative — function
+```
+(): boolean
+```
+
## isNonOrthogonal — function
```
(orientation: number): boolean
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e5099f7c7..dfd65b228 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: 1326 stable · 17 beta · 0 deprecated
+Symbols: 1330 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -4429,8 +4429,8 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale
bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void
clearStorage: (prefix: string) => void
createAudioBackend: () => PlatformAudioBackend
-createCanvas: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas
-createImage: () => HTMLImageElement
+createCanvas: (width: number, height: number) => PlatformCanvas
+createImage: () => PlatformImage
createSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefined
createVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined
devicePixelRatio: () => number
@@ -4441,7 +4441,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Impor
language: (() => string) | undefined
loadImagePixels: (path: string) => Promise<ImageLoadResult>
loadSubpackage: ((name: string) => Promise<void>) | undefined
-name: "web" | "wechat" | "douyin" | "node"
+name: "web" | "wechat" | "douyin" | "node" | "native"
now: () => number
onMemoryWarning: ((callback: () => void) => () => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -4468,6 +4468,36 @@ suspend: () => void
unloadBuffer: (handle: AudioBufferHandle) => void
```
+## PlatformCanvas — interface
+```
+getContext: (contextId: "2d", options?: PlatformCanvasContextAttributes) => PlatformCanvas2DContext | null
+height: number
+width: number
+```
+
+## PlatformCanvas2DContext — interface
+```
+clearRect: (x: number, y: number, w: number, h: number) => void
+drawImage: (image: PlatformImageSource, dx: number, dy: number) => void
+fillStyle: PlatformCanvasPaint
+fillText: (text: string, x: number, y: number) => void
+font: string
+getImageData: (sx: number, sy: number, sw: number, sh: number) => PlatformImageData
+measureText: (text: string) => PlatformTextMetrics
+textAlign: string
+textBaseline: string
+```
+
+## PlatformImage — interface
+```
+crossOrigin: string | null | undefined
+height: number
+onerror: PlatformImageEventHandler
+onload: PlatformImageEventHandler
+src: string
+width: number
+```
+
## PlatformRequestOptions — interface
```
body: string | ArrayBuffer | undefined
@@ -8382,7 +8412,7 @@ Plugin
## decodeImageBitmap — function
```
-(src: ImageBitmapSource, flip: boolean): Promise<ImageBitmap>
+(src: ImageBitmapSource | PlatformImage, flip: boolean): Promise<ImageBitmap>
```
## decodeImagePixels — function
@@ -8960,6 +8990,11 @@ InputRouter
(ext: string): boolean
```
+## isNative — function
+```
+(): boolean
+```
+
## isNonOrthogonal — function
```
(orientation: number): boolean
diff --git a/sdk/src/asset/imageDecode.ts b/sdk/src/asset/imageDecode.ts
index 83fe71a32..151a104c0 100644
--- a/sdk/src/asset/imageDecode.ts
+++ b/sdk/src/asset/imageDecode.ts
@@ -11,6 +11,7 @@
* `ImageBitmap` sources (uploads every texture upside-down otherwise).
*/
import { platformCreateCanvas } from '../platform/base';
+import type { PlatformImage } from '../platform/types';
/**
* Canonical `createImageBitmap` options. premultiply + colorspace conversion are
@@ -30,8 +31,15 @@ export function imageBitmapOptions(flip: boolean): ImageBitmapOptions {
* (the editor/web TextureLoader). With `flip`, the result samples file-top at v=1;
* upload it with `UNPACK_FLIP_Y_WEBGL` off (the orientation is already baked).
*/
-export function decodeImageBitmap(src: ImageBitmapSource, flip: boolean): Promise<ImageBitmap> {
- return createImageBitmap(src, imageBitmapOptions(flip));
+export function decodeImageBitmap(
+ src: ImageBitmapSource | PlatformImage,
+ flip: boolean,
+): Promise<ImageBitmap> {
+ // The one honest DOM cast in the decode path: `createImageBitmap`'s lib.dom
+ // signature lists DOM sources only, but every host that HAS createImageBitmap
+ // (web/editor/desktop) hands us a real HTMLImageElement — PlatformImage merely
+ // erases its DOM brand. Native decodes via loadImagePixels and never reaches here.
+ return createImageBitmap(src as ImageBitmapSource, imageBitmapOptions(flip));
}
export interface DecodedPixels {
@@ -52,12 +60,9 @@ export async function decodeImagePixels(src: ImageBitmapSource): Promise<Decoded
const canvas = platformCreateCanvas(bitmap.width, bitmap.height);
canvas.width = bitmap.width;
canvas.height = bitmap.height;
- const ctx = canvas.getContext('2d', { willReadFrequently: true }) as
- | CanvasRenderingContext2D
- | OffscreenCanvasRenderingContext2D
- | null;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new Error('imageDecode: 2D context unavailable for pixel decode');
- ctx.drawImage(bitmap as CanvasImageSource, 0, 0);
+ ctx.drawImage(bitmap, 0, 0);
const data = ctx.getImageData(0, 0, bitmap.width, bitmap.height);
return { width: bitmap.width, height: bitmap.height, pixels: new Uint8Array(data.data.buffer) };
} finally {
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index 75d016b89..ea6f2e6da 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -3,6 +3,7 @@
import type { AssetLoader, LoadContext, TextureResult } from '../AssetLoader';
import { linearColorSpace } from '../../env';
import { platformCreateCanvas, platformCreateImage } from '../../platform/base';
+import type { PlatformCanvas, PlatformCanvas2DContext, PlatformImage } from '../../platform/types';
import { decodeImageBitmap } from '../imageDecode';
import { requireResourceManager } from '../../resourceManager';
import type { ESEngineModule } from '../../wasm';
@@ -83,8 +84,8 @@ export class TextureLoader implements AssetLoader<TextureResult> {
this.transcoder_ = await this.transcoderPending_;
return this.transcoder_;
}
- private canvas_: HTMLCanvasElement | OffscreenCanvas | null = null;
- private ctx_: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null = null;
+ private canvas_: PlatformCanvas | null = null;
+ private ctx_: PlatformCanvas2DContext | null = null;
/**
* Optional hook that returns per-asset import settings. Invoked at
* load-time with the ORIGINAL ref (pre-resolution), so callers can key
@@ -109,7 +110,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
setPixelDecoder(decoder: TexturePixelDecoder | null): void { this.pixelDecoder_ = decoder; }
get pixelDecoder(): TexturePixelDecoder | null { return this.pixelDecoder_; }
- private ensureCanvas_(): { canvas: HTMLCanvasElement | OffscreenCanvas; ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D } {
+ private ensureCanvas_(): { canvas: PlatformCanvas; ctx: PlatformCanvas2DContext } {
if (this.canvas_ && this.ctx_) return { canvas: this.canvas_, ctx: this.ctx_ };
this.canvas_ = platformCreateCanvas(256, 256);
const ctx = this.canvas_.getContext('2d', { willReadFrequently: true });
@@ -213,7 +214,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
* on it uploads every texture upside-down. The raw `<img>` fallback keeps the
* flag (it works for element/pixel sources) — see {@link createTextureFromImage}.
*/
- private loadImage(src: string, flip: boolean): Promise<HTMLImageElement | ImageBitmap> {
+ private loadImage(src: string, flip: boolean): Promise<PlatformImage | ImageBitmap> {
return new Promise((resolve, reject) => {
const img = platformCreateImage();
img.crossOrigin = 'anonymous';
@@ -234,7 +235,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
}
private createTextureFromImage(
- img: HTMLImageElement | ImageBitmap, flip: boolean, settings?: TextureImportSettings,
+ img: PlatformImage | ImageBitmap, flip: boolean, settings?: TextureImportSettings,
): TextureResult {
const { width, height } = img;
const gl = this.getWebGL2Context();
@@ -257,7 +258,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
private createTextureWebGL2(
gl: WebGL2RenderingContext,
- img: HTMLImageElement | ImageBitmap,
+ img: PlatformImage | ImageBitmap,
width: number, height: number, flip: boolean,
settings?: TextureImportSettings,
): TextureResult {
@@ -311,7 +312,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
}
private createTextureFallback(
- img: HTMLImageElement | ImageBitmap,
+ img: PlatformImage | ImageBitmap,
width: number, height: number, flip: boolean,
settings?: TextureImportSettings,
): TextureResult {
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 24e71589d..551eb7a37 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -111,6 +111,7 @@ export {
isPlatformInitialized,
isWeChat,
isWeb,
+ isNative,
platformFetch,
platformReadFile,
platformReadTextFile,
@@ -120,6 +121,9 @@ export {
type PlatformType,
type PlatformRequestOptions,
type PlatformResponse,
+ type PlatformCanvas,
+ type PlatformCanvas2DContext,
+ type PlatformImage,
} from './platform';
// =============================================================================
diff --git a/sdk/src/lifecycle.ts b/sdk/src/lifecycle.ts
index 91a06b36a..80fda54fa 100644
--- a/sdk/src/lifecycle.ts
+++ b/sdk/src/lifecycle.ts
@@ -112,11 +112,12 @@ export class LifecyclePlugin implements Plugin {
if (platformType === 'wechat') {
this.cleanupFn_ = setupWeChatLifecycle_(manager, app);
- } else if (typeof document !== 'undefined' && typeof window !== 'undefined') {
+ } else if (platformType !== 'native' && typeof document !== 'undefined' && typeof window !== 'undefined') {
this.cleanupFn_ = setupWebLifecycle_(manager, app);
}
- // Headless hosts (node server, workers) have no visibility/focus
- // signal — the Lifecycle resource still exists, always visible.
+ // Headless hosts (node server, workers) and native (no DOM visibility/focus
+ // signal — a bridge.onShow/onHide seam lands with the shell) keep the
+ // Lifecycle resource, always visible.
}
cleanup(): void {
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index df61e200d..45f6f7c38 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -73,6 +73,16 @@ export function isWeb(): boolean {
return currentPlatform?.name === 'web';
}
+/**
+ * Check if running on a native host (embedded Dawn + JS engine on iOS/Android).
+ * Native has no DOM: offscreen canvas/image throw, textures come from the
+ * pixel-decode path (loadImagePixels), and lifecycle/safe-area treat it like a
+ * headless-but-visible host rather than the web DOM branch.
+ */
+export function isNative(): boolean {
+ return currentPlatform?.name === 'native';
+}
+
// =============================================================================
// Convenience Functions
// =============================================================================
@@ -107,11 +117,14 @@ export async function platformInstantiateWasm(
return getPlatform().instantiateWasm(pathOrBuffer, imports);
}
-export function platformCreateCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
+export function platformCreateCanvas(
+ width: number,
+ height: number,
+): import('./types').PlatformCanvas {
return getPlatform().createCanvas(width, height);
}
-export function platformCreateImage(): HTMLImageElement {
+export function platformCreateImage(): import('./types').PlatformImage {
return getPlatform().createImage();
}
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index 0986c0b6c..6634d5dbb 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -13,6 +13,9 @@ export type {
PlatformResponse,
WasmInstantiateResult,
ImageLoadResult,
+ PlatformCanvas,
+ PlatformCanvas2DContext,
+ PlatformImage,
} from './types';
// Re-export base functions
@@ -24,6 +27,7 @@ export {
isWeChat,
isMiniGame,
isWeb,
+ isNative,
platformFetch,
platformReadFile,
platformReadTextFile,
diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.ts
index e3489a884..1b91252df 100644
--- a/sdk/src/platform/minigame/adapter.ts
+++ b/sdk/src/platform/minigame/adapter.ts
@@ -19,6 +19,8 @@ import type {
WasmInstantiateResult,
InputEventCallbacks,
ImageLoadResult,
+ PlatformCanvas,
+ PlatformImage,
PlatformSocket,
PlatformSocketOptions,
} from '../types';
@@ -77,8 +79,10 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {
return this.profile_.instantiateWasm(pathOrBuffer, imports);
}
- createImage(): HTMLImageElement {
- return this.g_.createImage() as unknown as HTMLImageElement;
+ createImage(): PlatformImage {
+ // MiniGameImage is structurally assignable to PlatformImage (crossOrigin is
+ // optional, its handlers fit the neutral optional-arg shape) — no cast.
+ return this.g_.createImage();
}
/** Download an on-demand subpackage so its files become readable. */
@@ -108,8 +112,10 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {
return () => off?.call(this.g_, listener);
}
- createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
- const canvas = this.g_.createCanvas() as unknown as HTMLCanvasElement;
+ createCanvas(width: number, height: number): PlatformCanvas {
+ // One honest cast: MiniGameCanvas.getContext returns `unknown`, so it is not
+ // structurally assignable to PlatformCanvas's typed 2D getContext.
+ const canvas = this.g_.createCanvas() as unknown as PlatformCanvas;
canvas.width = width;
canvas.height = height;
return canvas;
diff --git a/sdk/src/platform/minigame/image.ts b/sdk/src/platform/minigame/image.ts
index e33f87320..566849830 100644
--- a/sdk/src/platform/minigame/image.ts
+++ b/sdk/src/platform/minigame/image.ts
@@ -6,16 +6,17 @@
* an offscreen 2D canvas → read back pixels.
*/
-import type { ImageLoadResult } from '../types';
+import type { ImageLoadResult, PlatformCanvas2DContext } from '../types';
import type { MiniGameGlobal, MiniGameImage } from './api';
function getOffscreenCanvas(g: MiniGameGlobal, width: number, height: number): {
- ctx: CanvasRenderingContext2D;
+ ctx: PlatformCanvas2DContext;
} {
const canvas = g.createCanvas();
canvas.width = width;
canvas.height = height;
- const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
+ // MiniGameCanvas.getContext returns `unknown`; assert to the neutral 2D context.
+ const ctx = canvas.getContext('2d') as PlatformCanvas2DContext;
return { ctx };
}
@@ -35,7 +36,7 @@ export function mgGetImagePixels(g: MiniGameGlobal, img: MiniGameImage): ImageLo
const { ctx } = getOffscreenCanvas(g, width, height);
ctx.clearRect(0, 0, width, height);
- ctx.drawImage(img as unknown as CanvasImageSource, 0, 0);
+ ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, width, height);
const pixels = new Uint8Array(imageData.data.buffer);
diff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.ts
new file mode 100644
index 000000000..055bbcef9
--- /dev/null
+++ b/sdk/src/platform/native/adapter.ts
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file adapter.ts
+ * @brief The native PlatformAdapter — the same engine wasm + TS SDK running on
+ * an embedded Dawn (WebGPU) + JS engine host (iOS/Android), NOT a WebView.
+ * It owns no OS capability itself: every call delegates to the injected
+ * {@link NativeBridge}. WASM instantiates through the host JS engine's
+ * `WebAssembly` global (like the Node host); textures take the
+ * pixel-decode path (loadImagePixels), so the offscreen DOM
+ * canvas/image methods fail loud rather than pretend.
+ *
+ * @beta Pre-1.0: unshipped native host; the adapter surface will change with the
+ * shell. Internal — reachable via relative import (tests today, an
+ * `esengine/native` bundle entry when the shell lands).
+ */
+
+import type {
+ PlatformAdapter,
+ PlatformRequestOptions,
+ PlatformResponse,
+ WasmInstantiateResult,
+ InputEventCallbacks,
+ ImageLoadResult,
+ PlatformCanvas,
+ PlatformImage,
+} from '../types';
+import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';
+import { NullAudioBackend } from '../../audio/NullAudioBackend';
+import { setPlatform } from '../base';
+import type { NativeBridge, NativeInputListener } from './bridge';
+
+export class NativePlatformAdapter implements PlatformAdapter {
+ readonly name = 'native' as const;
+ private inputCleanup_: (() => void) | null = null;
+
+ constructor(private readonly bridge_: NativeBridge) {}
+
+ async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {
+ const r = await this.bridge_.fetch(url, options);
+ const text = () =>
+ Promise.resolve(r.text ?? new TextDecoder().decode(r.arrayBuffer ?? new ArrayBuffer(0)));
+ return {
+ ok: r.ok,
+ status: r.status,
+ statusText: r.statusText ?? '',
+ headers: r.headers ?? {},
+ json: async <T>() => JSON.parse(await text()) as T,
+ text,
+ arrayBuffer: () =>
+ Promise.resolve(
+ r.arrayBuffer ?? (new TextEncoder().encode(r.text ?? '').buffer as ArrayBuffer),
+ ),
+ };
+ }
+
+ readFile(path: string): Promise<ArrayBuffer> {
+ return this.bridge_.readFile(path);
+ }
+
+ async readTextFile(path: string): Promise<string> {
+ return new TextDecoder().decode(await this.bridge_.readFile(path));
+ }
+
+ fileExists(path: string): Promise<boolean> {
+ return this.bridge_.fileExists(path);
+ }
+
+ loadImagePixels(path: string): Promise<ImageLoadResult> {
+ return this.bridge_.loadImagePixels(path);
+ }
+
+ async instantiateWasm(
+ pathOrBuffer: string | ArrayBuffer,
+ imports: WebAssembly.Imports,
+ ): Promise<WasmInstantiateResult> {
+ // The host JS engine (JavaScriptCore / V8 / Hermes) provides WebAssembly —
+ // no bridge call needed, same as the Node host.
+ const buffer = typeof pathOrBuffer === 'string' ? await this.bridge_.readFile(pathOrBuffer) : pathOrBuffer;
+ const { instance, module } = await WebAssembly.instantiate(buffer, imports);
+ return { instance, module };
+ }
+
+ // No offscreen DOM on native: image decode is the pixel path (loadImagePixels),
+ // and the GPU surface enters via the device handle (out of scope). Fail loud,
+ // like the Node host, instead of returning a fake canvas.
+ createCanvas(_width: number, _height: number): PlatformCanvas {
+ throw new Error('[native] no offscreen 2D canvas — decode via loadImagePixels (Path 2)');
+ }
+
+ createImage(): PlatformImage {
+ throw new Error('[native] no DOM images — decode via loadImagePixels');
+ }
+
+ now(): number {
+ return this.bridge_.now?.() ?? Date.now();
+ }
+
+ devicePixelRatio(): number {
+ return this.bridge_.devicePixelRatio();
+ }
+
+ language(): string {
+ // platformLanguage() normalizes underscores ('zh_CN' → 'zh-CN').
+ return this.bridge_.language?.() ?? 'en';
+ }
+
+ bindInputEvents(callbacks: InputEventCallbacks): void {
+ this.inputCleanup_?.();
+ let primaryTouchId: number | null = null;
+ const listener: NativeInputListener = {
+ onTouchStart: (id, x, y) => {
+ callbacks.onTouchStart?.(id, x, y);
+ if (primaryTouchId === null) {
+ primaryTouchId = id;
+ callbacks.onPointerDown(0, x, y);
+ }
+ },
+ onTouchMove: (id, x, y) => {
+ callbacks.onTouchMove?.(id, x, y);
+ if (id === primaryTouchId) callbacks.onPointerMove(x, y);
+ },
+ onTouchEnd: (id) => {
+ callbacks.onTouchEnd?.(id);
+ if (id === primaryTouchId) {
+ primaryTouchId = null;
+ callbacks.onPointerUp(0);
+ }
+ },
+ onTouchCancel: (id) => {
+ callbacks.onTouchCancel?.(id);
+ if (id === primaryTouchId) {
+ primaryTouchId = null;
+ callbacks.onPointerUp(0);
+ }
+ },
+ onKeyDown: (code) => callbacks.onKeyDown(code),
+ onKeyUp: (code) => callbacks.onKeyUp(code),
+ };
+ this.inputCleanup_ = this.bridge_.registerInput(listener);
+ }
+
+ unbindInputEvents(): void {
+ this.inputCleanup_?.();
+ this.inputCleanup_ = null;
+ }
+
+ // Audio ships with the shell; a silent backend keeps sound-playing gameplay
+ // code running unchanged until then (same choice as the Node host).
+ createAudioBackend(): PlatformAudioBackend {
+ return new NullAudioBackend();
+ }
+
+ getStorageItem(key: string): string | null {
+ return this.bridge_.getStorageItem(key);
+ }
+
+ setStorageItem(key: string, value: string): void {
+ this.bridge_.setStorageItem(key, value);
+ }
+
+ removeStorageItem(key: string): void {
+ this.bridge_.removeStorageItem(key);
+ }
+
+ clearStorage(prefix: string): void {
+ for (const k of this.bridge_.storageKeys()) {
+ if (k.startsWith(prefix)) this.bridge_.removeStorageItem(k);
+ }
+ }
+
+ // createSocket / createVideoBackend / pollGamepads / loadSubpackage /
+ // onMemoryWarning are optional and deferred to the shell.
+}
+
+/** Install a {@link NativePlatformAdapter} built from the host `bridge` as the
+ * active platform. The native shell calls this once at boot, before creating the
+ * engine App (mirrors the web/wechat/node entry points). */
+export function installNativePlatform(bridge: NativeBridge): NativePlatformAdapter {
+ const adapter = new NativePlatformAdapter(bridge);
+ setPlatform(adapter);
+ return adapter;
+}
diff --git a/sdk/src/platform/native/bridge.ts b/sdk/src/platform/native/bridge.ts
new file mode 100644
index 000000000..a1eb1432a
--- /dev/null
+++ b/sdk/src/platform/native/bridge.ts
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file bridge.ts
+ * @brief The contract a native host (embedded Dawn + JS engine on iOS/Android)
+ * injects so the existing TS SDK + wasm core runs unchanged — NOT a
+ * WebView. Every capability the engine needs from the OS is a method
+ * here; the {@link NativePlatformAdapter} adapts them to PlatformAdapter.
+ *
+ * Deliberately NOT on the bridge:
+ * - WASM instantiation — the host JS engine (JavaScriptCore / V8 / Hermes)
+ * provides the `WebAssembly` global; the adapter uses it directly, the
+ * same as the Node host.
+ * - The GPU render surface — it reaches the C++ renderer via a device
+ * handle (WebAppOptions), not through this adapter. Out of scope here.
+ *
+ * @beta Pre-1.0: the native host is unshipped; this contract will change as the
+ * shell (boot spike → full host) lands. Internal — not a public export yet.
+ */
+
+import type { ImageLoadResult, PlatformRequestOptions } from '../types';
+
+/**
+ * A single fetch result from the native http stack. The adapter wraps it into a
+ * {@link PlatformResponse}: provide `text` OR `arrayBuffer` (matching the request's
+ * responseType); the adapter derives the other on demand.
+ */
+export interface NativeFetchResult {
+ ok: boolean;
+ status: number;
+ statusText?: string;
+ headers?: Record<string, string>;
+ arrayBuffer?: ArrayBuffer;
+ text?: string;
+}
+
+/**
+ * The engine's input sink. The shell PUSHES events (native has no DOM event
+ * loop): touch coordinates are logical px, origin top-left. Keyboard is optional
+ * (most devices are touch-only). The adapter synthesizes the primary pointer from
+ * the first active touch, matching the web/mini-game adapters.
+ */
+export interface NativeInputListener {
+ onTouchStart(id: number, x: number, y: number): void;
+ onTouchMove(id: number, x: number, y: number): void;
+ onTouchEnd(id: number): void;
+ onTouchCancel(id: number): void;
+ onKeyDown?(code: string): void;
+ onKeyUp?(code: string): void;
+}
+
+/**
+ * The host functions the native shell injects. Async where the call crosses to
+ * the OS (files, network, image decode); sync where the native API is sync
+ * (key-value storage). Textures take the pixel-decode path: the host decodes an
+ * image to RGBA via {@link NativeBridge.loadImagePixels} (there is no offscreen
+ * DOM canvas on native).
+ */
+export interface NativeBridge {
+ /** Read a project-relative (packaged) file, or an absolute http(s) URL. */
+ readFile(path: string): Promise<ArrayBuffer>;
+ fileExists(path: string): Promise<boolean>;
+ fetch(url: string, options?: PlatformRequestOptions): Promise<NativeFetchResult>;
+
+ /** Decode an image to top-first RGBA (the Path-2 / createTextureFromPixels
+ * route the play realm and WeChat also use). */
+ loadImagePixels(path: string): Promise<ImageLoadResult>;
+
+ /** Persistent key-value store (NSUserDefaults / SharedPreferences). Sync,
+ * like localStorage / wx.*StorageSync. `storageKeys()` lets the adapter
+ * implement `clearStorage(prefix)` itself. */
+ getStorageItem(key: string): string | null;
+ setStorageItem(key: string, value: string): void;
+ removeStorageItem(key: string): void;
+ storageKeys(): string[];
+
+ /** Register the engine's input sink; returns an unsubscribe. */
+ registerInput(listener: NativeInputListener): () => void;
+
+ devicePixelRatio(): number;
+ /** High-resolution clock. Optional — falls back to `Date.now()`. */
+ now?(): number;
+ /** Host UI language ('zh-CN', 'en-US', …). Optional — falls back to 'en'. */
+ language?(): string;
+
+ /** App foreground/background signals. Reserved for the native Lifecycle seam
+ * (not wired this round). */
+ onShow?(callback: () => void): void;
+ onHide?(callback: () => void): void;
+}
diff --git a/sdk/src/platform/native/index.ts b/sdk/src/platform/native/index.ts
new file mode 100644
index 000000000..babe5a2ef
--- /dev/null
+++ b/sdk/src/platform/native/index.ts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief The native platform barrel (embedded Dawn + JS engine, iOS/Android).
+ *
+ * Internal this round: reachable only via relative import (the mock-bridge test
+ * harness). A public `esengine/native` bundle entry ships with the native shell,
+ * once a real device + toolchain can verify it — see the native-platform campaign.
+ */
+
+export { NativePlatformAdapter, installNativePlatform } from './adapter';
+export type { NativeBridge, NativeInputListener, NativeFetchResult } from './bridge';
diff --git a/sdk/src/platform/node.ts b/sdk/src/platform/node.ts
index 47ede45a0..7fcc12645 100644
--- a/sdk/src/platform/node.ts
+++ b/sdk/src/platform/node.ts
@@ -19,6 +19,8 @@ import type {
WasmInstantiateResult,
InputEventCallbacks,
ImageLoadResult,
+ PlatformCanvas,
+ PlatformImage,
PlatformSocket,
PlatformSocketOptions,
} from './types';
@@ -114,11 +116,11 @@ class NodePlatformAdapter implements PlatformAdapter {
return { instance, module };
}
- createCanvas(_width: number, _height: number): HTMLCanvasElement {
+ createCanvas(_width: number, _height: number): PlatformCanvas {
throw new Error('[node] no canvas on a headless host');
}
- createImage(): HTMLImageElement {
+ createImage(): PlatformImage {
throw new Error('[node] no DOM images on a headless host');
}
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index d3ea79c43..30ede0de8 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -117,12 +117,126 @@ export interface PlatformSocket {
close(code?: number, reason?: string): void;
}
+// =============================================================================
+// Neutral Surfaces (DOM-free)
+// =============================================================================
+//
+// The offscreen 2D surface the engine uses for image decode and dynamic glyph
+// rasterization. These are a bounded STRUCTURAL SUBSET of the DOM
+// Canvas/OffscreenCanvas + HTMLImageElement so a real HTMLCanvasElement /
+// OffscreenCanvas / HTMLImageElement is assignable to them (web/mini-game adapters
+// need no casts), while a native host — which has no DOM — can implement the
+// PlatformAdapter contract honestly (createCanvas/createImage simply throw there;
+// native textures come from loadImagePixels, the C++ createTextureFromPixels path).
+//
+// The main RENDER surface does NOT flow through here — it enters the C++ renderer
+// via a GL context handle / preinitialized WebGPU device (see WebAppOptions), not
+// createCanvas. So the neutral canvas is 2D-only.
+
+/** RGBA readback from getImageData. The DOM `ImageData` is assignable (its extra
+ * members are ignored structurally). */
+export interface PlatformImageData {
+ readonly data: Uint8ClampedArray;
+ readonly width: number;
+ readonly height: number;
+}
+
+/** The subset of `TextMetrics` the glyph rasterizer reads. `TextMetrics` is
+ * assignable. */
+export interface PlatformTextMetrics {
+ readonly width: number;
+ readonly actualBoundingBoxLeft?: number;
+ readonly actualBoundingBoxRight?: number;
+ readonly actualBoundingBoxAscent?: number;
+ readonly actualBoundingBoxDescent?: number;
+}
+
+/** The `getContext('2d', …)` options actually used. */
+export interface PlatformCanvasContextAttributes {
+ willReadFrequently?: boolean;
+ alpha?: boolean;
+}
+
+/**
+ * A drawable source for `ctx.drawImage`. Typed `object` deliberately: it is the
+ * only DOM-free SUPERTYPE of lib.dom's `CanvasImageSource` union (its
+ * `SVGImageElement`/`VideoFrame` branches share no structural `{width;height}`),
+ * so the real `CanvasRenderingContext2D.drawImage(CanvasImageSource)` stays
+ * assignable to this neutral method while callers pass an `ImageBitmap` OR a
+ * `PlatformImage` with no `as unknown` cast.
+ */
+export type PlatformImageSource = object;
+
+/** Paint value for `fillStyle`. `string | object` is the DOM-free supertype of the
+ * real `string | CanvasGradient | CanvasPattern` (callers only ever assign a color
+ * string; the supertype is what keeps the real 2D context assignable). */
+export type PlatformCanvasPaint = string | object;
+
+/**
+ * The offscreen 2D context the engine uses: image decode (`drawImage`/
+ * `getImageData`/`clearRect`) and dynamic glyph rasterization (`font`/`measureText`/
+ * `fillText`/…). Every member is present on BOTH `CanvasRenderingContext2D` and
+ * `OffscreenCanvasRenderingContext2D` with covariance-compatible types, so both are
+ * assignable here.
+ */
+export interface PlatformCanvas2DContext {
+ // Image decode.
+ drawImage(image: PlatformImageSource, dx: number, dy: number): void;
+ getImageData(sx: number, sy: number, sw: number, sh: number): PlatformImageData;
+ clearRect(x: number, y: number, w: number, h: number): void;
+ // Glyph rasterization (ui/text/glyph-rasterizer.ts).
+ font: string;
+ textBaseline: string;
+ textAlign: string;
+ fillStyle: PlatformCanvasPaint;
+ measureText(text: string): PlatformTextMetrics;
+ fillText(text: string, x: number, y: number): void;
+}
+
+/**
+ * The offscreen 2D canvas surface. `HTMLCanvasElement` and `OffscreenCanvas` are
+ * structurally assignable: their overloaded `getContext` matches this `'2d'`
+ * overload, whose real return is assignable to {@link PlatformCanvas2DContext}.
+ */
+export interface PlatformCanvas {
+ width: number;
+ height: number;
+ getContext(
+ contextId: '2d',
+ options?: PlatformCanvasContextAttributes,
+ ): PlatformCanvas2DContext | null;
+}
+
+/**
+ * A load/error callback SINK: callers only ever ASSIGN one (`img.onload = …`); the
+ * host image invokes it. The parameter is the bottom type `never` so, by
+ * contravariance, EVERY real handler shape is assignable to it — the DOM
+ * `(ev: Event) => any`, the mini-game `() => void`, and the SDK's own
+ * `() => resolve()` — without this "neutral" type naming any DOM type (`Event`).
+ */
+export type PlatformImageEventHandler = ((ev: never) => void) | null;
+
+/**
+ * A decodable image (the offscreen `<img>` on DOM hosts). `HTMLImageElement` and a
+ * mini-game image are both structurally assignable. Native never creates one
+ * (createImage throws), so the DOM-shaped members impose nothing on native.
+ * `crossOrigin` is optional so a mini-game image (which lacks it) fits too.
+ */
+export interface PlatformImage {
+ width: number;
+ height: number;
+ src: string;
+ crossOrigin?: string | null;
+ onload: PlatformImageEventHandler;
+ onerror: PlatformImageEventHandler;
+}
+
// =============================================================================
// Platform Adapter Interface
// =============================================================================
export interface PlatformAdapter {
- readonly name: 'web' | 'wechat' | 'douyin' | 'node';
+ readonly name: 'web' | 'wechat' | 'douyin' | 'node' | 'native';
fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>;
@@ -139,11 +253,11 @@ export interface PlatformAdapter {
imports: WebAssembly.Imports
): Promise<WasmInstantiateResult>;
- createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas;
+ createCanvas(width: number, height: number): PlatformCanvas;
now(): number;
- createImage(): HTMLImageElement;
+ createImage(): PlatformImage;
bindInputEvents(callbacks: InputEventCallbacks, target?: unknown): void;
diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.ts
index 4bc9ae639..1ce11065b 100644
--- a/sdk/src/platform/web.ts
+++ b/sdk/src/platform/web.ts
@@ -13,6 +13,8 @@ import type {
InputEventCallbacks,
GamepadSnapshot,
ImageLoadResult,
+ PlatformCanvas,
+ PlatformImage,
PlatformSocket,
PlatformSocketOptions,
} from './types';
@@ -91,7 +93,7 @@ class WebPlatformAdapter implements PlatformAdapter {
img.src = path;
});
const cv = this.createCanvas(img.width, img.height);
- const ctx = (cv as HTMLCanvasElement).getContext('2d')!;
+ const ctx = cv.getContext('2d')!;
ctx.drawImage(img, 0, 0);
const id = ctx.getImageData(0, 0, img.width, img.height);
return { width: img.width, height: img.height, pixels: new Uint8Array(id.data.buffer) };
@@ -116,11 +118,11 @@ class WebPlatformAdapter implements PlatformAdapter {
module: result.module,
};
}
- createImage(): HTMLImageElement {
+ createImage(): PlatformImage {
return new Image();
}
- createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
+ createCanvas(width: number, height: number): PlatformCanvas {
let canvas: HTMLCanvasElement | OffscreenCanvas;
if (typeof OffscreenCanvas !== 'undefined') {
canvas = new OffscreenCanvas(width, height);
diff --git a/sdk/src/ui/layout/safe-area.ts b/sdk/src/ui/layout/safe-area.ts
index 309d92622..abd832b08 100644
--- a/sdk/src/ui/layout/safe-area.ts
+++ b/sdk/src/ui/layout/safe-area.ts
@@ -77,6 +77,10 @@ function getSafeAreaInsets(): SafeAreaInsets {
if (isWeChat()) {
return getWeChatSafeAreaInsets();
}
+ // Native (no DOM) falls through to getWebSafeAreaInsets, which returns zero
+ // insets when `document` is absent — harmless. When the native shell exposes
+ // notch insets (a bridge.safeAreaInsets() seam), gate `isWeChat() || isNative()`
+ // here and read them the wechat way (non-DPR-scaled).
return getWebSafeAreaInsets();
}
diff --git a/sdk/src/ui/text/glyph-rasterizer.ts b/sdk/src/ui/text/glyph-rasterizer.ts
index 1205b9206..aba6cff87 100644
--- a/sdk/src/ui/text/glyph-rasterizer.ts
+++ b/sdk/src/ui/text/glyph-rasterizer.ts
@@ -13,6 +13,7 @@
*/
import type { ESEngineModule } from '../../wasm';
import { platformCreateCanvas } from '../../platform';
+import type { PlatformCanvas, PlatformCanvas2DContext } from '../../platform/types';
import { sdfFromAlpha } from './sdf';
import type { GlyphRasterizer, RasterGlyph } from './glyph-atlas';
@@ -74,8 +75,8 @@ export interface CanvasGlyphRasterizerOptions {
sdf?: boolean;
}
-type Canvas2D = HTMLCanvasElement | OffscreenCanvas;
-type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+type Canvas2D = PlatformCanvas;
+type Ctx2D = PlatformCanvas2DContext;
// SDF supersampling: rasterize + distance-transform at 4× the stored
// resolution, then box-downsample — magnified glyphs stop showing the source
@@ -100,7 +101,7 @@ export class CanvasGlyphRasterizer implements GlyphRasterizer {
const ss = this.sdf ? SDF_SUPERSAMPLE : 1;
const dim = Math.ceil((this.renderSize * 2 + this.pad * 2) * ss);
this.canvas = platformCreateCanvas(dim, dim);
- this.ctx = this.canvas.getContext('2d', { willReadFrequently: true }) as Ctx2D | null;
+ this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });
}
rasterize(codepoint: number, fontFamily: string, style: number, pixelSize = this.renderSize): RasterGlyph | null {
diff --git a/sdk/tests/native-adapter.test.ts b/sdk/tests/native-adapter.test.ts
new file mode 100644
index 000000000..5b0f610f5
--- /dev/null
+++ b/sdk/tests/native-adapter.test.ts
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The native PlatformAdapter driven headlessly by a mock NativeBridge — proves the
+// host-bridge contract holds (fs / fetch / wasm / image-pixels / storage / input /
+// identity) with no device, plus fills the platform-layer test gap that the
+// DOM-free surface refactor uncovered (detectPlatform, mini-game canvas/image with
+// the `as unknown` casts removed, node canvas/image fail loud).
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ NativePlatformAdapter,
+ installNativePlatform,
+ type NativeBridge,
+ type NativeInputListener,
+} from '../src/platform/native';
+import { getPlatformType, isNative, platformLanguage } from '../src/platform';
+import { detectPlatform } from '../src/platform/types';
+import type { InputEventCallbacks } from '../src/platform/types';
+
+function makeBridge() {
+ const store = new Map<string, string>();
+ const files = new Map<string, ArrayBuffer>([
+ ['data/config.json', new TextEncoder().encode('{"a":1}').buffer as ArrayBuffer],
+ ]);
+ const listeners: NativeInputListener[] = [];
+ const bridge: NativeBridge = {
+ readFile: async (p) => {
+ const b = files.get(p);
+ if (!b) throw new Error('ENOENT ' + p);
+ return b;
+ },
+ fileExists: async (p) => files.has(p),
+ fetch: async () => ({ ok: true, status: 200, statusText: 'OK', text: '{"ok":true}' }),
+ loadImagePixels: async () => ({ width: 2, height: 2, pixels: new Uint8Array(16).fill(255) }),
+ getStorageItem: (k) => store.get(k) ?? null,
+ setStorageItem: (k, v) => { store.set(k, v); },
+ removeStorageItem: (k) => { store.delete(k); },
+ storageKeys: () => [...store.keys()],
+ registerInput: (l) => {
+ listeners.push(l);
+ return () => {
+ const i = listeners.indexOf(l);
+ if (i >= 0) listeners.splice(i, 1);
+ };
+ },
+ devicePixelRatio: () => 3,
+ now: () => 12345,
+ language: () => 'zh_CN',
+ };
+ return { bridge, store, files, listeners };
+}
+
+function makeInputCallbacks(): InputEventCallbacks {
+ return {
+ onKeyDown: vi.fn(),
+ onKeyUp: vi.fn(),
+ onPointerMove: vi.fn(),
+ onPointerDown: vi.fn(),
+ onPointerUp: vi.fn(),
+ onWheel: vi.fn(),
+ onTouchStart: vi.fn(),
+ onTouchMove: vi.fn(),
+ onTouchEnd: vi.fn(),
+ onTouchCancel: vi.fn(),
+ };
+}
+
+describe('NativePlatformAdapter (mock bridge)', () => {
+ let env: ReturnType<typeof makeBridge>;
+ let adapter: NativePlatformAdapter;
+
+ beforeEach(() => {
+ env = makeBridge();
+ adapter = installNativePlatform(env.bridge);
+ });
+
+ it('installs as a first-class native platform identity', () => {
+ expect(adapter.name).toBe('native');
+ expect(getPlatformType()).toBe('native');
+ expect(isNative()).toBe(true);
+ });
+
+ it('reads packaged files as bytes and text', async () => {
+ expect(await adapter.fileExists('data/config.json')).toBe(true);
+ expect(await adapter.fileExists('nope')).toBe(false);
+ expect(new TextDecoder().decode(await adapter.readFile('data/config.json'))).toBe('{"a":1}');
+ expect(await adapter.readTextFile('data/config.json')).toBe('{"a":1}');
+ await expect(adapter.readFile('nope')).rejects.toThrow();
+ });
+
+ it('wraps the bridge fetch into a PlatformResponse', async () => {
+ const res = await adapter.fetch('https://cdn/x.json');
+ expect(res.ok).toBe(true);
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe('{"ok":true}');
+ expect(await res.json()).toEqual({ ok: true });
+ });
+
+ it('decodes image pixels through the bridge (Path 2)', async () => {
+ const img = await adapter.loadImagePixels('art/hero.png');
+ expect(img.width).toBe(2);
+ expect(img.height).toBe(2);
+ expect(img.pixels.length).toBe(16);
+ expect(img.pixels[0]).toBe(255);
+ });
+
+ it('instantiates wasm via the host JS engine WebAssembly (no bridge call)', async () => {
+ // Minimal valid module: magic + version header.
+ const bytes = new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).buffer;
+ const result = await adapter.instantiateWasm(bytes, {});
+ expect(result.instance).toBeDefined();
+ expect(result.module).toBeDefined();
+ });
+
+ it('round-trips storage and clears by prefix', () => {
+ adapter.setStorageItem('esengine:a', '1');
+ adapter.setStorageItem('esengine:b', '2');
+ adapter.setStorageItem('other:c', '3');
+ expect(adapter.getStorageItem('esengine:a')).toBe('1');
+ adapter.removeStorageItem('esengine:a');
+ expect(adapter.getStorageItem('esengine:a')).toBeNull();
+
+ adapter.clearStorage('esengine:');
+ expect(adapter.getStorageItem('esengine:b')).toBeNull();
+ expect(adapter.getStorageItem('other:c')).toBe('3'); // untouched
+ });
+
+ it('reports clock, DPR and normalized language', () => {
+ expect(adapter.now()).toBe(12345);
+ expect(adapter.devicePixelRatio()).toBe(3);
+ // base.platformLanguage() normalizes the bridge's underscore tag.
+ expect(platformLanguage()).toBe('zh-CN');
+ });
+
+ it('dispatches pushed native input, synthesizing the primary pointer', () => {
+ const cb = makeInputCallbacks();
+ adapter.bindInputEvents(cb);
+ expect(env.listeners.length).toBe(1);
+ const sink = env.listeners[0];
+
+ sink.onTouchStart(1, 10, 20);
+ expect(cb.onTouchStart).toHaveBeenCalledWith(1, 10, 20);
+ expect(cb.onPointerDown).toHaveBeenCalledWith(0, 10, 20);
+
+ sink.onTouchMove(1, 30, 40);
+ expect(cb.onPointerMove).toHaveBeenCalledWith(30, 40);
+
+ sink.onTouchEnd(1);
+ expect(cb.onPointerUp).toHaveBeenCalledWith(0);
+
+ sink.onKeyDown?.('KeyA');
+ expect(cb.onKeyDown).toHaveBeenCalledWith('KeyA');
+
+ adapter.unbindInputEvents();
+ expect(env.listeners.length).toBe(0);
+ });
+
+ it('fails loud on the offscreen DOM surfaces (native uses loadImagePixels)', () => {
+ expect(() => adapter.createCanvas(1, 1)).toThrow(/native/);
+ expect(() => adapter.createImage()).toThrow(/native/);
+ });
+});
+
+describe('detectPlatform()', () => {
+ afterEach(() => {
+ delete (globalThis as Record<string, unknown>).tt;
+ delete (globalThis as Record<string, unknown>).wx;
+ });
+
+ it('is web with no vendor global', () => {
+ expect(detectPlatform()).toBe('web');
+ });
+
+ it('is douyin when tt is present', () => {
+ (globalThis as Record<string, unknown>).tt = { getSystemInfoSync: () => ({}) };
+ expect(detectPlatform()).toBe('douyin');
+ });
+
+ it('is wechat when wx is present (and tt is not)', () => {
+ (globalThis as Record<string, unknown>).wx = { getSystemInfoSync: () => ({}) };
+ expect(detectPlatform()).toBe('wechat');
+ });
+});
+
+describe('MiniGamePlatformAdapter surfaces (casts removed)', () => {
+ it('returns a sized canvas and image from the host global', async () => {
+ const { MiniGamePlatformAdapter } = await import('../src/platform/minigame/adapter');
+ const g = {
+ createCanvas: () => ({ width: 0, height: 0, getContext: () => null }),
+ createImage: () => ({ width: 5, height: 7, src: '', onload: null, onerror: null }),
+ };
+ const profile = {
+ id: 'wechat',
+ hostLabel: 'WeChat',
+ global: g,
+ instantiateWasm: vi.fn(),
+ createAudioBackend: vi.fn(),
+ createVideoBackend: vi.fn(),
+ createSocket: vi.fn(),
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const a = new MiniGamePlatformAdapter(profile as any);
+ expect(a.name).toBe('wechat');
+ const c = a.createCanvas(10, 20);
+ expect(c.width).toBe(10);
+ expect(c.height).toBe(20);
+ const img = a.createImage();
+ expect(img.width).toBe(5);
+ expect(img.height).toBe(7);
+ });
+});
+
+describe('node adapter surfaces (fail loud, no render host)', () => {
+ it('throws for canvas/image and rejects image decode', async () => {
+ const { nodeAdapter } = await import('../src/platform/node');
+ expect(() => nodeAdapter.createCanvas(1, 1)).toThrow();
+ expect(() => nodeAdapter.createImage()).toThrow();
+ await expect(nodeAdapter.loadImagePixels('x.png')).rejects.toThrow();
+ });
+});