refactor: reorganize package structure and decouple framework packages (#338)

* refactor: reorganize package structure and decouple framework packages

## Package Structure Reorganization
- Reorganized 55 packages into categorized subdirectories:
  - packages/framework/ - Generic framework (Laya/Cocos compatible)
  - packages/engine/ - ESEngine core modules
  - packages/rendering/ - Rendering modules (WASM dependent)
  - packages/physics/ - Physics modules
  - packages/streaming/ - World streaming
  - packages/network-ext/ - Network extensions
  - packages/editor/ - Editor framework and plugins
  - packages/rust/ - Rust WASM engine
  - packages/tools/ - Build tools and SDK

## Framework Package Decoupling
- Decoupled behavior-tree and blueprint packages from ESEngine dependencies
- Created abstracted interfaces (IBTAssetManager, IBehaviorTreeAssetContent)
- ESEngine-specific code moved to esengine/ subpath exports
- Framework packages now usable with Cocos/Laya without ESEngine

## CI Configuration
- Updated CI to only type-check and lint framework packages
- Added type-check:framework and lint:framework scripts

## Breaking Changes
- Package import paths changed due to directory reorganization
- ESEngine integrations now use subpath imports (e.g., '@esengine/behavior-tree/esengine')

* fix: update es-engine file path after directory reorganization

* docs: update README to focus on framework over engine

* ci: only build framework packages, remove Rust/WASM dependencies

* fix: remove esengine subpath from behavior-tree and blueprint builds

ESEngine integration code will only be available in full engine builds.
Framework packages are now purely engine-agnostic.

* fix: move network-protocols to framework, build both in CI

* fix: update workflow paths from packages/core to packages/framework/core

* fix: exclude esengine folder from type-check in behavior-tree and blueprint

* fix: update network tsconfig references to new paths

* fix: add test:ci:framework to only test framework packages in CI

* fix: only build core and math npm packages in CI

* fix: exclude test files from CodeQL and fix string escaping security issue
This commit is contained in:
YHH
2025-12-26 14:50:35 +08:00
committed by GitHub
parent a84ff902e4
commit 155411e743
1936 changed files with 4147 additions and 11578 deletions

View File

@@ -0,0 +1,48 @@
# @esengine/platform-common
平台通用接口定义包,定义了所有平台子系统的接口规范。
## 安装
```bash
npm install @esengine/platform-common
```
## 用途
此包仅包含 TypeScript 接口定义,供各平台适配器包实现:
- `@esengine/platform-wechat` - 微信小游戏
- `@esengine/platform-web` - Web 浏览器
- `@esengine/platform-bytedance` - 抖音小游戏
## 接口列表
### Canvas/渲染
- `IPlatformCanvasSubsystem`
- `IPlatformCanvas`
- `IPlatformImage`
### 音频
- `IPlatformAudioSubsystem`
- `IPlatformAudioContext`
### 存储
- `IPlatformStorageSubsystem`
### 网络
- `IPlatformNetworkSubsystem`
- `IPlatformWebSocket`
### 输入
- `IPlatformInputSubsystem`
### 文件系统
- `IPlatformFileSubsystem`
### WASM
- `IPlatformWASMSubsystem`
## License
MIT

View File

@@ -0,0 +1,21 @@
{
"id": "platform-common",
"name": "@esengine/platform-common",
"displayName": "Platform Common",
"description": "Common platform interfaces | 平台通用接口定义",
"version": "1.0.0",
"category": "Core",
"icon": "Layers",
"tags": ["platform", "common", "interface"],
"isCore": true,
"defaultEnabled": true,
"isEngineModule": true,
"canContainContent": false,
"platforms": ["web", "desktop", "mobile"],
"dependencies": [],
"exports": {
"other": ["WasmLibraryLoaderFactory", "IPlatformAdapter"]
},
"requiresWasm": false,
"outputPath": "dist/index.mjs"
}

View File

@@ -0,0 +1,50 @@
{
"name": "@esengine/platform-common",
"version": "1.0.0",
"description": "平台通用接口定义",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": [
"dist"
],
"scripts": {
"build": "rollup -c",
"build:npm": "npm run build",
"clean": "rimraf dist",
"type-check": "npx tsc --noEmit",
"prepublishOnly": "npm run build"
},
"keywords": [
"ecs",
"platform",
"interface",
"common"
],
"author": "yhh",
"license": "MIT",
"devDependencies": {
"@rollup/plugin-commonjs": "^28.0.3",
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-typescript": "^11.1.6",
"rimraf": "^5.0.0",
"rollup": "^4.42.0",
"rollup-plugin-dts": "^6.2.1",
"typescript": "^5.8.3"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/esengine/esengine.git",
"directory": "packages/platform-common"
}
}

View File

@@ -0,0 +1,40 @@
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import dts from 'rollup-plugin-dts';
export default [
// ESM and CJS builds
{
input: 'src/index.ts',
output: [
{
file: 'dist/index.mjs',
format: 'esm',
sourcemap: true
},
{
file: 'dist/index.js',
format: 'cjs',
sourcemap: true
}
],
plugins: [
resolve(),
commonjs(),
typescript({
tsconfig: './tsconfig.json',
declaration: false
})
]
},
// Type declarations
{
input: 'src/index.ts',
output: {
file: 'dist/index.d.ts',
format: 'esm'
},
plugins: [dts()]
}
];

View File

