Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

28.9 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    adapter.ts
 * @brief   The mini-game platform adapter family.
 *
 * ONE implementation of `PlatformAdapter` shared by every mini-game vendor. It
 * reads `profile.global` for the shared capabilities (canvas, fs, fetch, image,
 * input, storage, subpackage, memory-warning, DPR, language) and delegates the
 * genuine per-vendor divergences (WASM, audio, video, sockets) to the profile.
 *
 * Adding a vendor = one `MiniGameProfile`, not a parallel adapter.
 */

import type {
    PlatformAdapter,
    PlatformRequestOptions,
    PlatformResponse,
    WasmInstantiateResult,
    InputEventCallbacks,
    ImageLoadResult,
    PlatformCanvas,
    PlatformImage,
    PlatformSocket,
    PlatformSocketOptions,
    PlatformRewardedAd,
    PlatformRewardedAdResult,
    PlatformInterstitialAd,
    PlatformShareOptions,
    PlatformPaymentRequest,
    PlatformScreenRecorder,
} from '../types';
import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';
import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';
import { log } from '../../util/logger';
import type {
    MiniGameGlobal, MiniGameProfile, MiniGameCanvas, MiniGameFileSystemManager, MiniGameTouchEvent,
    MiniGameOpenDataContext,
} from './api';
import { createPrimaryPointer } from '../primaryPointer';
import { mgReadFile, mgReadFileSync, mgReadTextFileSync, mgFileExistsSync } from './fs';
import { cacheEntryName } from '../cacheEntryName';
import { mgLoadImagePixels } from './image';
import { mgFetch } from './fetch';
import { MiniGameAudioBackend } from '../../audio/MiniGameAudioBackend';
import { MiniGameSocket } from '../../net/MiniGameSocket';
import { WasmVideoBackend } from '../../video/WasmVideoBackend';
import { createMiniGameRecorder } from './recorder';
import { MiniGameDevice } from '../../device/minigame';

export class MiniGamePlatformAdapter implements PlatformAdapter {
    private device_: MiniGameDevice | null = null;
    device(): MiniGameDevice { return this.device_ ??= new MiniGameDevice(this.g_); }
    readonly name: PlatformAdapter['name'];
    /** Every vendor built on this adapter answers `isMiniGame()` — no name list. */
    readonly family = 'minigame' as const;

    private readonly profile_: MiniGameProfile;
    private readonly g_: MiniGameGlobal;
    private fs_: MiniGameFileSystemManager | null = null;
    private inputCleanup_: (() => void) | null = null;
    private pixelRatio_: number | null = null;
    private openDataCtx_: MiniGameOpenDataContext | null = null;
    private openDataResolved_ = false;
    private recorder_: PlatformScreenRecorder | null | undefined;
    private cacheWriteId_ = 0;

    constructor(profile: MiniGameProfile) {
        this.profile_ = profile;
        this.g_ = profile.global;
        this.name = profile.id;
    }

    /**
     * The host global, for the few capabilities only a mini-game has — the
     * loading indicator a boot reports through, which exists because the display
     * canvas is the GL surface and nothing 2D can be drawn over it.
     *
     * @internal Read-only: the adapter stays the one caller of what it abstracts.
     */
    get host(): MiniGameGlobal {
        return this.g_;
    }

    private fs(): MiniGameFileSystemManager {
        if (!this.fs_) this.fs_ = this.g_.getFileSystemManager();
        return this.fs_;
    }

    async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {
        return mgFetch(this.g_, url, options);
    }

    async readFile(path: string): Promise<ArrayBuffer> {
        return mgReadFileSync(this.fs(), path, this.profile_.hostLabel);
    }

    async readTextFile(path: string): Promise<string> {
        return mgReadTextFileSync(this.fs(), path, this.profile_.hostLabel);
    }

    async fileExists(path: string): Promise<boolean> {
        return mgFileExistsSync(this.fs(), path);
    }

