feat(platform-common): 添加WASM加载器和环境检测API

This commit is contained in:
yhh
2025-12-03 16:18:21 +08:00
parent 88af781d78
commit e6fb80d0be
8 changed files with 1025 additions and 0 deletions

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';