@@ -0,0 +1,847 @@
/**
* 平台子系统接口定义
* 将平台能力分解为独立的子系统,支持按需实现和代码裁剪
*/
// ============================================================================
// Canvas/渲染子系统
// ============================================================================
/**
* 平台 Canvas 对象抽象
*/
/**
* Canvas 上下文属性(兼容 Web 和小游戏平台)
*/
export interface CanvasContextAttributes {
alpha?: boolean | number;
antialias?: boolean;
depth?: boolean;
stencil?: boolean;
premultipliedAlpha?: boolean;
preserveDrawingBuffer?: boolean;
failIfMajorPerformanceCaveat?: boolean;
powerPreference?: 'default' | 'high-performance' | 'low-power';
antialiasSamples?: number;
}
export interface IPlatformCanvas {
width: number;
height: number;
getContext(contextType: '2d' | 'webgl' | 'webgl2', contextAttributes?: CanvasContextAttributes): RenderingContext | null;
toDataURL(): string;
toTempFilePath?(options: TempFilePathOptions): void;
}
/**
* 平台 Image 对象抽象
*/
export interface IPlatformImage {
src: string;
width: number;
height: number;
onload: (() => void) | null;
onerror: ((error: any) => void) | null;
}
/**
* 临时文件路径选项
*/
export interface TempFilePathOptions {
x?: number;
y?: number;
width?: number;
height?: number;
destWidth?: number;
destHeight?: number;
fileType?: 'png' | 'jpg';
quality?: number;
success?: (res: { tempFilePath: string }) => void;
fail?: (error: any) => void;
complete?: () => void;
}
/**
* Canvas 子系统接口
*/
export interface IPlatformCanvasSubsystem {
/**
* 创建主 Canvas首次调用或离屏 Canvas
*/
createCanvas(width?: number, height?: number): IPlatformCanvas;
/**
* 创建图片对象
*/
createImage(): IPlatformImage;
/**
* 创建 ImageData
*/
createImageData?(width: number, height: number): ImageData;
/**
* 获取屏幕宽度
*/
getScreenWidth(): number;
/**
* 获取屏幕高度
*/
getScreenHeight(): number;
/**
* 获取设备像素比
*/
getDevicePixelRatio(): number;
}
// ============================================================================
// 音频子系统
// ============================================================================
/**
* 平台音频上下文抽象
*/
export interface IPlatformAudioContext {
src: string;
autoplay: boolean;
loop: boolean;
volume: number;
duration: number;
currentTime: number;
paused: boolean;
buffered: number;
play(): void;
pause(): void;
stop(): void;
seek(position: number): void;
destroy(): void;
onPlay(callback: () => void): void;
onPause(callback: () => void): void;
onStop(callback: () => void): void;
onEnded(callback: () => void): void;
onError(callback: (error: { errCode: number; errMsg: string }) => void): void;
onTimeUpdate(callback: () => void): void;
onCanplay(callback: () => void): void;
onSeeking(callback: () => void): void;
onSeeked(callback: () => void): void;
offPlay(callback: () => void): void;
offPause(callback: () => void): void;
offStop(callback: () => void): void;
offEnded(callback: () => void): void;
offError(callback: (error: { errCode: number; errMsg: string }) => void): void;
offTimeUpdate(callback: () => void): void;
}
/**
* 音频子系统接口
*/
export interface IPlatformAudioSubsystem {
/**
* 创建音频上下文
*/
createAudioContext(options?: { useWebAudioImplement?: boolean }): IPlatformAudioContext;
/**
* 获取支持的音频格式
*/
getSupportedFormats(): string[];
/**
* 设置静音模式下是否可以播放音频
*/
setInnerAudioOption?(options: {
mixWithOther?: boolean;
obeyMuteSwitch?: boolean;
speakerOn?: boolean;
}): Promise<void>;
}
// ============================================================================
// 存储子系统
// ============================================================================
/**
* 存储信息
*/
export interface StorageInfo {
keys: string[];
currentSize: number;
limitSize: number;
}
/**
* 存储子系统接口
*/
export interface IPlatformStorageSubsystem {
/**
* 同步获取存储
*/
getStorageSync<T = any>(key: string): T | undefined;
/**
* 同步设置存储
*/
setStorageSync<T = any>(key: string, value: T): void;
/**
* 同步移除存储
*/
removeStorageSync(key: string): void;
/**
* 同步清空存储
*/
clearStorageSync(): void;
/**
* 获取存储信息
*/
getStorageInfoSync(): StorageInfo;
/**
* 异步获取存储
*/
getStorage<T = any>(key: string): Promise<T | undefined>;
/**
* 异步设置存储
*/
setStorage<T = any>(key: string, value: T): Promise<void>;
/**
* 异步移除存储
*/
removeStorage(key: string): Promise<void>;
/**
* 异步清空存储
*/
clearStorage(): Promise<void>;
}
// ============================================================================
// 网络子系统
// ============================================================================
/**
* 请求配置
*/
export interface RequestConfig {
url: string;
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT';
data?: any;
header?: Record<string, string>;
timeout?: number;
dataType?: 'json' | 'text' | 'arraybuffer';
responseType?: 'text' | 'arraybuffer';
}
/**
* 请求响应
*/
export interface RequestResponse<T = any> {
data: T;
statusCode: number;
header: Record<string, string>;
}
/**
* 下载任务
*/
export interface IDownloadTask {
abort(): void;
onProgressUpdate(callback: (res: {
progress: number;
totalBytesWritten: number;
totalBytesExpectedToWrite: number;
}) => void): void;
offProgressUpdate(callback: Function): void;
}
/**
* 上传任务
*/
export interface IUploadTask {
abort(): void;
onProgressUpdate(callback: (res: {
progress: number;
totalBytesSent: number;
totalBytesExpectedToSend: number;
}) => void): void;
offProgressUpdate(callback: Function): void;
}
/**
* WebSocket 接口
*/
export interface IPlatformWebSocket {
send(data: string | ArrayBuffer): void;
close(code?: number, reason?: string): void;
onOpen(callback: (res: { header: Record<string, string> }) => void): void;
onClose(callback: (res: { code: number; reason: string }) => void): void;
onError(callback: (error: any) => void): void;
onMessage(callback: (res: { data: string | ArrayBuffer }) => void): void;
}
/**
* 网络子系统接口
*/
export interface IPlatformNetworkSubsystem {
/**
* 发起请求
*/
request<T = any>(config: RequestConfig): Promise<RequestResponse<T>>;
/**
* 下载文件
*/
downloadFile(options: {
url: string;
filePath?: string;
header?: Record<string, string>;
timeout?: number;
}): Promise<{ tempFilePath: string; filePath?: string; statusCode: number }> & IDownloadTask;
/**
* 上传文件
*/
uploadFile(options: {
url: string;
filePath: string;
name: string;
header?: Record<string, string>;
formData?: Record<string, any>;
timeout?: number;
}): Promise<{ data: string; statusCode: number }> & IUploadTask;
/**
* 创建 WebSocket 连接
*/
connectSocket(options: {
url: string;
header?: Record<string, string>;
protocols?: string[];
timeout?: number;
}): IPlatformWebSocket;
/**
* 获取网络类型
*/
getNetworkType(): Promise<'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none'>;
/**
* 监听网络状态变化
*/
onNetworkStatusChange(callback: (res: {
isConnected: boolean;
networkType: string;
}) => void): void;
/**
* 取消监听网络状态变化
*/
offNetworkStatusChange(callback: Function): void;
}
// ============================================================================
// 输入子系统
// ============================================================================
/**
* 触摸点信息
* Touch point information
*/
export interface TouchInfo {
identifier: number;
x: number;
y: number;
force?: number;
}
/**
* 触摸事件
* Touch event
*/
export interface TouchEvent {
touches: TouchInfo[];
changedTouches: TouchInfo[];
timeStamp: number;
}
/**
* 触摸事件处理函数
* Touch event handler
*/
export type TouchHandler = (event: TouchEvent) => void;
/**
* 键盘事件信息
* Keyboard event information
*/
export interface KeyboardEventInfo {
/** 按键代码 (如 'KeyW', 'Space', 'ArrowUp') | Key code */
code: string;
/** 按键值 (如 'w', ' ', 'ArrowUp') | Key value */
key: string;
/** Alt 键是否按下 | Alt key pressed */
altKey: boolean;
/** Ctrl 键是否按下 | Ctrl key pressed */
ctrlKey: boolean;
/** Shift 键是否按下 | Shift key pressed */
shiftKey: boolean;
/** Meta 键是否按下 (Windows/Command) | Meta key pressed */
metaKey: boolean;
/** 是否重复触发 | Is repeat */
repeat: boolean;
/** 时间戳 | Timestamp */
timeStamp: number;
}
/**
* 键盘事件处理函数
* Keyboard event handler
*/
export type KeyboardHandler = (event: KeyboardEventInfo) => void;
/**
* 鼠标按钮枚举
* Mouse button enum
*/
export enum MouseButton {
/** 左键 | Left button */
Left = 0,
/** 中键 | Middle button */
Middle = 1,
/** 右键 | Right button */
Right = 2
}
/**
* 鼠标事件信息
* Mouse event information
*/
export interface MouseEventInfo {
/** X 坐标 | X coordinate */
x: number;
/** Y 坐标 | Y coordinate */
y: number;
/** 相对上次的 X 偏移 | X movement delta */
movementX: number;
/** 相对上次的 Y 偏移 | Y movement delta */
movementY: number;
/** 按下的按钮 | Button pressed */
button: MouseButton;
/** 所有按下的按钮位掩码 | Buttons bitmask */
buttons: number;
/** Alt 键是否按下 | Alt key pressed */
altKey: boolean;
/** Ctrl 键是否按下 | Ctrl key pressed */
ctrlKey: boolean;
/** Shift 键是否按下 | Shift key pressed */
shiftKey: boolean;
/** Meta 键是否按下 | Meta key pressed */
metaKey: boolean;
/** 时间戳 | Timestamp */
timeStamp: number;
}
/**
* 鼠标滚轮事件信息
* Mouse wheel event information
*/
export interface WheelEventInfo {
/** X 坐标 | X coordinate */
x: number;
/** Y 坐标 | Y coordinate */
y: number;
/** X 轴滚动量 | Delta X */
deltaX: number;
/** Y 轴滚动量 | Delta Y */
deltaY: number;
/** Z 轴滚动量 | Delta Z */
deltaZ: number;
/** 时间戳 | Timestamp */
timeStamp: number;
}
/**
* 鼠标事件处理函数
* Mouse event handler
*/
export type MouseHandler = (event: MouseEventInfo) => void;
/**
* 鼠标滚轮事件处理函数
* Mouse wheel event handler
*/
export type WheelHandler = (event: WheelEventInfo) => void;
/**
* 输入子系统接口
* Input subsystem interface
*/
export interface IPlatformInputSubsystem {
// ========== 触摸事件 | Touch events ==========
/**
* 监听触摸开始
* Listen for touch start
*/
onTouchStart(handler: TouchHandler): void;
/**
* 监听触摸移动
* Listen for touch move
*/
onTouchMove(handler: TouchHandler): void;
/**
* 监听触摸结束
* Listen for touch end
*/
onTouchEnd(handler: TouchHandler): void;
/**
* 监听触摸取消
* Listen for touch cancel
*/
onTouchCancel(handler: TouchHandler): void;
/**
* 取消监听触摸开始
* Stop listening for touch start
*/
offTouchStart(handler: TouchHandler): void;
/**
* 取消监听触摸移动
* Stop listening for touch move
*/
offTouchMove(handler: TouchHandler): void;
/**
* 取消监听触摸结束
* Stop listening for touch end
*/
offTouchEnd(handler: TouchHandler): void;
/**
* 取消监听触摸取消
* Stop listening for touch cancel
*/
offTouchCancel(handler: TouchHandler): void;
/**
* 获取触摸点是否支持压感
* Check if touch supports pressure
*/
supportsPressure?(): boolean;
// ========== 键盘事件 | Keyboard events ==========
/**
* 监听键盘按下
* Listen for key down
*/
onKeyDown?(handler: KeyboardHandler): void;
/**
* 监听键盘释放
* Listen for key up
*/
onKeyUp?(handler: KeyboardHandler): void;
/**
* 取消监听键盘按下
* Stop listening for key down
*/
offKeyDown?(handler: KeyboardHandler): void;
/**
* 取消监听键盘释放
* Stop listening for key up
*/
offKeyUp?(handler: KeyboardHandler): void;
// ========== 鼠标事件 | Mouse events ==========
/**
* 监听鼠标移动
* Listen for mouse move
*/
onMouseMove?(handler: MouseHandler): void;
/**
* 监听鼠标按下
* Listen for mouse down
*/
onMouseDown?(handler: MouseHandler): void;
/**
* 监听鼠标释放
* Listen for mouse up
*/
onMouseUp?(handler: MouseHandler): void;
/**
* 监听鼠标滚轮
* Listen for mouse wheel
*/
onWheel?(handler: WheelHandler): void;
/**
* 取消监听鼠标移动
* Stop listening for mouse move
*/
offMouseMove?(handler: MouseHandler): void;
/**
* 取消监听鼠标按下
* Stop listening for mouse down
*/
offMouseDown?(handler: MouseHandler): void;
/**
* 取消监听鼠标释放
* Stop listening for mouse up
*/
offMouseUp?(handler: MouseHandler): void;
/**
* 取消监听鼠标滚轮
* Stop listening for mouse wheel
*/
offWheel?(handler: WheelHandler): void;
// ========== 输入能力查询 | Input capability queries ==========
/**
* 是否支持键盘输入
* Check if keyboard input is supported
*/
supportsKeyboard?(): boolean;
/**
* 是否支持鼠标输入
* Check if mouse input is supported
*/
supportsMouse?(): boolean;
// ========== 生命周期 | Lifecycle ==========
/**
* 释放资源
* Dispose resources
*/
dispose?(): void;
}
// ============================================================================
// 文件系统子系统
// ============================================================================
/**
* 文件信息
*/
export interface FileInfo {
size: number;
createTime: number;
modifyTime?: number;
isDirectory: boolean;
isFile: boolean;
}
/**
* 文件系统子系统接口
*/
export interface IPlatformFileSubsystem {
/**
* 读取文件
*/
readFile(options: {
filePath: string;
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'utf-8' | 'utf8';
position?: number;
length?: number;
}): Promise<string | ArrayBuffer>;
/**
* 同步读取文件
*/
readFileSync(
filePath: string,
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'utf-8' | 'utf8',
position?: number,
length?: number
): string | ArrayBuffer;
/**
* 写入文件
*/
writeFile(options: {
filePath: string;
data: string | ArrayBuffer;
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'utf-8' | 'utf8';
}): Promise<void>;
/**
* 同步写入文件
*/
writeFileSync(
filePath: string,
data: string | ArrayBuffer,
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'utf-8' | 'utf8'
): void;
/**
* 追加文件内容
*/
appendFile(options: {
filePath: string;
data: string | ArrayBuffer;
encoding?: 'ascii' | 'base64' | 'binary' | 'hex' | 'ucs2' | 'utf-8' | 'utf8';
}): Promise<void>;
/**
* 删除文件
*/
unlink(filePath: string): Promise<void>;
/**
* 创建目录
*/
mkdir(options: {
dirPath: string;
recursive?: boolean;
}): Promise<void>;
/**
* 删除目录
*/
rmdir(options: {
dirPath: string;
recursive?: boolean;
}): Promise<void>;
/**
* 读取目录
*/
readdir(dirPath: string): Promise<string[]>;
/**
* 获取文件信息
*/
stat(path: string): Promise<FileInfo>;
/**
* 检查文件/目录是否存在
*/
access(path: string): Promise<void>;
/**
* 重命名文件
*/
rename(oldPath: string, newPath: string): Promise<void>;
/**
* 复制文件
*/
copyFile(srcPath: string, destPath: string): Promise<void>;
/**
* 获取用户数据目录路径
*/
getUserDataPath(): string;
/**
* 解压文件
*/
unzip?(options: {
zipFilePath: string;
targetPath: string;
}): Promise<void>;
}
// ============================================================================
// WASM 子系统
// ============================================================================
/**
* WASM 模块导出
*/
export type WASMExports = Record<string, WebAssembly.ExportValue>;
/**
* WASM 导入值类型(兼容 Web 和小游戏平台)
*/
export type WASMImportValue = WebAssembly.ExportValue | number;
/**
* WASM 模块导入
*/
export type WASMImports = Record<string, Record<string, WASMImportValue>>;
/**
* WASM 实例
*/
export interface IWASMInstance {
exports: WASMExports;
}
/**
* WASM 子系统接口
*/
export interface IPlatformWASMSubsystem {
/**
* 实例化 WASM 模块
* @param path WASM 文件路径
* @param imports 导入对象
*/
instantiate(path: string, imports?: WASMImports): Promise<IWASMInstance>;
/**
* 检查是否支持 WASM
*/
isSupported(): boolean;
}
// ============================================================================
// 系统信息
// ============================================================================
/**
* 系统信息
*/
export interface SystemInfo {
/** 设备品牌 */
brand: string;
/** 设备型号 */
model: string;
/** 设备像素比 */
pixelRatio: number;
/** 屏幕宽度 */
screenWidth: number;
/** 屏幕高度 */
screenHeight: number;
/** 可使用窗口宽度 */
windowWidth: number;
/** 可使用窗口高度 */
windowHeight: number;
/** 状态栏高度 */
statusBarHeight: number;
/** 操作系统及版本 */
system: string;
/** 客户端平台 */
platform: 'ios' | 'android' | 'windows' | 'mac' | 'devtools';
/** 客户端基础库版本 */
SDKVersion: string;
/** 设备性能等级 */
benchmarkLevel: number;
/** 设备内存大小 (MB) */
memorySize?: number;
}