    /** Hot update's content cache, flat under the host's user data directory and
     *  named as on every other platform. */
    async readCacheFile(key: string): Promise<ArrayBuffer | null> {
        const dir = this.g_.env?.USER_DATA_PATH;
        if (!dir) return null;
        try {
            return await mgReadFile(this.fs(), `${dir}/${cacheEntryName(key)}`, this.profile_.hostLabel);
        } catch {
            return null;
        }
    }

    async writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {
        const dir = this.g_.env?.USER_DATA_PATH;
        if (!dir) throw new Error(`${this.profile_.hostLabel} names no user data directory`);
        const file = `${dir}/${cacheEntryName(key)}`;
        const fs = this.fs();
        const temp = fs.rename ? `${file}.${++this.cacheWriteId_}.tmp` : file;
        await new Promise<void>((resolve, reject) => fs.writeFile({
            filePath: temp, data: bytes,
            success: () => resolve(),
            fail: (err) => reject(new Error(err.errMsg)),
        }));
        if (fs.rename) {
            try {
                await new Promise<void>((resolve, reject) => fs.rename!({ oldPath: temp, newPath: file,
                    success: resolve, fail: err => reject(new Error(err.errMsg)) }));
            } catch (err) {
                fs.unlink?.({ filePath: temp });
                throw err;
            }
        }
    }

    canManageCache(): boolean {
        const fs = this.fs();
        return Boolean(this.g_.env?.USER_DATA_PATH && fs.readdir && fs.stat && fs.unlink && fs.rename);
    }

    hasCacheStorage(): boolean { return Boolean(this.g_.env?.USER_DATA_PATH); }

    async listCacheFiles(): Promise<{ name: string; size: number; lastAccess: number }[]> {
        if (!this.canManageCache()) throw Error('cache management unavailable');
        const fs = this.fs();
        const dir = this.g_.env!.USER_DATA_PATH!;
        const names = await new Promise<string[]>((resolve, reject) => fs.readdir!({ dirPath: dir,
            success: r => resolve(r.files), fail: e => reject(new Error(e.errMsg)) }));
        const result: { name: string; size: number; lastAccess: number }[] = [];
        for (const name of names.filter(n => /^[0-9a-f]{16}(?:\.\d+\.tmp)?$/.test(n))) {
            const stats = await new Promise<{ size: number; lastAccessedTime: number; isFile(): boolean }>((resolve, reject) =>
                fs.stat!({ path: `${dir}/${name}`, recursive: false,
                    success: r => resolve(r.stats), fail: e => reject(new Error(e.errMsg)) }));
            if (stats.isFile()) result.push({ name, size: stats.size, lastAccess: stats.lastAccessedTime * 1000 });
        }
        return result;
    }

    async removeCacheFile(name: string): Promise<void> {
        if (!this.canManageCache() || !/^[0-9a-f]{16}$/.test(name)) throw Error('invalid cache entry or unsupported host');
        await new Promise<void>((resolve, reject) => this.fs().unlink!({
            filePath: `${this.g_.env!.USER_DATA_PATH}/${name}`, success: resolve,
            fail: e => reject(new Error(e.errMsg)),
        }));
    }

    async loadImagePixels(path: string): Promise<ImageLoadResult> {
        return mgLoadImagePixels(this.g_, this.cachedFileOf_(path) ?? path);
    }

