Files
cocos4/@types/pal/minigame.d.ts
T
llsansun 2157fd176d Multithreading (#322)
* worker pool

* opt

* backup

* worker and worker backend

* worker fallback

* opt

* opt

* remove meta

* opt

* worker export

* testcase fix

* worker js template

* worker pal

* worker opt

* test

* Replace error messages with error codes

* Package size reduction

* Package size reduction

* revert

* Restore editor asset .meta files to the base branch state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014HAtWwr4dy5azfpccweh1g

* bugfix

* Split into two features: Worker and Worker Pool

* worker option

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 16:35:14 +08:00

533 lines
18 KiB
TypeScript

declare module 'pal/minigame' {
export const minigame: IMiniGame;
export interface IMiniGame {
setPreferredFramesPerSecond(_targetFrameRate: number);
// platform related
wx?: WeChatAPI;
tt?: ByteDanceAPI;
ral?: RuntimeAPI;
// system
isDevTool: boolean;
isLandscape: boolean;
orientation: import('pal/screen-adapter/enum-type').Orientation;
/**
* Most mini game platforms have performance issues calling this interface, so the engine does caching internally.
* This interface is deprecated in WeChat mini games, please use 'getSystemSetting', 'getAppAuthorizeSetting','getSystemSetting',
* 'getDeviceInfo','getWindowInfo', 'getAppBaseInfo' instead.
*/
getSystemInfoSync(): SystemInfo;
onShow(callback: () => void): void;
offShow(callback: () => void): void;
onHide(callback: () => void): void;
offHide(callback: () => void): void;
onWindowResize?(callback: () => void): void;
/**
* This method returns the standardized SafeArea based on the screen coordinate system,
* which is not affected by the orientation of the screen.
* @returns {SafeArea} An interface displaying the data of safe area, including 'top', 'bottom', 'left', 'right', 'width' and 'height'.
*/
getSafeArea(): SafeArea;
triggerGC?(): void;
getBatteryInfoSync(): BatteryInfo;
exitMiniProgram? (): void;
// render
getSharedCanvas(): any;
getOpenDataContext(): any;
// worker
/**
* Create a worker thread from a packaged script path.
*
* IMPORTANT — this is optional and genuinely absent on some platforms:
* - Present: WeChat (`wx.createWorker`), ByteDance (`tt.createWorker`), Alipay
* (`my.createWorker`), Baidu (`swan.createWorker`, base library 1.6.1+), and the
* quick-game family (`qg.createWorker` on Xiaomi / Huawei 1117+ / OPPO / vivo).
* Each `pal/minigame/*.js` adapter starts with `cloneObject(minigame, <platformGlobal>)`,
* and `cloneObject` copies functions with `.bind(origin)` — so `createWorker` arrives on
* `minigame` for free, already bound to the right global. No per-platform adapter code
* is needed, and `pal/` itself must not be edited (it is regenerated from the
* `@cocos/engine-pal` package on postinstall).
* - Absent: Taobao mini-game has NO worker API at all (its API surface has no Worker
* category), and no `Worker` / `Blob` / `URL.createObjectURL` either — there is no way to
* get a real thread there. Callers must degrade to synchronous execution.
*
* Returns `undefined` (rather than throwing) when creation fails on Huawei quick game, so
* the result MUST be null-checked.
*
* Every platform caps concurrency at ONE worker except WeChat V2 (standard worker).
* Script paths must be relative (no leading "/") and end with ".js", and the file must be
* packaged under the workers directory declared in game.json / manifest.json / app.json.
*/
createWorker?: (scriptPath: string, options?: MinigameWorkerOptions) => MinigameWorker | undefined;
/**
* Platform environment info. On WeChat this carries `isSupportStandardWorker`, which gates
* the V2 standard worker (grey release; NOT supported in the WeChat devtools). Absent on
* platforms whose global has no `env`.
*/
env?: MinigameEnv;
// file system
getFileSystemManager(): FileSystemManager;
loadSubpackage? (option: LoadSubpackageOption): LoadSubpackageTask;
// input
onTouchStart: IEventManager<TouchEvent>;
onTouchMove: IEventManager<TouchEvent>;
onTouchEnd: IEventManager<TouchEvent>;
onTouchCancel: IEventManager<TouchEvent>;
// audio
createInnerAudioContext(): InnerAudioContext;
onAudioInterruptionBegin(callback: () => void): any;
offAudioInterruptionBegin(callback: () => void): any;
onAudioInterruptionEnd(callback: () => void): any;
offAudioInterruptionEnd(callback: () => void): any;
// font
loadFont(url: string): string;
// device
onAccelerometerChange(cb: AccelerometerChangeCallback);
offAccelerometerChange(cb?: AccelerometerChangeCallback);
startAccelerometer(obj: AccelerometerStartParameter);
stopAccelerometer(obj: AccelerometerStopParameter);
// New interfaces for base libraries 2.25.3 and above
getSystemSetting(): SystemSetting;
getAppAuthorizeSetting(): AppAuthorizeSetting,
getDeviceInfo(): DeviceInfo;
getWindowInfo(): WindowInfo;
getAppBaseInfo(): AppBaseInfo;
// interace for douyin live play feature
checkFeedSubscribeStatus(opt: subscribeOptions): void;
requestFeedSubscribe(opt: reqSubscribeOptions): void;
getLaunchOptionsSync(): LaunchOptions;
reportScene(opt: reportOption): void;
onFeedStatusChange(cb: (type: string) => void): void;
offFeedStatusChange(cb?: (type: string) => void): void;
storeFeedData(opt: storeFeedDataOptions): void;
getFeedData(opt: getFeedDataOptions): void;
setEnableDebug? (parm: DebugParameter): void;
notifyMiniProgramPlayableStatus? (parm: notiOptions): void;
}
interface WeChatAPI {
onKeyDown?: (cb: (res: KeyboardEventData) => void) => void;
onKeyUp?: (cb: (res: KeyboardEventData) => void) => void;
onMouseDown?: (cb: (res: MouseEventData) => void) => void;
onMouseMove?: (cb: (res: MouseEventData) => void) => void;
onMouseUp?: (cb: (res: MouseEventData) => void) => void;
onWheel?: (cb: (res: MouseWheelEventData) => void) => void;
}
export interface KeyboardEventData {
key: string;
code: string;
timeStamp: number;
}
export interface MouseEventData {
x: number;
y: number;
button: number;
timeStamp: number;
}
export interface MouseWheelEventData extends MouseEventData {
deltaX: number;
deltaY: number;
deltaZ: number;
}
interface ICANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC {
name: string,
enable: number,
}
interface ICANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT {
name: string,
alphabetic: number,
}
interface RuntimeAPI {
CANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC: ICANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC,
CANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT: ICANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT,
getFeaturePropertyInt(featureName: string): number;
setFeaturePropertyInt(featureName: string, value: number);
}
interface ByteDanceAPI {
getAudioContext?: () => AudioContext;
}
/**
* Options accepted by `minigame.createWorker`. Only WeChat defines any; other platforms ignore
* the second argument. Kept loose on purpose — the platform surface differs and grows.
*/
export interface MinigameWorkerOptions {
/**
* WeChat only, base library 2.13.0+. Uses the "experimental" worker implementation, which
* speeds up JS execution several times over on iOS. Requires pairing with
* `onProcessKilled`, because the system may reclaim the worker process at any time.
* This legacy option does not select the V2 standard Worker.
*/
useExperimentalWorker?: boolean;
[key: string]: any;
}
/**
* Platform environment info exposed as `minigame.env`.
*/
export interface MinigameEnv {
/**
* WeChat only. `true` when the runtime supports the V2 standard worker: multiple concurrent
* workers, `SharedArrayBuffer`, transfer lists in `postMessage`, `OffscreenCanvas`. Requires
* WeChat client >= 8.0.74 (Android) and base library >= 3.17.0, is in grey release, and is
* NOT supported in the WeChat devtools — so it must be checked at runtime, never assumed.
*/
isSupportStandardWorker?: boolean;
[key: string]: any;
}
/**
* The worker handle returned by `minigame.createWorker`. The API shape is remarkably consistent
* across WeChat / ByteDance / Alipay / Baidu / quick-game: all use `postMessage` + `onMessage`,
* and all expose the worker-side global as `worker` (NOT `self`).
*
* Differences that the engine's backend layer must absorb:
* - `onError` is missing on some platforms (Huawei quick game documents only
* create/postMessage/onMessage/terminate) — guard before calling.
* - `onProcessKilled` is WeChat-only (iOS experimental worker reclamation).
* - The transfer list (second `postMessage` argument) is honored ONLY by WeChat V2. Huawei quick
* game documents data transfer as structured clone with no transferable objects; passing a
* transfer list elsewhere may throw, so omit it unless the platform supports it.
*/
export interface MinigameWorker {
postMessage(message: any, transfer?: any[]): void;
onMessage(listener: (res: any) => void): void;
onError?: (listener: (err: any) => void) => void;
terminate(): void;
/** WeChat only: fired when the system reclaims the worker process. */
onProcessKilled?: (listener: (err: any) => void) => void;
}
export type AccelerometerIntervalMode = 'game' | 'ui' | 'normal';
export interface AccelerometerStartParameter {
interval: AccelerometerIntervalMode,
success?: () => void,
fail?: (err: any) => void,
complete?: () => void,
}
export interface AccelerometerStopParameter {
success?: () => void,
fail?: (err: any) => void,
complete?: () => void,
}
export interface SystemInfo {
abi: string;
deviceAbi: string;
brand: string;
model: string;
pixelRatio: number;
screenWidth: number;
screenHeight: number;
windowWidth: number;
windowHeight: number;
statusBarHeight: number;
language: string;
version: string;
system: string;
platform: string;
fontSizeSetting: number;
enableDebug: boolean;
SDKVersion: string;
benchmarkLevel: number;
albumAuthorized: boolean;
cameraAuthorized: boolean;
locationAuthorized: boolean;
microphoneAuthorized: boolean;
notificationAuthorized: boolean;
notificationAlertAuthorized: boolean;
notificationBadgeAuthorized: boolean;
notificationSoundAuthorized: boolean;
phoneCalendarAuthorized: string;
host: HostInfo;
bluetoothAuthorized: string;
bluetoothEnabled: boolean;
locationEnabled: boolean;
wifiEnabled: boolean;
safeArea: SafeArea;
locationReducedAccuracy: boolean;
theme: string;
cpuType: string;
memorySize: string;
screenTop: number;
mode: string;
fontSizeScaleFactor: number;
deviceOrientation?: 'portrait' | 'landscape';
}
export interface SystemSetting {
bluetoothEnabled: boolean;
locationEnabled: boolean;
wifiEnabled: boolean;
deviceOrientation?: 'portrait' | 'landscape';
}
export interface AppAuthorizeSetting {
albumAuthorized: string | undefined;
bluetoothAuthorized: string | undefined;
cameraAuthorized: string | undefined;
locationAuthorized: string | undefined;
locationReducedAccuracy: boolean | undefined;
microphoneAuthorized: string | undefined;
notificationAuthorized: string | undefined;
notificationAlertAuthorized: string | undefined;
notificationBadgeAuthorized: string | undefined;
notificationSoundAuthorized: string | undefined;
phoneCalendarAuthorized: string | undefined;
}
export interface HostInfo {
appId: string;
}
export interface AppBaseInfo {
SDKVersion: string;
enableDebug: boolean;
host: HostInfo;
language: string;
version: string;
theme: string;
fontSizeScaleFactor: number;
fontSizeSetting: number;
mode: string;
}
export interface DeviceInfo {
abi: string;
deviceAbi: string;
benchmarkLevel: number;
brand: string;
model: string;
system: string;
platform: string;
cpuType: string;
memorySize: string;
}
export interface WindowInfo {
pixelRatio: number;
screenWidth: number;
screenHeight: number;
windowWidth: number;
windowHeight: number;
statusBarHeight: number;
safeArea: SafeArea;
screenTop: number;
}
}
declare interface BatteryInfo {
level: number; // ranged from 1-100
isCharging: boolean;
}
type AccelerometerChangeCallback = (res: AccelerometerData) => void;
declare interface AccelerometerData {
x: number,
y: number,
z: number,
}
declare interface IEventManager<Event> {
(listener: (event: Event) => void): void;
}
declare class FileSystemManager {
access(obj: any);
accessSync(path: string): boolean;
appendFile(obj: any);
appendFileSync(filePath: string, data: string|ArrayBuffer, encoding: string);
copyFile(obj: any);
copyFileSync(srcPath: string, destPath: string);
getFileInfo(obj: any);
getSavedFileList(obj: any);
mkdir(obj: any);
mkdirSync();
readdir(obj: any);
readdirSync();
readFile(obj: any);
readFileSync();
removeSavedFile(obj: any);
rename(obj: any);
renameSync();
rmdir(obj: any);
rmdirSync();
saveFile(obj: any);
saveFileSync();
stat(obj: any);
statSync();
unlink(obj: any);
unlinkSync();
unzip(obj: any);
writeFile(obj: any);
writeFileSync();
}
declare interface SafeArea {
left: number;
right: number;
top: number;
bottom: number;
width: number;
height: number;
}
declare class InnerAudioContext {
src: string;
startTime: number;
autoplay: boolean;
loop: boolean;
obeyMuteSwitch: boolean;
volume: number;
duration: number;
currentTime: number;
paused: boolean;
buffered: number;
destroy(): any;
offCanplay(callback: () => void): any;
offEnded(callback: () => void): any;
offError(callback: (err: any) => void): any;
offPause(callback: () => void): any;
offPlay(callback: () => void): any;
offSeeked(callback: () => void): any;
offSeeking(callback: () => void): any;
offStop(callback: () => void): any;
offTimeUpdate(callback: () => void): any;
offWaiting(callback: () => void): any;
onCanplay(callback: () => void): any;
onEnded(callback: () => void): any;
onError(callback: (err: any) => void): any;
onPause(callback: () => void): any;
onPlay(callback: () => void): any;
onSeeked(callback: () => void): any;
onSeeking(callback: () => void): any;
onStop(callback: () => void): any;
onTimeUpdate(callback: () => void): any;
onWaiting(callback: () => void): any;
pause(): any;
play(): any;
seek(position: number): any;
stop(): any;
}
interface LoadSubpackageOption {
name: string;
fail?: (...args: unknown[]) => void;
success?: (...args: unknown[]) => void;
complete?: (...args: unknown[]) => void;
}
interface LoadSubpackageTask {
onProgressUpdate(
listener: LoadSubpackageTaskOnProgressUpdateCallback
): void;
}
type LoadSubpackageTaskOnProgressUpdateCallback = (result: LoadSubpackageTaskOnProgressUpdateListenerResult) => void;
interface LoadSubpackageTaskOnProgressUpdateListenerResult {
progress: number;
totalBytesExpectedToWrite: number;
totalBytesWritten: number;
}
interface subscribeOptions {
scene: number;
allScene: boolean;
type: string;
success?: (successObj: commonSuccessObj) => void,
fail?: (failObj: commonFailObj) => void,
complete?: () => void,
}
interface reqSubscribeOptions {
scene: number;
contentIDs: string[];
allScene: boolean;
type: string;
success?: (successObj: commonSuccessObj) => void,
fail?: (failObj: commonFailObj) => void,
complete?: () => void,
}
interface LaunchOptions {
query: LaunchOptionQuery;
scene: string;
extra: LaunchOptionExtra;
}
interface LaunchOptionExtra {
aid: object;
appId: string;
mpVersion: string;
launch_from: string;
}
interface LaunchOptionQuery {
ad_params: any;
feed_game_scene: any;
feed_game_channel: any;
feed_game_content_id: any;
feed_game_extra: any;
}
interface reportOption {
costTime: number; //ms
sceneId: number;
dimension: object;
metric: object;
success?: (successObj: commonSuccessObj) => void,
fail?: (failObj: commonFailObj) => void,
complete?: () => void,
}
interface commonSuccessObj {
errMsg: string,
data: object,
}
interface commonFailObj {
errMsg: string,
}
interface storeFeedDataOptions {
scene: string;
extra: string;
status: number;
contentID: string;
leftValue: number;//ms
operator: string;
rightValue: number;//ms
success?: (successObj: {errMsg: string}) => void,
fail?: (failObj: commonFailObj) => void,
complete?: () => void,
}
interface getFeedDataOptions {
scene: string;
contentID: string;
success?: (successObj: {errMsg: string, extra: string, status: number}) => void,
fail?: (failObj: commonFailObj) => void,
complete?: () => void,
}
interface DebugParameter {
enableDebug: boolean,
success?: () => void,
fail?: (err: any) => void,
complete?: () => void,
}
interface notiOptions {
success?: () => void,
fail?: (err: any) => void,
complete?: () => void,
}