View File

@@ -0,0 +1,98 @@
/**
* 平台通用接口定义包
* @packageDocumentation
*/
// 导出所有平台子系统接口
export type {
// Canvas/渲染
IPlatformCanvas,
IPlatformImage,
IPlatformCanvasSubsystem,
TempFilePathOptions,
CanvasContextAttributes,
// 音频
IPlatformAudioContext,
IPlatformAudioSubsystem,
// 存储
IPlatformStorageSubsystem,
StorageInfo,
// 网络
IPlatformNetworkSubsystem,
RequestConfig,
RequestResponse,
IDownloadTask,
IUploadTask,
IPlatformWebSocket,
// 输入
IPlatformInputSubsystem,
TouchInfo,
TouchEvent,
TouchHandler,
KeyboardEventInfo,
KeyboardHandler,
MouseEventInfo,
MouseHandler,
WheelEventInfo,
WheelHandler,
// 文件系统
IPlatformFileSubsystem,
FileInfo,
// WASM
IPlatformWASMSubsystem,
IWASMInstance,
WASMExports,
WASMImports,
// 系统信息
SystemInfo
} from './IPlatformSubsystems';
// 导出枚举值 | Export enum values
export { MouseButton } from './IPlatformSubsystems';
// WASM 库加载器
export {
PlatformType,
WasmLibraryLoaderFactory
} from './wasm';
export type {
WasmLibraryConfig,
PlatformInfo,
IWasmLibraryLoader,
IPlatformWasmLoader
} from './wasm';
// Polyfills
export {
installTextDecoderPolyfill,
installTextEncoderPolyfill,
isTextDecoderAvailable,
isTextEncoderAvailable,
installAllPolyfills,
getRequiredPolyfills,
TextDecoderPolyfill,
TextEncoderPolyfill
} from './polyfills';
/**
* 检测是否在编辑器环境Tauri 桌面应用)
* Detect if running in editor environment (Tauri desktop app)
*/
export function isEditorEnvironment(): boolean {
if (typeof window === 'undefined') {
return false;
}
// Tauri 桌面应用 | Tauri desktop app
if ('__TAURI__' in window || '__TAURI_INTERNALS__' in window) {
return true;
}
// 编辑器标记 | Editor marker
if ('__ESENGINE_EDITOR__' in window) {
return true;
}
return false;
}