    /** Where hot update stored @p url's bytes, when it did: an image drawn from the
     *  CDN url instead goes blank the first launch without a network. */
    private cachedFileOf_(url: string): string | null {
        const dir = this.g_.env?.USER_DATA_PATH;
        if (!dir || !/^https?:\/\//i.test(url)) return null;
        const file = `${dir}/${cacheEntryName(url)}`;
        return mgFileExistsSync(this.fs(), file) ? file : null;
    }

    async instantiateWasm(
        pathOrBuffer: string | ArrayBuffer,
        imports: WebAssembly.Imports,
    ): Promise<WasmInstantiateResult> {
        if (this.profile_.instantiateWasm) return this.profile_.instantiateWasm(pathOrBuffer, imports);
        // Family default: standard WebAssembly over the packaged filesystem. A
        // path is read through the host fs first — mini-game packages ship the
        // binary as a file, and there is no `fetch` to stream it from.
        const bytes = typeof pathOrBuffer === 'string' ? await this.readFile(pathOrBuffer) : pathOrBuffer;
        return WebAssembly.instantiate(bytes, imports);
    }

    createImage(): PlatformImage {
        // MiniGameImage is structurally assignable to PlatformImage (crossOrigin is
        // optional, its handlers fit the neutral optional-arg shape) — no cast.
        return this.g_.createImage();
    }

    /** Download an on-demand subpackage so its files become readable. */
    loadSubpackage(name: string): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            const load = this.g_.loadSubpackage;
            if (!load) {
                resolve();
                return;
            }
            load.call(this.g_, {
                name,
                success: () => resolve(),
                fail: (err: unknown) =>
                    reject(new Error(`loadSubpackage("${name}") failed: ${JSON.stringify(err)}`)),
                complete: () => {},
            });
        });
    }

    /** One rewarded ad over the host's RewardedVideoAd; null when this vendor
     *  has no ad API (the services layer substitutes its mock or fails loud). */
    createRewardedAd(adUnitId: string): PlatformRewardedAd | null {
        const create = this.g_.createRewardedVideoAd;
        if (!create) return null;
        const ad = create.call(this.g_, { adUnitId });
        return {
            preload: () => ad.load(),
            show(): Promise<PlatformRewardedAdResult> {
                let settle!: (r: PlatformRewardedAdResult) => void;
                const onClose = (res?: { isEnded: boolean }): void => {
                    ad.offClose(onClose);
                    // An absent record is a host that granted the reward without
                    // saying so (documented behavior on older runtimes) — only an
                    // explicit isEnded:false is an abandoned video.
                    settle({ completed: res?.isEnded !== false });
                };
                const closed = new Promise<PlatformRewardedAdResult>((r) => { settle = r; });
                ad.onClose(onClose);
                // The host's documented dance: show() rejects when no fill is
                // loaded; one load()+show() retry is the remedy, and a second
                // failure is a real "no ad right now" the caller must hear.
                return ad.show()
                    .catch(() => ad.load().then(() => ad.show()))
                    .then(() => closed, (e) => { ad.offClose(onClose); throw e; });
            },
            // Rewarded ads are host singletons per unit — nothing to free.
            destroy: () => {},
        };
    }

    /** One interstitial over the host's InterstitialAd; null when absent. */
    createInterstitialAd(adUnitId: string): PlatformInterstitialAd | null {
        const create = this.g_.createInterstitialAd;
        if (!create) return null;
        const ad = create.call(this.g_, { adUnitId });
        return {
            preload: () => ad.load(),
            show(): Promise<void> {
                let settle!: () => void;
                const onClose = (): void => { ad.offClose(onClose); settle(); };
                const closed = new Promise<void>((r) => { settle = r; });
                ad.onClose(onClose);
                return ad.show()
                    .catch(() => ad.load().then(() => ad.show()))
                    .then(() => closed, (e) => { ad.offClose(onClose); throw e; });
            },
            destroy: () => ad.destroy(),
        };
    }

    /** Open the host's share sheet. A vendor without `shareAppMessage` no-ops:
     *  every shipped mini-game host has it, and "the sheet did not open" is not
     *  a state the caller can act on (no host reports share outcomes at all). */
    share(options: PlatformShareOptions): void {
        this.g_.shareAppMessage?.call(this.g_, options);
    }

    /** The host's foreground signal. A host without `offShow` cannot unsubscribe,
     *  and the returned function then does nothing. */
    onAppShow(callback: () => void): () => void {
        this.g_.onShow?.call(this.g_, callback);
        return () => { this.g_.offShow?.call(this.g_, callback); };
    }

    onAppHide(callback: () => void): () => void {
        this.g_.onHide?.call(this.g_, callback);
        return () => { this.g_.offHide?.call(this.g_, callback); };
    }

    /** Register the passive-share card provider (the host's own share menu). */
    onShareRequest(provide: () => PlatformShareOptions): void {
        this.g_.onShareAppMessage?.call(this.g_, provide);
    }

    /** The host hands out one recorder, so this does too. */
    screenRecorder(): PlatformScreenRecorder | null {
        if (this.recorder_ === undefined) {
            this.recorder_ = createMiniGameRecorder(this.g_, this.profile_.recordingLimits);
        }
        return this.recorder_;
    }

    /** This one class serves every vendor, so it defines `login` regardless —
     *  the honest answer is whether the host behind it has one. */
    canSignIn(): boolean {
        return this.g_.login !== undefined;
    }

    /**
     * Whether a purchase may happen on THIS device.
     *
     * Paying inside a mini-game is an Android-only permission: the call exists
     * on an iPhone and the platform refuses it. That is a rule, not a fault, so
     * it belongs in the capability rather than in an error a game discovers by
     * charging someone. Devtools counts — that is where a purchase flow is
     * built, against the host's sandbox.
     */
    canPay(): boolean {
        if (this.profile_.pay) return this.profile_.pay.can();
        if (!this.g_.requestMidasPayment) return false;
        const where = this.g_.getSystemInfoSync().platform;
        // Unknown means a host that did not say. Treated as allowed: refusing
        // on silence would disable purchase on any vendor whose system info we
        // have not met, and the host still gets the final word at call time.
        return where === undefined || where === 'android' || where === 'devtools';
    }

    /** Buy in-game currency. Rejects with the host's own reason: "the purchase
     *  failed" without a code cannot be told apart from the player changing
     *  their mind, and those need different UI. */
    requestPayment(request: PlatformPaymentRequest): Promise<void> {
        if (this.profile_.pay) return this.profile_.pay.request(request);
        const pay = this.g_.requestMidasPayment;
        if (!pay) return Promise.reject(new Error('this host sells nothing'));
        return new Promise<void>((resolve, reject) => {
            pay.call(this.g_, {
                mode: 'game',
                offerId: request.offerId,
                buyQuantity: request.quantity,
                zoneId: request.zoneId ?? '1',
                currencyType: 'CNY',
                // Named explicitly rather than left to the host's default: the
                // one platform this is allowed on is the one it must say.
                platform: 'android',
                ...(request.sandbox ? { env: 1 } : {}),
                success: () => resolve(),
                fail: (err) => {
                    const e = new Error(err?.errMsg ?? 'payment failed') as Error & { code?: number };
                    // Carried, not interpreted: the codes are the host's, they
                    // differ between vendors, and a mapping this layer invented
                    // would be a guess a game then branches on.
                    e.code = err?.errCode;
                    reject(e);
                },
            });
        });
    }

    /** Begin a sign-in, as a promise. Rejects with the host's own words: this
     *  is a network round trip and "it failed" without why is unactionable. */
    login(): Promise<string> {
        const begin = this.g_.login;
        if (!begin) return Promise.reject(new Error('this host has no sign-in'));
        return new Promise<string>((resolve, reject) => {
            begin.call(this.g_, {
                success: (res) => {
                    // A host that answers success with no code has not signed
                    // anyone in, whatever it says.
                    if (res?.code) resolve(res.code);
                    else reject(new Error('sign-in returned no code'));
                },
                fail: (err) => reject(new Error(`sign-in failed: ${JSON.stringify(err)}`)),
            });
        });
    }

    /** Whether the last sign-in is still current. The hosts answer by which
     *  callback they call, so this is where that becomes a boolean. */
    checkSession(): Promise<boolean> {
        const check = this.g_.checkSession;
        if (!check) return Promise.resolve(false);
        return new Promise<boolean>((resolve) => {
            check.call(this.g_, { success: () => resolve(true), fail: () => resolve(false) });
        });
    }

    /**
     * The open data context, resolved once and kept.
     *
     * `getOpenDataContext()` is documented as returning the same object every
     * time, but it is not free — and this is asked on the frame a leaderboard
     * opens, not at boot, because a host whose package declares no context
     * throws rather than answering null. Caching a THROW as "absent" is the
     * point: the second ask would throw again to no one's benefit.
     */
    private openData_(): MiniGameOpenDataContext | null {
        if (this.openDataResolved_) return this.openDataCtx_;
        this.openDataResolved_ = true;
        try {
            this.openDataCtx_ = this.g_.getOpenDataContext?.call(this.g_) ?? null;
        } catch {
            this.openDataCtx_ = null;
        }
        return this.openDataCtx_;
    }

    /** Send one message into the open data context. Absent context = no-op:
     *  the caller already asked `available` if it cared. */
    openDataPostMessage(message: Record<string, unknown>): void {
        this.openData_()?.postMessage(message);
    }

    /** The shared canvas, for the main domain to sample as a texture. The same
     *  honest cast {@link createCanvas} makes, for the same reason. */
    openDataCanvas(): PlatformCanvas | null {
        return (this.openData_()?.canvas as unknown as PlatformCanvas | undefined) ?? null;
    }

    /** Write this player's own rows to the host's cloud store. Whether there
     *  was a store is reported; whether the write landed is not — that failure
     *  (offline) is the one no host distinguishes for us. */
    setCloudKeyValues(entries: Readonly<Record<string, string>>): boolean {
        const set = this.g_.setUserCloudStorage;
        if (!set) return false;
        set.call(this.g_, {
            KVDataList: Object.entries(entries).map(([key, value]) => ({ key, value })),
        });
        return true;
    }

    onMemoryWarning(callback: () => void): () => void {
        const on = this.g_.onMemoryWarning;
        const off = this.g_.offMemoryWarning;
        if (!on) return () => {};
        const listener = () => callback();
        on.call(this.g_, listener);
        return () => off?.call(this.g_, listener);
    }

    /**
     * The host's two uncaught channels, each subscribed only if this base
     * library has it.
     *
     * A script error arrives as a STRING on WeChat rather than an Error, so the
     * stack is in the text and there is nothing to take a `.stack` off — which
     * is why the diagnostics layer tolerates non-Errors instead of assuming one.
     * `onUnhandledRejection` is newer than `onError`; a base without it loses
     * only the promise half.
     */
    onUnhandledError(callback: (error: unknown) => void): () => void {
        const onError = this.g_.onError;
        const offError = this.g_.offError;
        const onRejection = this.g_.onUnhandledRejection;
        const offRejection = this.g_.offUnhandledRejection;
        const errorListener = (e: string | { message?: string; stack?: string }): void => { callback(e); };
        const rejectionListener = (res: { reason?: unknown }): void => { callback(res?.reason ?? res); };
        if (onError) onError.call(this.g_, errorListener);
        if (onRejection) onRejection.call(this.g_, rejectionListener);
        return () => {
            if (onError) offError?.call(this.g_, errorListener);
            if (onRejection) offRejection?.call(this.g_, rejectionListener);
        };
    }

    createCanvas(width: number, height: number): PlatformCanvas {
        // One honest cast: MiniGameCanvas.getContext returns `unknown`, so it is not
        // structurally assignable to PlatformCanvas's typed 2D getContext.
        const canvas = this.g_.createCanvas() as unknown as PlatformCanvas;
        canvas.width = width;
        canvas.height = height;
        return canvas;
    }

    /**
     * The ON-SCREEN canvas, sized to the device viewport.
     *
     * Distinct from {@link createCanvas}, which makes offscreen 2D surfaces for
     * image decode and glyph rasterization: on every mini-game host the FIRST
     * `createCanvas()` of the process returns the display canvas, and the render
     * surface is the GL context taken from it. The runtime calls this once at
     * boot, before anything else touches createCanvas.
     */
    createScreenCanvas(): MiniGameCanvas {
        const canvas = this.g_.createCanvas();
        this.sizeScreenCanvas_(canvas, this.g_.getSystemInfoSync());
        // The window is not fixed — a rotation, a foldable, a host that opens in
        // the other orientation. Sized once, the canvas keeps the old space while
        // touches keep arriving in the window's, and taps stop landing at all.
        this.g_.onWindowResize?.((res) => this.sizeScreenCanvas_(canvas, res));
        return canvas;
    }

    /** Size the display canvas to a window measurement. Left at the host's own
     *  default when the measurement is incomplete — a 0×0 surface would be worse
     *  than the host's guess. */
    private sizeScreenCanvas_(
        canvas: MiniGameCanvas,
        size: { windowWidth?: number; windowHeight?: number },
    ): void {
        this.pixelRatio_ = null;
        const dpr = this.profile_.windowInPhysicalPixels ? 1 : this.devicePixelRatio();
        if (size.windowWidth) canvas.width = size.windowWidth * dpr;
        if (size.windowHeight) canvas.height = size.windowHeight * dpr;
    }

    now(): number {
        return Date.now();
    }

    bindInputEvents(callbacks: InputEventCallbacks, _target?: unknown): void {
        if (this.inputCleanup_) {
            this.inputCleanup_();
            this.inputCleanup_ = null;
        }

        const g = this.g_;

        const heldKeys = new Set<string>();
        const onKeyDown = (res: { code: string }) => {
            heldKeys.add(res.code);
            callbacks.onKeyDown(res.code);
        };
        const onKeyUp = (res: { code: string }) => {
            if (heldKeys.delete(res.code)) callbacks.onKeyUp(res.code);
        };

        const hasKeyboard = typeof g.onKeyDown === 'function';
        if (hasKeyboard) {
            g.onKeyDown?.(onKeyDown);
            g.onKeyUp?.(onKeyUp);
        }

        const pointer = createPrimaryPointer(callbacks);
        const heldTouches = new Set<number>();
        const cancelInput = () => {
            for (const code of heldKeys) callbacks.onKeyUp(code);
            heldKeys.clear();
            for (const id of heldTouches) pointer.cancel(id);
            heldTouches.clear();
            callbacks.onInputCancel?.();
        };
        // A pointer is read in logical pixels and scaled by pixelRatio to reach the
        // canvas; a host that reports touches in physical pixels would land every
        // tap pixelRatio times too far out, past the edge of the screen.
        const toLogical = this.profile_.windowInPhysicalPixels ? 1 / this.devicePixelRatio() : 1;

        const onTouchStart = (res: MiniGameTouchEvent) => {
            for (const touch of res.changedTouches) {
                heldTouches.add(touch.identifier);
                pointer.start(touch.identifier, touch.clientX * toLogical, touch.clientY * toLogical);
            }
        };
        const onTouchMove = (res: MiniGameTouchEvent) => {
            for (const touch of res.changedTouches) {
                if (heldTouches.has(touch.identifier)) pointer.move(touch.identifier, touch.clientX * toLogical, touch.clientY * toLogical);
            }
        };
        const onTouchEnd = (res: MiniGameTouchEvent) => {
            for (const touch of res.changedTouches) if (heldTouches.delete(touch.identifier)) pointer.end(touch.identifier);
        };
        const onTouchCancel = (res: MiniGameTouchEvent) => {
            for (const touch of res.changedTouches) if (heldTouches.delete(touch.identifier)) pointer.cancel(touch.identifier);
        };

        g.onTouchStart(onTouchStart);
        g.onTouchMove(onTouchMove);
        g.onTouchEnd(onTouchEnd);
        g.onTouchCancel?.(onTouchCancel);
        g.onHide?.(cancelInput);

        this.inputCleanup_ = () => {
            if (hasKeyboard) {
                g.offKeyDown?.(onKeyDown);
                g.offKeyUp?.(onKeyUp);
            }
            g.offTouchStart(onTouchStart);
            g.offTouchMove(onTouchMove);
            g.offTouchEnd(onTouchEnd);
            g.offTouchCancel?.(onTouchCancel);
            g.offHide?.(cancelInput);
            cancelInput();
        };
    }

    unbindInputEvents(): void {
        if (this.inputCleanup_) {
            this.inputCleanup_();
            this.inputCleanup_ = null;
        }
    }

    createAudioBackend(): PlatformAudioBackend {
        return this.profile_.createAudioBackend?.() ?? new MiniGameAudioBackend(this.g_, this.profile_.hostLabel);
    }

    createVideoBackend(ctx: VideoBackendContext): PlatformVideoBackend {
        // The engine-owned wasm decoder is the family default on every vendor:
        // host video decoders are absent on desktop clients and unreliable on
        // phones (per-device staging, null frames, no playhead), so the
        // deterministic single path wins even where one exists.
        return this.profile_.createVideoBackend?.(ctx) ?? new WasmVideoBackend(ctx);
    }

    createSocket(options: PlatformSocketOptions): PlatformSocket {
        return this.profile_.createSocket?.(options) ?? new MiniGameSocket(options, this.g_);
    }

    /** The host returns `''` for both absent keys and stored empty strings.
     *  Only that ambiguous result needs the key list; normal reads stay direct. */
    getStorageItem(key: string): string | null {
        try {
            const value = this.g_.getStorageSync(key);
            if (typeof value !== 'string') return null;
            if (value !== '') return value;
            return this.g_.getStorageInfoSync?.().keys.includes(key) ? '' : null;
        } catch {
            return null;
        }
    }

    setStorageItem(key: string, value: string): void {
        try {
            this.g_.setStorageSync(key, value);
        } catch (e) {
            log.warn(this.profile_.id, 'setStorageSync failed', e);
        }
    }

    removeStorageItem(key: string): void {
        try {
            this.g_.removeStorageSync(key);
        } catch (e) {
            log.warn(this.profile_.id, 'removeStorageSync failed', e);
        }
    }

    /** Read once and again after a resize: the UI, the cameras and text ask every
     *  frame, and on vivo each read is a synchronous call across its bridge. */
    devicePixelRatio(): number {
        if (this.pixelRatio_ !== null) return this.pixelRatio_;
        try {
            this.pixelRatio_ = this.g_.getSystemInfoSync?.()?.pixelRatio ?? 1;
        } catch {
            this.pixelRatio_ = 1;
        }
        return this.pixelRatio_;
    }

    deviceName(): string {
        try {
            // WeChat appends the hardware id, as in 'iPhone 13<iPhone14,5>'.
            return (this.g_.getSystemInfoSync?.()?.model ?? '').replace(/<.*>$/, '').trim();
        } catch {
            return '';
        }
    }

    deviceQualityInfo(): { model?: string; memoryGB?: number } {
        try {
            const info = this.g_.getDeviceInfo?.() ?? this.g_.getSystemInfoSync?.();
            const memory = Number(info?.memorySize);
            return {
                model: info?.model?.replace(/<.*>$/, '').trim(),
                ...(Number.isFinite(memory) && memory > 0 ? { memoryGB: memory / 1024 } : {}),
            };
        } catch {
            return {};
        }
    }

    language(): string {
        try {
            // Hosts report 'zh_CN'-style tags; platformLanguage() normalizes underscores.
            return this.g_.getSystemInfoSync?.()?.language ?? 'en';
        } catch {
            return 'en';
        }
    }

    clearStorage(prefix: string): void {
        try {
            const { keys } = this.g_.getStorageInfoSync();
            for (const k of keys) {
                if (k.startsWith(prefix)) {
                    this.g_.removeStorageSync(k);
                }
            }
        } catch (e) {
            log.warn(this.profile_.id, 'clearStorage failed', e);
        }
    }
}