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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: Add platform adapter and npm publish workflow
esenginea6424cec89c0
diff --git a/.github/workflows/publish-sdk.yml b/.github/workflows/publish-sdk.ymlnew file mode 100644index 000000000..04ec038e5--- /dev/null+++ b/.github/workflows/publish-sdk.yml@@ -0,0 +1,44 @@+name: Publish SDK++on:+ push:+ tags:+ - 'sdk-v*'+ workflow_dispatch:+ inputs:+ version:+ description: 'Version to publish (e.g., 0.2.0)'+ required: false++jobs:+ publish:+ name: Publish to npm+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: '20'+ registry-url: 'https://registry.npmjs.org'++ - name: Setup pnpm+ uses: pnpm/action-setup@v2+ with:+ version: 8++ - name: Install dependencies+ working-directory: sdk+ run: pnpm install++ - name: Build SDK+ working-directory: sdk+ run: pnpm run build++ - name: Publish to npm+ working-directory: sdk+ run: npm publish --access public+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}diff --git a/sdk/package.json b/sdk/package.jsonindex a60e4f672..27912eafd 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -45,6 +45,7 @@"license": "MIT","devDependencies": {"@rollup/plugin-typescript": "^11.1.5",+ "minigame-api-typings": "^3.8.16","rimraf": "^5.0.5","rollup": "^4.9.0","rollup-plugin-dts": "^6.1.0",diff --git a/sdk/rollup.config.js b/sdk/rollup.config.jsindex bc434b2b7..7a7213503 100644--- a/sdk/rollup.config.js+++ b/sdk/rollup.config.js@@ -1,12 +1,20 @@import typescript from '@rollup/plugin-typescript';import dts from 'rollup-plugin-dts';+// =============================================================================+// Module Entries+// =============================================================================+const modules = {- 'index': 'src/index.ts',+ 'index': 'src/index.ts', // Web entry+ 'index.wechat': 'src/index.wechat.ts', // WeChat entry'wasm': 'src/wasm.ts',};-// Local dist builds (ESM)+// =============================================================================+// Local Dist Builds (ESM)+// =============================================================================+const esmBuilds = Object.entries(modules).map(([name, input]) => ({input,output: {@@ -25,21 +33,35 @@ const esmBuilds = Object.entries(modules).map(([name, input]) => ({},}));-// Type declarations-const dtsBuilds = Object.entries(modules).map(([name, input]) => ({- input,- output: {- file: `dist/${name}.d.ts`,- format: 'esm',+// =============================================================================+// Type Declarations+// =============================================================================++// Only generate .d.ts for main entries (Web and WeChat share the same types)+const dtsBuilds = [+ {+ input: 'src/index.ts',+ output: {+ file: 'dist/index.d.ts',+ format: 'esm',+ },+ plugins: [dts()],},- plugins: [dts()],-}));+ {+ input: 'src/wasm.ts',+ output: {+ file: 'dist/wasm.d.ts',+ format: 'esm',+ },+ plugins: [dts()],+ },+];// =============================================================================-// Desktop Public Builds (organized by format)+// Desktop Public Builds// =============================================================================-// ESM build for editor preview+// ESM build for editor preview (Web)const esmPublicBuild = {input: 'src/index.ts',output: {@@ -58,8 +80,28 @@ const esmPublicBuild = {},};-// CJS build for WeChat Mini Game-const cjsPublicBuild = {+// CJS build for WeChat Mini Game (includes WeChat adapter)+const cjsWechatBuild = {+ input: 'src/index.wechat.ts',+ output: {+ file: '../desktop/public/sdk/cjs/esengine.wechat.js',+ format: 'cjs',+ sourcemap: false,+ exports: 'named',+ },+ plugins: [+ typescript({+ tsconfig: './tsconfig.json',+ declaration: false,+ }),+ ],+ treeshake: {+ moduleSideEffects: false,+ },+};++// CJS build for Web (no WeChat code)+const cjsWebBuild = {input: 'src/index.ts',output: {file: '../desktop/public/sdk/cjs/esengine.js',@@ -78,7 +120,7 @@ const cjsPublicBuild = {},};-// IIFE build for playable ads+// IIFE build for playable ads (Web, no WeChat code)const iifePublicBuild = {input: 'src/index.ts',output: {@@ -102,6 +144,7 @@ export default [...esmBuilds,...dtsBuilds,esmPublicBuild,- cjsPublicBuild,+ cjsWebBuild,+ cjsWechatBuild,iifePublicBuild,];diff --git a/sdk/src/core.ts b/sdk/src/core.tsnew file mode 100644index 000000000..49887a6b9--- /dev/null+++ b/sdk/src/core.ts@@ -0,0 +1,209 @@+/**+ * @file core.ts+ * @brief ESEngine SDK - Core exports (no platform initialization)+ */++// =============================================================================+// Types+// =============================================================================++export {+ type Entity,+ INVALID_ENTITY,+ type TextureHandle,+ INVALID_TEXTURE,+ type Vec2,+ type Vec3,+ type Vec4,+ type Color,+ type Quat,+ vec2,+ vec3,+ vec4,+ color,+ quat,+} from './types';++// =============================================================================+// Components+// =============================================================================++export {+ defineComponent,+ defineTag,+ isBuiltinComponent,+ type ComponentDef,+ type BuiltinComponentDef,+ type AnyComponentDef,+ type ComponentData,+ LocalTransform,+ WorldTransform,+ Sprite,+ Camera,+ Canvas,+ Velocity,+ Parent,+ Children,+ type LocalTransformData,+ type WorldTransformData,+ type SpriteData,+ type CameraData,+ type CanvasData,+ type VelocityData,+ type ParentData,+ type ChildrenData,+} from './component';++// =============================================================================+// Resources+// =============================================================================++export {+ defineResource,+ Res,+ ResMut,+ Time,+ Input,+ type ResourceDef,+ type ResDescriptor,+ type ResMutDescriptor,+ type ResMutInstance,+ type TimeData,+ type InputState,+} from './resource';++// =============================================================================+// Query+// =============================================================================++export {+ Query,+ Mut,+ QueryInstance,+ type QueryDescriptor,+ type QueryResult,+ type MutWrapper,+} from './query';++// =============================================================================+// Commands+// =============================================================================++export {+ Commands,+ CommandsInstance,+ EntityCommands,+ type CommandsDescriptor,+} from './commands';++// =============================================================================+// System+// =============================================================================++export {+ Schedule,+ defineSystem,+ SystemRunner,+ type SystemDef,+ type SystemParam,+ type InferParam,+ type InferParams,+} from './system';++// =============================================================================+// World+// =============================================================================++export { World } from './world';++// =============================================================================+// App+// =============================================================================++export {+ App,+ createWebApp,+ type Plugin,+ type WebAppOptions,+} from './app';++// =============================================================================+// WASM Types+// =============================================================================++export type {+ ESEngineModule,+ CppRegistry,+ CppResourceManager,+} from './wasm';++// =============================================================================+// UI+// =============================================================================++export {+ Text,+ TextAlign,+ TextVerticalAlign,+ TextOverflow,+ UIRect,+ TextRenderer,+ TextPlugin,+ textPlugin,+ type TextData,+ type UIRectData,+ type TextRenderResult,+} from './ui';++// =============================================================================+// Asset+// =============================================================================++export {+ AssetServer,+ Assets,+ AssetPlugin,+ assetPlugin,+ type TextureInfo,+ type AssetsData,+} from './asset';++// =============================================================================+// Scene+// =============================================================================++export {+ loadSceneData,+ loadSceneWithAssets,+ type SceneData,+ type SceneEntityData,+ type SceneComponentData,+ type SceneLoadOptions,+} from './scene';++// =============================================================================+// Preview+// =============================================================================++export { PreviewPlugin } from './preview';++// =============================================================================+// Platform (base functions only)+// =============================================================================++export {+ getPlatform,+ getPlatformType,+ isPlatformInitialized,+ isWeChat,+ isWeb,+ platformFetch,+ platformReadFile,+ platformReadTextFile,+ platformFileExists,+ platformInstantiateWasm,+ type PlatformAdapter,+ type PlatformType,+ type PlatformRequestOptions,+ type PlatformResponse,+} from './platform';diff --git a/sdk/src/index.ts b/sdk/src/index.tsindex cbf3741d7..14fc44cf6 100644--- a/sdk/src/index.ts+++ b/sdk/src/index.ts@@ -1,188 +1,11 @@/*** @file index.ts- * @brief ESEngine SDK - Main entry point+ * @brief ESEngine SDK - Web entry point (auto-initializes Web platform)*/-// =============================================================================-// Types-// =============================================================================+// Initialize Web platform+import { setPlatform, webAdapter } from './platform';+setPlatform(webAdapter);-export {- type Entity,- INVALID_ENTITY,- type TextureHandle,- INVALID_TEXTURE,- type Vec2,- type Vec3,- type Vec4,- type Color,- type Quat,- vec2,- vec3,- vec4,- color,- quat,-} from './types';--// =============================================================================-// Components-// =============================================================================--export {- defineComponent,- defineTag,- isBuiltinComponent,- type ComponentDef,- type BuiltinComponentDef,- type AnyComponentDef,- type ComponentData,- LocalTransform,- WorldTransform,- Sprite,- Camera,- Canvas,- Velocity,- Parent,- Children,- type LocalTransformData,- type WorldTransformData,- type SpriteData,- type CameraData,- type CanvasData,- type VelocityData,- type ParentData,- type ChildrenData,-} from './component';--// =============================================================================-// Resources-// =============================================================================--export {- defineResource,- Res,- ResMut,- Time,- Input,- type ResourceDef,- type ResDescriptor,- type ResMutDescriptor,- type ResMutInstance,- type TimeData,- type InputState,-} from './resource';--// =============================================================================-// Query-// =============================================================================--export {- Query,- Mut,- QueryInstance,- type QueryDescriptor,- type QueryResult,- type MutWrapper,-} from './query';--// =============================================================================-// Commands-// =============================================================================--export {- Commands,- CommandsInstance,- EntityCommands,- type CommandsDescriptor,-} from './commands';--// =============================================================================-// System-// =============================================================================--export {- Schedule,- defineSystem,- SystemRunner,- type SystemDef,- type SystemParam,- type InferParam,- type InferParams,-} from './system';--// =============================================================================-// World-// =============================================================================--export { World } from './world';--// =============================================================================-// App-// =============================================================================--export {- App,- createWebApp,- type Plugin,- type WebAppOptions,-} from './app';--// =============================================================================-// WASM Types-// =============================================================================--export type {- ESEngineModule,- CppRegistry,- CppResourceManager,-} from './wasm';--// =============================================================================-// UI-// =============================================================================--export {- Text,- TextAlign,- TextVerticalAlign,- TextOverflow,- UIRect,- TextRenderer,- TextPlugin,- textPlugin,- type TextData,- type UIRectData,- type TextRenderResult,-} from './ui';--// =============================================================================-// Asset-// =============================================================================--export {- AssetServer,- Assets,- AssetPlugin,- assetPlugin,- type TextureInfo,- type AssetsData,-} from './asset';--// =============================================================================-// Scene-// =============================================================================--export {- loadSceneData,- loadSceneWithAssets,- type SceneData,- type SceneEntityData,- type SceneComponentData,- type SceneLoadOptions,-} from './scene';--// =============================================================================-// Preview-// =============================================================================--export { PreviewPlugin } from './preview';+// Re-export everything from core+export * from './core';diff --git a/sdk/src/index.wechat.ts b/sdk/src/index.wechat.tsnew file mode 100644index 000000000..a06a4c0ce--- /dev/null+++ b/sdk/src/index.wechat.ts@@ -0,0 +1,23 @@+/**+ * @file index.wechat.ts+ * @brief ESEngine SDK - WeChat MiniGame entry point+ */++// Initialize WeChat platform+import { setPlatform } from './platform';+import { wechatAdapter, initWeChatPlatform } from './platform/wechat';++initWeChatPlatform();+setPlatform(wechatAdapter);++// Re-export everything from core+export * from './core';++// Export WeChat-specific utilities+export {+ wxReadFile,+ wxReadTextFile,+ wxFileExists,+ wxFileExistsSync,+ wxWriteFile,+} from './platform/wechat';diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsnew file mode 100644index 000000000..527303ea4--- /dev/null+++ b/sdk/src/platform/base.ts@@ -0,0 +1,92 @@+/**+ * @file base.ts+ * @brief Base platform adapter - no platform-specific code+ */++import type { PlatformAdapter } from './types';++// =============================================================================+// Platform Instance (set by entry point)+// =============================================================================++let currentPlatform: PlatformAdapter | null = null;++/**+ * Set the platform adapter (called by entry point)+ */+export function setPlatform(adapter: PlatformAdapter): void {+ currentPlatform = adapter;+ console.log(`[ESEngine] Platform: ${adapter.name}`);+}++/**+ * Get the current platform adapter+ * @throws Error if platform not initialized+ */+export function getPlatform(): PlatformAdapter {+ if (!currentPlatform) {+ throw new Error(+ '[ESEngine] Platform not initialized. ' ++ 'Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.'+ );+ }+ return currentPlatform;+}++/**+ * Check if platform is initialized+ */+export function isPlatformInitialized(): boolean {+ return currentPlatform !== null;+}++/**+ * Get platform type+ */+export function getPlatformType(): 'web' | 'wechat' | null {+ return currentPlatform?.name ?? null;+}++/**+ * Check if running on WeChat+ */+export function isWeChat(): boolean {+ return currentPlatform?.name === 'wechat';+}++/**+ * Check if running on Web+ */+export function isWeb(): boolean {+ return currentPlatform?.name === 'web';+}++// =============================================================================+// Convenience Functions+// =============================================================================++export async function platformFetch(+ url: string,+ options?: import('./types').PlatformRequestOptions+): Promise<import('./types').PlatformResponse> {+ return getPlatform().fetch(url, options);+}++export async function platformReadFile(path: string): Promise<ArrayBuffer> {+ return getPlatform().readFile(path);+}++export async function platformReadTextFile(path: string): Promise<string> {+ return getPlatform().readTextFile(path);+}++export async function platformFileExists(path: string): Promise<boolean> {+ return getPlatform().fileExists(path);+}++export async function platformInstantiateWasm(+ pathOrBuffer: string | ArrayBuffer,+ imports: WebAssembly.Imports+): Promise<import('./types').WasmInstantiateResult> {+ return getPlatform().instantiateWasm(pathOrBuffer, imports);+}diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsnew file mode 100644index 000000000..59da5838d--- /dev/null+++ b/sdk/src/platform/index.ts@@ -0,0 +1,34 @@+/**+ * @file index.ts+ * @brief Platform adapter exports+ */++// Re-export types+export type {+ PlatformAdapter,+ PlatformType,+ PlatformRequestOptions,+ PlatformResponse,+ WasmInstantiateResult,+} from './types';++// Re-export base functions+export {+ setPlatform,+ getPlatform,+ getPlatformType,+ isPlatformInitialized,+ isWeChat,+ isWeb,+ platformFetch,+ platformReadFile,+ platformReadTextFile,+ platformFileExists,+ platformInstantiateWasm,+} from './base';++// Note: webAdapter is exported here for initialization+// wechatAdapter should be imported directly from './wechat' to avoid bundling in web builds++// Re-export web adapter+export { webAdapter } from './web';diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsnew file mode 100644index 000000000..af7403045--- /dev/null+++ b/sdk/src/platform/types.ts@@ -0,0 +1,99 @@+/**+ * @file types.ts+ * @brief Platform adapter interface definitions+ */++// =============================================================================+// Response Types+// =============================================================================++export interface PlatformResponse {+ ok: boolean;+ status: number;+ statusText: string;+ headers: Record<string, string>;+ json<T = unknown>(): Promise<T>;+ text(): Promise<string>;+ arrayBuffer(): Promise<ArrayBuffer>;+}++// =============================================================================+// Request Types+// =============================================================================++export interface PlatformRequestOptions {+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS';+ headers?: Record<string, string>;+ body?: string | ArrayBuffer;+ responseType?: 'text' | 'arraybuffer' | 'json';+ timeout?: number;+}++// =============================================================================+// WASM Types+// =============================================================================++export interface WasmInstantiateResult {+ instance: WebAssembly.Instance;+ module: WebAssembly.Module;+}++// =============================================================================+// Platform Adapter Interface+// =============================================================================++export interface PlatformAdapter {+ /**+ * Platform name identifier+ */+ readonly name: 'web' | 'wechat';++ /**+ * Fetch resource from URL+ */+ fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>;++ /**+ * Read local file as ArrayBuffer+ * @param path - File path (relative to game root)+ */+ readFile(path: string): Promise<ArrayBuffer>;++ /**+ * Read local file as text+ * @param path - File path (relative to game root)+ */+ readTextFile(path: string): Promise<string>;++ /**+ * Check if file exists+ * @param path - File path+ */+ fileExists(path: string): Promise<boolean>;++ /**+ * Instantiate WebAssembly module+ * @param pathOrBuffer - WASM file path (WeChat) or ArrayBuffer (Web)+ * @param imports - Import object+ */+ instantiateWasm(+ pathOrBuffer: string | ArrayBuffer,+ imports: WebAssembly.Imports+ ): Promise<WasmInstantiateResult>;+}++// =============================================================================+// Platform Detection+// =============================================================================++export type PlatformType = 'web' | 'wechat';++export function detectPlatform(): PlatformType {+ // Check for WeChat MiniGame environment+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const g = globalThis as any;+ if (typeof g.wx !== 'undefined' && typeof g.wx.getSystemInfoSync === 'function') {+ return 'wechat';+ }+ return 'web';+}diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.tsnew file mode 100644index 000000000..3c5b60e1c--- /dev/null+++ b/sdk/src/platform/web.ts@@ -0,0 +1,93 @@+/**+ * @file web.ts+ * @brief Web platform adapter implementation+ */++import type {+ PlatformAdapter,+ PlatformRequestOptions,+ PlatformResponse,+ WasmInstantiateResult,+} from './types';++// =============================================================================+// Web Platform Adapter+// =============================================================================++class WebPlatformAdapter implements PlatformAdapter {+ readonly name = 'web' as const;++ async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {+ const response = await globalThis.fetch(url, {+ method: options?.method ?? 'GET',+ headers: options?.headers,+ body: options?.body,+ });++ const headers: Record<string, string> = {};+ response.headers.forEach((value, key) => {+ headers[key] = value;+ });++ return {+ ok: response.ok,+ status: response.status,+ statusText: response.statusText,+ headers,+ json: <T>() => response.json() as Promise<T>,+ text: () => response.text(),+ arrayBuffer: () => response.arrayBuffer(),+ };+ }++ async readFile(path: string): Promise<ArrayBuffer> {+ const response = await this.fetch(path);+ if (!response.ok) {+ throw new Error(`Failed to read file: ${path} (${response.status})`);+ }+ return response.arrayBuffer();+ }++ async readTextFile(path: string): Promise<string> {+ const response = await this.fetch(path);+ if (!response.ok) {+ throw new Error(`Failed to read file: ${path} (${response.status})`);+ }+ return response.text();+ }++ async fileExists(path: string): Promise<boolean> {+ try {+ const response = await globalThis.fetch(path, { method: 'HEAD' });+ return response.ok;+ } catch {+ return false;+ }+ }++ async instantiateWasm(+ pathOrBuffer: string | ArrayBuffer,+ imports: WebAssembly.Imports+ ): Promise<WasmInstantiateResult> {+ let buffer: ArrayBuffer;++ if (typeof pathOrBuffer === 'string') {+ buffer = await this.readFile(pathOrBuffer);+ } else {+ buffer = pathOrBuffer;+ }++ const result = await WebAssembly.instantiate(buffer, imports);++ return {+ instance: result.instance,+ module: result.module,+ };+ }+}++// =============================================================================+// Export Singleton+// =============================================================================++export const webAdapter = new WebPlatformAdapter();diff --git a/sdk/src/platform/wechat/fetch.ts b/sdk/src/platform/wechat/fetch.tsnew file mode 100644index 000000000..d2f7d85c2--- /dev/null+++ b/sdk/src/platform/wechat/fetch.ts@@ -0,0 +1,109 @@+/**+ * @file fetch.ts+ * @brief Fetch polyfill for WeChat MiniGame using wx.request+ */++/// <reference types="minigame-api-typings" />++import type { PlatformRequestOptions, PlatformResponse } from '../types';++// =============================================================================+// WeChat Fetch Implementation+// =============================================================================++export function wxFetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {+ return new Promise((resolve, reject) => {+ const responseType = options?.responseType ?? 'text';++ wx.request({+ url,+ method: (options?.method ?? 'GET') as WechatMinigame.RequestOption['method'],+ data: options?.body,+ header: options?.headers,+ responseType: responseType === 'arraybuffer' ? 'arraybuffer' : 'text',+ timeout: options?.timeout,+ success: (res) => {+ const ok = res.statusCode >= 200 && res.statusCode < 300;+ const headers: Record<string, string> = {};++ if (res.header) {+ for (const key of Object.keys(res.header)) {+ headers[key.toLowerCase()] = res.header[key];+ }+ }++ resolve({+ ok,+ status: res.statusCode,+ statusText: ok ? 'OK' : 'Error',+ headers,+ json: <T>() => {+ if (typeof res.data === 'string') {+ return Promise.resolve(JSON.parse(res.data) as T);+ }+ return Promise.resolve(res.data as T);+ },+ text: () => {+ if (typeof res.data === 'string') {+ return Promise.resolve(res.data);+ }+ return Promise.resolve(JSON.stringify(res.data));+ },+ arrayBuffer: () => {+ if (res.data instanceof ArrayBuffer) {+ return Promise.resolve(res.data);+ }+ // Convert string to ArrayBuffer+ const encoder = new TextEncoder();+ const data = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);+ return Promise.resolve(encoder.encode(data).buffer);+ },+ });+ },+ fail: (err) => {+ reject(new Error(`wx.request failed: ${err.errMsg}`));+ },+ });+ });+}++// =============================================================================+// Global Fetch Polyfill+// =============================================================================++export function polyfillFetch(): void {+ if (typeof globalThis.fetch === 'undefined') {+ (globalThis as any).fetch = async (+ input: string | URL,+ init?: RequestInit+ ): Promise<Response> => {+ const url = typeof input === 'string' ? input : input.toString();+ const options: PlatformRequestOptions = {+ method: (init?.method as PlatformRequestOptions['method']) ?? 'GET',+ headers: init?.headers as Record<string, string>,+ body: init?.body as string | ArrayBuffer,+ };++ const response = await wxFetch(url, options);++ // Return a Response-like object+ return {+ ok: response.ok,+ status: response.status,+ statusText: response.statusText,+ headers: new Headers(response.headers),+ json: () => response.json(),+ text: () => response.text(),+ arrayBuffer: () => response.arrayBuffer(),+ blob: () => Promise.reject(new Error('Blob not supported in WeChat')),+ formData: () => Promise.reject(new Error('FormData not supported in WeChat')),+ clone: () => { throw new Error('clone not supported'); },+ body: null,+ bodyUsed: false,+ redirected: false,+ type: 'basic',+ url,+ } as unknown as Response;+ };+ }+}diff --git a/sdk/src/platform/wechat/fs.ts b/sdk/src/platform/wechat/fs.tsnew file mode 100644index 000000000..34a29d466--- /dev/null+++ b/sdk/src/platform/wechat/fs.ts@@ -0,0 +1,122 @@+/**+ * @file fs.ts+ * @brief File system adapter for WeChat MiniGame+ */++/// <reference types="minigame-api-typings" />++// =============================================================================+// Types+// =============================================================================++type WxFileSystemManager = WechatMinigame.FileSystemManager;++// =============================================================================+// WeChat File System+// =============================================================================++let fsManager: WxFileSystemManager | null = null;++function getFileSystemManager(): WxFileSystemManager {+ if (!fsManager) {+ fsManager = wx.getFileSystemManager();+ }+ return fsManager;+}++/**+ * Read file as ArrayBuffer (synchronous)+ */+export function wxReadFileSync(path: string): ArrayBuffer {+ const fs = getFileSystemManager();+ return fs.readFileSync(path) as ArrayBuffer;+}++/**+ * Read file as string (synchronous)+ */+export function wxReadTextFileSync(path: string, encoding: 'utf8' | 'utf-8' = 'utf-8'): string {+ const fs = getFileSystemManager();+ return fs.readFileSync(path, encoding) as string;+}++/**+ * Read file as ArrayBuffer (async)+ */+export function wxReadFile(path: string): Promise<ArrayBuffer> {+ return new Promise((resolve, reject) => {+ const fs = getFileSystemManager();+ fs.readFile({+ filePath: path,+ success: (res) => {+ resolve(res.data as ArrayBuffer);+ },+ fail: (err) => {+ reject(new Error(`Failed to read file "${path}": ${err.errMsg}`));+ },+ });+ });+}++/**+ * Read file as string (async)+ */+export function wxReadTextFile(path: string, encoding: 'utf8' | 'utf-8' = 'utf-8'): Promise<string> {+ return new Promise((resolve, reject) => {+ const fs = getFileSystemManager();+ fs.readFile({+ filePath: path,+ encoding,+ success: (res) => {+ resolve(res.data as string);+ },+ fail: (err) => {+ reject(new Error(`Failed to read file "${path}": ${err.errMsg}`));+ },+ });+ });+}++/**+ * Check if file exists+ */+export function wxFileExists(path: string): Promise<boolean> {+ return new Promise((resolve) => {+ const fs = getFileSystemManager();+ fs.access({+ path,+ success: () => resolve(true),+ fail: () => resolve(false),+ });+ });+}++/**+ * Check if file exists (sync)+ */+export function wxFileExistsSync(path: string): boolean {+ const fs = getFileSystemManager();+ try {+ fs.accessSync(path);+ return true;+ } catch {+ return false;+ }+}++/**+ * Write file+ */+export function wxWriteFile(path: string, data: string | ArrayBuffer): Promise<void> {+ return new Promise((resolve, reject) => {+ const fs = getFileSystemManager();+ fs.writeFile({+ filePath: path,+ data,+ success: () => resolve(),+ fail: (err) => {+ reject(new Error(`Failed to write file "${path}": ${err.errMsg}`));+ },+ });+ });+}diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.tsnew file mode 100644index 000000000..e3123b6ba--- /dev/null+++ b/sdk/src/platform/wechat/index.ts@@ -0,0 +1,81 @@+/**+ * @file index.ts+ * @brief WeChat MiniGame platform adapter+ */++/// <reference types="minigame-api-typings" />++import type {+ PlatformAdapter,+ PlatformRequestOptions,+ PlatformResponse,+ WasmInstantiateResult,+} from '../types';+import { wxFetch, polyfillFetch } from './fetch';+import { wxInstantiateWasm, polyfillWebAssembly } from './wasm';+import { wxReadFile, wxReadTextFile, wxFileExists } from './fs';++// =============================================================================+// WeChat Platform Adapter+// =============================================================================++class WeChatPlatformAdapter implements PlatformAdapter {+ readonly name = 'wechat' as const;++ async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {+ return wxFetch(url, options);+ }++ async readFile(path: string): Promise<ArrayBuffer> {+ return wxReadFile(path);+ }++ async readTextFile(path: string): Promise<string> {+ return wxReadTextFile(path);+ }++ async fileExists(path: string): Promise<boolean> {+ return wxFileExists(path);+ }++ async instantiateWasm(+ pathOrBuffer: string | ArrayBuffer,+ imports: WebAssembly.Imports+ ): Promise<WasmInstantiateResult> {+ if (typeof pathOrBuffer !== 'string') {+ throw new Error(+ 'WeChat WXWebAssembly requires a file path string, not ArrayBuffer'+ );+ }+ return wxInstantiateWasm(pathOrBuffer, imports);+ }+}++// =============================================================================+// Initialization+// =============================================================================++let initialized = false;++/**+ * Initialize WeChat platform polyfills+ * Call this at the entry point of your game+ */+export function initWeChatPlatform(): void {+ if (initialized) return;+ initialized = true;++ polyfillFetch();+ polyfillWebAssembly();++ console.log('[ESEngine] WeChat platform initialized');+}++// =============================================================================+// Export+// =============================================================================++export const wechatAdapter = new WeChatPlatformAdapter();++export { polyfillFetch, polyfillWebAssembly };+export { wxReadFile, wxReadTextFile, wxFileExists, wxFileExistsSync, wxWriteFile } from './fs';diff --git a/sdk/src/platform/wechat/wasm.ts b/sdk/src/platform/wechat/wasm.tsnew file mode 100644index 000000000..4b446e595--- /dev/null+++ b/sdk/src/platform/wechat/wasm.ts@@ -0,0 +1,89 @@+/**+ * @file wasm.ts+ * @brief WebAssembly adapter for WeChat MiniGame using WXWebAssembly+ */++/// <reference types="minigame-api-typings" />++import type { WasmInstantiateResult } from '../types';++// =============================================================================+// WeChat WASM Implementation+// =============================================================================++/**+ * Instantiate WASM using WXWebAssembly+ * Note: WeChat requires path to be a string (package-relative path), not ArrayBuffer+ */+export async function wxInstantiateWasm(+ path: string,+ imports: WebAssembly.Imports+): Promise<WasmInstantiateResult> {+ if (typeof WXWebAssembly === 'undefined') {+ throw new Error('WXWebAssembly is not available. Requires WeChat base library >= 2.13.0');+ }++ // WeChat requires the path to be a package-relative path string+ // e.g., "esengine.wasm" not "/esengine.wasm" or ArrayBuffer+ const normalizedPath = path.startsWith('/') ? path.slice(1) : path;++ try {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const result = await WXWebAssembly.instantiate(normalizedPath, imports as any);+ return {+ // WXWebAssembly.instantiate returns { instance, module } but types are slightly different+ instance: (result as any).instance ?? result,+ module: (result as any).module,+ };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ throw new Error(`WXWebAssembly.instantiate failed for "${normalizedPath}": ${message}`);+ }+}++// =============================================================================+// Global WebAssembly Polyfill+// =============================================================================++/**+ * Polyfill global WebAssembly with WXWebAssembly+ * This allows existing code using WebAssembly.instantiate to work on WeChat+ */+export function polyfillWebAssembly(): void {+ if (typeof WXWebAssembly !== 'undefined' && typeof WebAssembly === 'undefined') {+ (globalThis as any).WebAssembly = {+ instantiate: async (+ bufferOrPath: BufferSource | string,+ imports?: WebAssembly.Imports+ ) => {+ if (typeof bufferOrPath !== 'string') {+ throw new Error(+ 'WeChat WXWebAssembly requires a file path string, not ArrayBuffer. ' ++ 'Use platform adapter instead of direct WebAssembly.instantiate.'+ );+ }+ return wxInstantiateWasm(bufferOrPath, imports ?? {});+ },+ compile: () => {+ throw new Error('WebAssembly.compile is not supported in WeChat MiniGame');+ },+ compileStreaming: () => {+ throw new Error('WebAssembly.compileStreaming is not supported in WeChat MiniGame');+ },+ instantiateStreaming: () => {+ throw new Error('WebAssembly.instantiateStreaming is not supported in WeChat MiniGame');+ },+ validate: () => {+ throw new Error('WebAssembly.validate is not supported in WeChat MiniGame');+ },+ Module: class {} as any,+ Instance: class {} as any,+ Memory: class {} as any,+ Table: class {} as any,+ Global: class {} as any,+ CompileError: Error,+ LinkError: Error,+ RuntimeError: Error,+ };+ }+}diff --git a/sdk/src/preview/PreviewPlugin.ts b/sdk/src/preview/PreviewPlugin.tsindex 85be70303..bb521b6f8 100644--- a/sdk/src/preview/PreviewPlugin.ts+++ b/sdk/src/preview/PreviewPlugin.ts@@ -7,6 +7,7 @@ import type { App, Plugin } from '../app';import { Assets, assetPlugin } from '../asset';import { loadSceneWithAssets, type SceneData } from '../scene';import { LocalTransform, Camera, type LocalTransformData, type CameraData } from '../component';+import { platformFetch } from '../platform';// =============================================================================// PreviewPlugin@@ -44,11 +45,11 @@ export class PreviewPlugin implements Plugin {if (!this.app_) return;try {- const response = await fetch(this.sceneUrl_);+ const response = await platformFetch(this.sceneUrl_);if (!response.ok) {throw new Error(`Failed to fetch scene: ${response.status}`);}- const sceneData = await response.json() as SceneData;+ const sceneData = await response.json<SceneData>();const assets = this.app_.getResource(Assets);await loadSceneWithAssets(this.app_.world, sceneData, {