View File

@@ -0,0 +1,235 @@
/**
* TextDecoder polyfill
*
* 用于不原生支持 TextDecoder 的平台(如微信小游戏 iOS 环境)
*
* 支持以下编码格式:
* - UTF-8包含1-4字节字符、代理对
* - ASCII
* - UTF-16LE
*/
class TextDecoderPolyfill {
/**
* 编码格式
*/
readonly encoding: string;
/**
* 是否在遇到无效序列时抛出错误
*/
readonly fatal: boolean = false;
/**
* 是否忽略 BOM字节顺序标记
*/
readonly ignoreBOM: boolean = false;
/**
* 创建 TextDecoder 实例
*
* @param encoding - 编码格式,默认 'utf-8'
* @param options - 解码选项
*/
constructor(encoding: string = 'utf-8', options?: TextDecoderOptions) {
this.encoding = encoding.toLowerCase().replace('-', '');
if (options?.fatal) {
this.fatal = options.fatal;
}
if (options?.ignoreBOM) {
this.ignoreBOM = options.ignoreBOM;
}
}
/**
* 将二进制数据解码为字符串
*
* @param input - 要解码的二进制数据
* @param options - 解码选项
* @returns 解码后的字符串
*/
decode(input?: BufferSource | null, options?: TextDecodeOptions): string {
if (!input) return '';
const bytes = input instanceof Uint8Array
? input
: input instanceof ArrayBuffer
? new Uint8Array(input)
: new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
if (this.encoding === 'utf8' || this.encoding === 'utf-8') {
return this.decodeUTF8(bytes);
}
if (this.encoding === 'ascii' || this.encoding === 'usascii') {
return this.decodeASCII(bytes);
}
if (this.encoding === 'utf16le' || this.encoding === 'utf-16le') {
return this.decodeUTF16LE(bytes);
}
// 降级:作为 ASCII 处理
return this.decodeASCII(bytes);
}
/**
* 解码 UTF-8 数据
*
* @param bytes - 字节数组
* @returns 解码后的字符串
*/
private decodeUTF8(bytes: Uint8Array): string {
const result: string[] = [];
let i = 0;
// 跳过 BOM如果存在且不忽略
if (!this.ignoreBOM && bytes.length >= 3 &&
bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF) {
i = 3;
}
while (i < bytes.length) {
const byte1 = bytes[i++];
if (byte1 < 0x80) {
// 1字节字符ASCII: 0xxxxxxx
result.push(String.fromCharCode(byte1));
} else if ((byte1 & 0xE0) === 0xC0) {
// 2字节字符110xxxxx 10xxxxxx
if (i >= bytes.length) {
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
break;
}
const byte2 = bytes[i++];
if ((byte2 & 0xC0) !== 0x80) {
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
i--;
continue;
}
result.push(String.fromCharCode(
((byte1 & 0x1F) << 6) | (byte2 & 0x3F)
));
} else if ((byte1 & 0xF0) === 0xE0) {
// 3字节字符1110xxxx 10xxxxxx 10xxxxxx
if (i + 1 >= bytes.length) {
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
break;
}
const byte2 = bytes[i++];
const byte3 = bytes[i++];
if ((byte2 & 0xC0) !== 0x80 || (byte3 & 0xC0) !== 0x80) {
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
i -= 2;
continue;
}
result.push(String.fromCharCode(
((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F)
));
} else if ((byte1 & 0xF8) === 0xF0) {
// 4字节字符11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
if (i + 2 >= bytes.length) {
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
break;
}
const byte2 = bytes[i++];
const byte3 = bytes[i++];
const byte4 = bytes[i++];
if ((byte2 & 0xC0) !== 0x80 || (byte3 & 0xC0) !== 0x80 || (byte4 & 0xC0) !== 0x80) {
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
i -= 3;
continue;
}
// 计算码点并转换为代理对
const codePoint = ((byte1 & 0x07) << 18) | ((byte2 & 0x3F) << 12) |
((byte3 & 0x3F) << 6) | (byte4 & 0x3F);
if (codePoint > 0x10FFFF) {
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
continue;
}
const surrogate = codePoint - 0x10000;
result.push(
String.fromCharCode(0xD800 + (surrogate >> 10)),
String.fromCharCode(0xDC00 + (surrogate & 0x3FF))
);
} else {
// 无效字节
if (this.fatal) throw new TypeError('无效的 UTF-8 序列');
result.push('\uFFFD');
}
}
return result.join('');
}
/**
* 解码 ASCII 数据
*
* @param bytes - 字节数组
* @returns 解码后的字符串
*/
private decodeASCII(bytes: Uint8Array): string {
const result: string[] = [];
for (let i = 0; i < bytes.length; i++) {
result.push(String.fromCharCode(bytes[i] & 0x7F));
}
return result.join('');
}
/**
* 解码 UTF-16LE 数据
*
* @param bytes - 字节数组
* @returns 解码后的字符串
*/
private decodeUTF16LE(bytes: Uint8Array): string {
const result: string[] = [];
// 跳过 BOM如果存在
let i = 0;
if (!this.ignoreBOM && bytes.length >= 2 &&
bytes[0] === 0xFF && bytes[1] === 0xFE) {
i = 2;
}
for (; i + 1 < bytes.length; i += 2) {
const codeUnit = bytes[i] | (bytes[i + 1] << 8);
result.push(String.fromCharCode(codeUnit));
}
return result.join('');
}
}
/**
* 安装 TextDecoder polyfill
*
* 如果当前环境不支持 TextDecoder则安装 polyfill
*
* @returns 是否安装了 polyfill
*/
export function installTextDecoderPolyfill(): boolean {
if (typeof globalThis.TextDecoder === 'undefined') {
(globalThis as any).TextDecoder = TextDecoderPolyfill;
console.log('[Polyfill] TextDecoder 已安装');
return true;
}
return false;
}
/**
* 检查 TextDecoder 是否可用(原生或 polyfill
*
* @returns 是否可用
*/
export function isTextDecoderAvailable(): boolean {
return typeof globalThis.TextDecoder !== 'undefined';
}
export { TextDecoderPolyfill };

View File

@@ -0,0 +1,167 @@
/**
* TextEncoder polyfill
*
* 用于不原生支持 TextEncoder 的平台(如微信小游戏 iOS 环境)
*
* 支持 UTF-8 编码,包含:
* - ASCII 字符1字节输出
* - 扩展 Unicode2-4字节输出
* - BMP 外字符的代理对处理
*/
class TextEncoderPolyfill {
/**
* 编码格式(始终为 'utf-8'
*/
readonly encoding: string = 'utf-8';
/**
* 将字符串编码为 UTF-8 字节数组
*
* @param input - 要编码的字符串
* @returns UTF-8 编码的字节数组
*/
encode(input: string = ''): Uint8Array {
const bytes: number[] = [];
for (let i = 0; i < input.length; i++) {
let codePoint = input.charCodeAt(i);
// 处理代理对BMP 外的字符)
if (codePoint >= 0xD800 && codePoint <= 0xDBFF) {
// 高代理项
if (i + 1 < input.length) {
const next = input.charCodeAt(i + 1);
if (next >= 0xDC00 && next <= 0xDFFF) {
// 低代理项 - 组合成完整码点
codePoint = 0x10000 + ((codePoint - 0xD800) << 10) + (next - 0xDC00);
i++; // 跳过低代理项
}
}
} else if (codePoint >= 0xDC00 && codePoint <= 0xDFFF) {
// 孤立的低代理项 - 替换为替换字符
codePoint = 0xFFFD;
}
if (codePoint < 0x80) {
// 1字节字符ASCII
bytes.push(codePoint);
} else if (codePoint < 0x800) {
// 2字节字符
bytes.push(0xC0 | (codePoint >> 6));
bytes.push(0x80 | (codePoint & 0x3F));
} else if (codePoint < 0x10000) {
// 3字节字符
bytes.push(0xE0 | (codePoint >> 12));
bytes.push(0x80 | ((codePoint >> 6) & 0x3F));
bytes.push(0x80 | (codePoint & 0x3F));
} else if (codePoint <= 0x10FFFF) {
// 4字节字符
bytes.push(0xF0 | (codePoint >> 18));
bytes.push(0x80 | ((codePoint >> 12) & 0x3F));
bytes.push(0x80 | ((codePoint >> 6) & 0x3F));
bytes.push(0x80 | (codePoint & 0x3F));
} else {
// 无效码点 - 使用替换字符
bytes.push(0xEF, 0xBF, 0xBD); // U+FFFD 的 UTF-8 编码
}
}
return new Uint8Array(bytes);
}
/**
* 将字符串编码到目标缓冲区
*
* 尽可能多地将源字符串编码到目标缓冲区中
*
* @param source - 要编码的字符串
* @param destination - 目标缓冲区
* @returns 包含已读取字符数和已写入字节数的对象
*/
encodeInto(source: string, destination: Uint8Array): TextEncoderEncodeIntoResult {
let read = 0;
let written = 0;
for (let i = 0; i < source.length; i++) {
let codePoint = source.charCodeAt(i);
let bytesNeeded: number;
// 处理代理对
if (codePoint >= 0xD800 && codePoint <= 0xDBFF && i + 1 < source.length) {
const next = source.charCodeAt(i + 1);
if (next >= 0xDC00 && next <= 0xDFFF) {
codePoint = 0x10000 + ((codePoint - 0xD800) << 10) + (next - 0xDC00);
}
}
// 计算所需字节数
if (codePoint < 0x80) {
bytesNeeded = 1;
} else if (codePoint < 0x800) {
bytesNeeded = 2;
} else if (codePoint < 0x10000) {
bytesNeeded = 3;
} else {
bytesNeeded = 4;
}
// 检查是否有足够空间
if (written + bytesNeeded > destination.length) {
break;
}
// 写入字节
if (codePoint < 0x80) {
destination[written++] = codePoint;
} else if (codePoint < 0x800) {
destination[written++] = 0xC0 | (codePoint >> 6);
destination[written++] = 0x80 | (codePoint & 0x3F);
} else if (codePoint < 0x10000) {
destination[written++] = 0xE0 | (codePoint >> 12);
destination[written++] = 0x80 | ((codePoint >> 6) & 0x3F);
destination[written++] = 0x80 | (codePoint & 0x3F);
} else {
destination[written++] = 0xF0 | (codePoint >> 18);
destination[written++] = 0x80 | ((codePoint >> 12) & 0x3F);
destination[written++] = 0x80 | ((codePoint >> 6) & 0x3F);
destination[written++] = 0x80 | (codePoint & 0x3F);
}
read++;
// 如果处理了代理对,跳过低代理项
if (codePoint >= 0x10000) {
read++;
i++;
}
}
return { read, written };
}
}
/**
* 安装 TextEncoder polyfill
*
* 如果当前环境不支持 TextEncoder则安装 polyfill
*
* @returns 是否安装了 polyfill
*/
export function installTextEncoderPolyfill(): boolean {
if (typeof globalThis.TextEncoder === 'undefined') {
(globalThis as any).TextEncoder = TextEncoderPolyfill;
console.log('[Polyfill] TextEncoder 已安装');
return true;
}
return false;
}
/**
* 检查 TextEncoder 是否可用(原生或 polyfill
*
* @returns 是否可用
*/
export function isTextEncoderAvailable(): boolean {
return typeof globalThis.TextEncoder !== 'undefined';
}
export { TextEncoderPolyfill };

View File

@@ -0,0 +1,58 @@
/**
* 平台 polyfills
*
* 提供跨平台兼容性支持,用于填补不同平台的 API 差异
*/
export {
TextDecoderPolyfill,
installTextDecoderPolyfill,
isTextDecoderAvailable
} from './TextDecoderPolyfill';
export {
TextEncoderPolyfill,
installTextEncoderPolyfill,
isTextEncoderAvailable
} from './TextEncoderPolyfill';
import { installTextDecoderPolyfill } from './TextDecoderPolyfill';
import { installTextEncoderPolyfill } from './TextEncoderPolyfill';
/**
* 安装当前平台所需的所有 polyfills
*
* @returns 已安装的 polyfill 列表
*/
export function installAllPolyfills(): { installed: string[] } {
const installed: string[] = [];
if (installTextDecoderPolyfill()) {
installed.push('TextDecoder');
}
if (installTextEncoderPolyfill()) {
installed.push('TextEncoder');
}
return { installed };
}
/**
* 检查当前平台需要哪些 polyfills
*
* @returns 需要的 polyfill 名称列表
*/
export function getRequiredPolyfills(): string[] {
const required: string[] = [];
if (typeof globalThis.TextDecoder === 'undefined') {
required.push('TextDecoder');
}
if (typeof globalThis.TextEncoder === 'undefined') {
required.push('TextEncoder');
}
return required;
}

View File

@@ -0,0 +1,240 @@
/**
* WASM 库平台适配层
*
* 提供统一的 WASM 库加载接口,屏蔽不同平台的差异
*
* 支持的平台:
* - Web 浏览器(标准 WebAssembly API
* - 微信小游戏WXWebAssembly
* - 字节跳动小游戏
* - 支付宝小游戏
* - 百度小游戏
*/
/**
* 平台类型枚举
*/
export enum PlatformType {
/** Web 浏览器 */
Web = 'web',
/** 微信小游戏 */
WeChatMiniGame = 'wechat-minigame',
/** 字节跳动小游戏 */
ByteDanceMiniGame = 'bytedance-minigame',
/** 支付宝小游戏 */
AlipayMiniGame = 'alipay-minigame',
/** 百度小游戏 */
BaiduMiniGame = 'baidu-minigame',
/** Node.js */
NodeJS = 'nodejs',
/** 未知平台 */
Unknown = 'unknown'
}
/**
* WASM 库加载配置
*
* @example
* ```typescript
* const config: WasmLibraryConfig = {
* name: 'Rapier2D',
* web: {
* useCompat: true, // Web 使用 compat 版本
* },
* minigame: {
* wasmPath: 'wasm/rapier2d_bg.wasm',
* needsTextDecoderPolyfill: true,
* }
* };
* ```
*/
export interface WasmLibraryConfig {
/**
* 库名称(用于日志和错误提示)
*/
name: string;
/**
* Web 平台配置
*/
web?: {
/**
* 使用 -compat 版本WASM 以 base64 嵌入 JS
*
* 优点:无需额外配置,开箱即用
* 缺点:包体积较大,首次加载慢
*/
useCompat?: boolean;
/**
* 模块路径(非 compat 版本时使用)
*/
modulePath?: string;
/**
* WASM 文件路径(非 compat 版本时使用)
*/
wasmPath?: string;
};
/**
* 小游戏平台配置
*/
minigame?: {
/**
* WASM 文件路径(相对于小游戏根目录)
*/
wasmPath: string;
/**
* JS glue 文件路径(可选)
*/
gluePath?: string;
/**
* 是否需要 TextDecoder polyfill
*
* iOS 微信小游戏通常需要此 polyfill
*/
needsTextDecoderPolyfill?: boolean;
/**
* 是否需要 TextEncoder polyfill
*
* iOS 微信小游戏通常需要此 polyfill
*/
needsTextEncoderPolyfill?: boolean;
};
/**
* 自定义初始化函数
*
* 用于库特定的初始化逻辑
*
* @param wasmInstance - WASM 实例
* @returns 初始化后的模块
*/
customInit?: (wasmInstance: any) => Promise<any>;
}
/**
* 平台信息
* Platform information
*/
export interface PlatformInfo {
/** 平台类型 | Platform type */
type: PlatformType;
/** 是否支持 WebAssembly | Supports WebAssembly */
supportsWasm: boolean;
/** 是否支持 SharedArrayBuffer | Supports SharedArrayBuffer */
supportsSharedArrayBuffer: boolean;
/** 需要安装的 polyfills 列表 | Required polyfills */
needsPolyfills: string[];
/**
* 是否在编辑器环境Tauri 桌面应用)
* Whether running in editor environment (Tauri desktop app)
*/
isEditor: boolean;
}
/**
* WASM 库加载器接口
*
* 每个 WASM 库需要实现此接口以支持跨平台加载
*
* @typeParam T - WASM 库模块类型
*
* @example
* ```typescript
* class Rapier2DLoader implements IWasmLibraryLoader<typeof RAPIER> {
* async load(): Promise<typeof RAPIER> {
* const RAPIER = await import('@dimforge/rapier2d-compat');
* await RAPIER.init();
* return RAPIER;
* }
*
* isSupported(): boolean {
* return typeof WebAssembly !== 'undefined';
* }
*
* getPlatformInfo(): PlatformInfo {
* return {
* type: PlatformType.Web,
* supportsWasm: true,
* supportsSharedArrayBuffer: true,
* needsPolyfills: []
* };
* }
* }
* ```
*/
export interface IWasmLibraryLoader<T> {
/**
* 加载 WASM 库
*
* @returns 加载完成的库模块
* @throws 如果加载失败或平台不支持
*/
load(): Promise<T>;
/**
* 检查当前平台是否支持此库
*
* @returns 是否支持
*/
isSupported(): boolean;
/**
* 获取当前平台信息
*
* @returns 平台信息
*/
getPlatformInfo(): PlatformInfo;
/**
* 获取库配置
*
* @returns 库配置
*/
getConfig(): WasmLibraryConfig;
}
/**
* 平台特定 WASM 加载器接口
*
* 提供平台级别的 WASM 加载能力
*/
export interface IPlatformWasmLoader {
/**
* 平台类型
*/
readonly platformType: PlatformType;
/**
* 加载 WASM 模块
*
* @param wasmPath - WASM 文件路径
* @param imports - WASM 导入对象
* @returns WASM 实例
*/
loadWasmModule(
wasmPath: string,
imports?: WebAssembly.Imports
): Promise<WebAssembly.Instance>;
/**
* 检查是否支持 WASM
*
* @returns 是否支持
*/
isSupported(): boolean;
/**
* 安装必要的 polyfills
*/
installPolyfills(): void;
}

View File

@@ -0,0 +1,241 @@
/**
* WASM 库加载器工厂
*
* 提供自动平台检测和加载器创建功能
*
* @example
* ```typescript
* // 注册加载器
* WasmLibraryLoaderFactory.registerLoader(
* 'rapier2d',
* PlatformType.Web,
* () => new WebRapier2DLoader(config)
* );
*
* // 创建加载器(自动选择平台)
* const loader = WasmLibraryLoaderFactory.createLoader<typeof RAPIER>('rapier2d');
* const rapier = await loader.load();
* ```
*/
import { PlatformType, IWasmLibraryLoader } from './IWasmLibraryLoader';
/**
* 加载器创建函数类型
*/
type LoaderFactory<T> = () => IWasmLibraryLoader<T>;
/**
* 已注册的加载器映射
*
* 结构libraryName -> platformType -> loaderFactory
*/
const registeredLoaders = new Map<string, Map<PlatformType, LoaderFactory<any>>>();
/**
* 缓存的平台检测结果
*/
let detectedPlatform: PlatformType | null = null;
/**
* WASM 库加载器工厂
*/
export class WasmLibraryLoaderFactory {
/**
* 注册 WASM 库加载器
*
* @param libraryName - 库名称(如 'rapier2d'
* @param platform - 目标平台
* @param factory - 加载器工厂函数
*
* @example
* ```typescript
* WasmLibraryLoaderFactory.registerLoader(
* 'rapier2d',
* PlatformType.Web,
* () => new WebRapier2DLoader(config)
* );
* ```
*/
static registerLoader<T>(
libraryName: string,
platform: PlatformType,
factory: LoaderFactory<T>
): void {
if (!registeredLoaders.has(libraryName)) {
registeredLoaders.set(libraryName, new Map());
}
registeredLoaders.get(libraryName)!.set(platform, factory);
}
/**
* 检测当前运行平台
*
* 检测顺序:
* 1. 微信小游戏wx 全局对象)
* 2. 字节跳动小游戏tt 全局对象)
* 3. 支付宝小游戏my 全局对象)
* 4. 百度小游戏swan 全局对象)
* 5. Node.jsprocess 对象)
* 6. Web 浏览器window + document
*
* @returns 检测到的平台类型
*/
static detectPlatform(): PlatformType {
if (detectedPlatform !== null) {
return detectedPlatform;
}
// 微信小游戏
if (typeof (globalThis as any).wx !== 'undefined') {
const wx = (globalThis as any).wx;
if (wx.getSystemInfo && wx.createCanvas) {
detectedPlatform = PlatformType.WeChatMiniGame;
return detectedPlatform;
}
}
// 字节跳动小游戏
if (typeof (globalThis as any).tt !== 'undefined') {
const tt = (globalThis as any).tt;
if (tt.getSystemInfo) {
detectedPlatform = PlatformType.ByteDanceMiniGame;
return detectedPlatform;
}
}
// 支付宝小游戏
if (typeof (globalThis as any).my !== 'undefined') {
const my = (globalThis as any).my;
if (my.getSystemInfo) {
detectedPlatform = PlatformType.AlipayMiniGame;
return detectedPlatform;
}
}
// 百度小游戏
if (typeof (globalThis as any).swan !== 'undefined') {
const swan = (globalThis as any).swan;
if (swan.getSystemInfo) {
detectedPlatform = PlatformType.BaiduMiniGame;
return detectedPlatform;
}
}
// Node.js
if (typeof process !== 'undefined' && process.versions?.node) {
detectedPlatform = PlatformType.NodeJS;
return detectedPlatform;
}
// Web 浏览器
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
detectedPlatform = PlatformType.Web;
return detectedPlatform;
}
detectedPlatform = PlatformType.Unknown;
return detectedPlatform;
}
/**
* 创建 WASM 库加载器
*
* 自动检测平台并选择对应的加载器
*
* @param libraryName - 库名称
* @returns 对应平台的加载器实例
* @throws 如果库未注册或平台不支持
*
* @example
* ```typescript
* const loader = WasmLibraryLoaderFactory.createLoader<typeof RAPIER>('rapier2d');
* const rapier = await loader.load();
* ```
*/
static createLoader<T>(libraryName: string): IWasmLibraryLoader<T> {
const platform = this.detectPlatform();
const libraryLoaders = registeredLoaders.get(libraryName);
if (!libraryLoaders) {
throw new Error(`[WasmLibraryLoaderFactory] 未注册的库: ${libraryName}`);
}
const factory = libraryLoaders.get(platform);
if (!factory) {
// 尝试使用 Web 加载器作为降级方案
const webFactory = libraryLoaders.get(PlatformType.Web);
if (webFactory && platform !== PlatformType.Unknown) {
console.warn(
`[WasmLibraryLoaderFactory] 平台 ${platform} 没有专用加载器,使用 Web 加载器作为降级方案`
);
return webFactory() as IWasmLibraryLoader<T>;
}
throw new Error(
`[WasmLibraryLoaderFactory] 库 "${libraryName}" 不支持平台: ${platform}`
);
}
return factory() as IWasmLibraryLoader<T>;
}
/**
* 检查指定库是否支持当前平台
*
* @param libraryName - 库名称
* @returns 是否支持
*/
static isLibrarySupported(libraryName: string): boolean {
const platform = this.detectPlatform();
const libraryLoaders = registeredLoaders.get(libraryName);
if (!libraryLoaders) {
return false;
}
return libraryLoaders.has(platform) || libraryLoaders.has(PlatformType.Web);
}
/**
* 获取库支持的所有平台
*
* @param libraryName - 库名称
* @returns 支持的平台列表
*/
static getSupportedPlatforms(libraryName: string): PlatformType[] {
const libraryLoaders = registeredLoaders.get(libraryName);
if (!libraryLoaders) {
return [];
}
return Array.from(libraryLoaders.keys());
}
/**
* 获取所有已注册的库名称
*
* @returns 库名称列表
*/
static getRegisteredLibraries(): string[] {
return Array.from(registeredLoaders.keys());
}
/**
* 清除平台检测缓存
*
* 主要用于测试
*/
static clearPlatformCache(): void {
detectedPlatform = null;
}
/**
* 清除所有已注册的加载器
*
* 主要用于测试
*/
static clearAllLoaders(): void {
registeredLoaders.clear();
}
}

View File

@@ -0,0 +1,16 @@
/**
* WASM 库加载器
*
* 提供跨平台的 WASM 库加载支持
*/
export { PlatformType } from './IWasmLibraryLoader';
export type {
WasmLibraryConfig,
PlatformInfo,
IWasmLibraryLoader,
IPlatformWasmLoader
} from './IWasmLibraryLoader';
export { WasmLibraryLoaderFactory } from './WasmLibraryLoaderFactory';

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM"],
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"strictNullChecks": true,
"noImplicitAny": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"composite": true,
"incremental": true,
"tsBuildInfoFile": "./dist/.tsbuildinfo"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}