A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sdk): ads and sharing are engine services, not per-game glue
esengine942f4ff38bb3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffd67f975..3ce6a2487 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,24 @@ published separately; it ships inside the editor.## [Unreleased]+### Added++- **Ads and sharing are engine services now, not glue every game writes itself.**+ A rewarded video is four lines on the platform and a page of ceremony around+ them, and the ceremony is the part teams get wrong: `Ads.showRewarded(unitId)`+ pauses the game clock while the ad covers the screen (a revive must not cost+ the player their run), suspends the audio device without touching any volume+ the user set, restores both however the ad ends — including the error paths —+ and resolves with whether the reward was earned, folding in the hosts'+ load/show retry dance and the runtime that grants a reward without saying so.+ `Share.share(...)` and `Share.setShareCard(...)` cover both share surfaces+ (the game's own button, and the host's menu — asked at share time, so the card+ can carry a live room code). WeChat and Douyin are one family implementation;+ `Ads.available` is false where there is no ad system (web, native until a+ mediation provider is installed through the same door), and the editor's play+ mode installs a mock provider — so "watch an ad to revive" is a flow you can+ rehearse at your desk, real pauses included, without a device.+### Fixed- **Compressed textures are no longer upside down.** Every uncompressed image isdiff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex 7e669d7d6..55996b494 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -14,7 +14,7 @@* Everything is same-origin estella:// (host, sdk, bundle, wasm, assets),* sidestepping the custom-scheme cross-fetch ban.*/-import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets } from 'esengine';+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider } from 'esengine';import type { App, ESEngineModule, SceneData } from 'esengine';import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';import type { PlayOutbound, PlayInbound } from './engine/playProtocol';@@ -229,6 +229,11 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {setEditorMode(false);setPlayMode(true);+ // The editor's play realm has no ad host, but "watch an ad to revive" is a+ // flow a game has to be able to REHEARSE here — the mock keeps the real+ // pause/audio ceremony and just skips the video.+ app.getResource(Ads)?.setProvider(createMockAdProvider());+// Role first, runtime second: initPlayRealmRuntime ends in app.run(), and by// then the Net role must already be decided (see beginNet).const netReady = beginNet(msg);diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex cb85af928..cdccfcb6e 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1380 stable · 17 beta · 1 deprecated+Symbols: 1391 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -42,6 +42,12 @@ ranges: ActivationRange[]type: "activation"```+## AdProvider — interface+```+createInterstitialAd: (adUnitId: string) => PlatformInterstitialAd+createRewardedAd: (adUnitId: string) => PlatformRewardedAd+```+## Added — function```<T extends AnyComponentDef>(component: T): AddedWrapper<T>@@ -95,6 +101,31 @@ bundleMode: stringlabels: string[]```+## Ads — const+```+ResourceDef<AdsAPI>+```++## AdsAPI — class+```+available: boolean+preloadRewarded: (adUnitId: string) => Promise<void>+setProvider: (provider: AdProvider | null) => void+showInterstitial: (adUnitId: string) => Promise<void>+showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>+showing: boolean+static new (host: AdsHost): AdsAPI+static prototype: AdsAPI+```++## AdsHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## AiAction — type```(@@ -684,6 +715,7 @@ preload: (url: string) => Promise<void>preloadAll: (urls: string[]) => Promise<void>preloadFromData: (url: string, data: ArrayBuffer) => Promise<void>releaseBuffer: (url: string) => void+resume: () => voidretainBuffer: (url: string) => booleansetAssetResolver: (resolver: (url: string) => ArrayBuffer | null) => voidsetBufferBudget: (bytes: number | null) => void@@ -697,6 +729,7 @@ setSFXVolume: (volume: number) => voidsetUIVolume: (volume: number) => voidstopAll: () => voidstopBGM: (fadeOut?: number) => void+suspend: () => voidtrimBufferCache: () => numberupdateDucking: () => voidupdateFades: (dt: number) => void@@ -4087,6 +4120,12 @@ static new (missing: MissingAsset[]): MissingAssetsErrorstatic prototype: MissingAssetsError```+## MockAdProviderOptions — interface+```+completed: boolean | undefined+durationMs: number | undefined+```+## Modifiers — interface```alt: boolean@@ -4707,6 +4746,8 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImage+createInterstitialAd: ((adUnitId: string) => PlatformInterstitialAd | null) | undefined+createRewardedAd: ((adUnitId: string) => PlatformRewardedAd | null) | undefinedcreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefinedcreateTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined@@ -4724,6 +4765,7 @@ now: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefined+onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefinedrasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined@@ -4732,6 +4774,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+share: ((options: PlatformShareOptions) => void) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6081,6 +6124,14 @@ sensorEntity: numbervisitorEntity: number```+## ServicesPlugin — class+```+build: (app: App) => void+name: string+static new (): ServicesPlugin+static prototype: ServicesPlugin+```+## ShaderHandle — type```number@@ -6125,6 +6176,25 @@ Circle = 0RoundedRect = 2```+## Share — const+```+ResourceDef<ShareAPI>+```++## ShareAPI — class+```+available: boolean+setShareCard: (card: ShareCard | (() => ShareCard)) => void+share: (card?: ShareCard) => boolean+static new (): ShareAPI+static prototype: ShareAPI+```++## ShareCard — type+```+PlatformShareOptions+```+## SideModuleHost — interface```acquire: (id: SideModuleId) => Promise<SideModule | null>@@ -8710,6 +8780,11 @@ Plugin(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]```+## createMockAdProvider — function+```+(options?: MockAdProviderOptions): AdProvider+```+## createPackagedAssetSource — function```(index: PackagedAssetIndex, options?: PackagedAssetSourceOptions): RuntimeAssetSource@@ -10115,6 +10190,11 @@ Plugin(asset: TimelineAsset, indent?: number): string```+## servicesPlugin — const+```+ServicesPlugin+```+## setAnimatorConditions — function```(def: AnimatorControllerDef, from: string, index: number, conditions: AnimatorCondition[]): AnimatorControllerDefdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex b82c6b9d7..130017f10 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1399 stable · 22 beta · 1 deprecated+Symbols: 1410 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -42,6 +42,12 @@ ranges: ActivationRange[]type: "activation"```+## AdProvider — interface+```+createInterstitialAd: (adUnitId: string) => PlatformInterstitialAd+createRewardedAd: (adUnitId: string) => PlatformRewardedAd+```+## Added — function```<T extends AnyComponentDef>(component: T): AddedWrapper<T>@@ -95,6 +101,31 @@ bundleMode: stringlabels: string[]```+## Ads — const+```+ResourceDef<AdsAPI>+```++## AdsAPI — class+```+available: boolean+preloadRewarded: (adUnitId: string) => Promise<void>+setProvider: (provider: AdProvider | null) => void+showInterstitial: (adUnitId: string) => Promise<void>+showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>+showing: boolean+static new (host: AdsHost): AdsAPI+static prototype: AdsAPI+```++## AdsHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## AiAction — type```(@@ -684,6 +715,7 @@ preload: (url: string) => Promise<void>preloadAll: (urls: string[]) => Promise<void>preloadFromData: (url: string, data: ArrayBuffer) => Promise<void>releaseBuffer: (url: string) => void+resume: () => voidretainBuffer: (url: string) => booleansetAssetResolver: (resolver: (url: string) => ArrayBuffer | null) => voidsetBufferBudget: (bytes: number | null) => void@@ -697,6 +729,7 @@ setSFXVolume: (volume: number) => voidsetUIVolume: (volume: number) => voidstopAll: () => voidstopBGM: (fadeOut?: number) => void+suspend: () => voidtrimBufferCache: () => numberupdateDucking: () => voidupdateFades: (dt: number) => void@@ -4100,6 +4133,12 @@ static new (missing: MissingAsset[]): MissingAssetsErrorstatic prototype: MissingAssetsError```+## MockAdProviderOptions — interface+```+completed: boolean | undefined+durationMs: number | undefined+```+## Modifiers — interface```alt: boolean@@ -4863,6 +4902,8 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImage+createInterstitialAd: ((adUnitId: string) => PlatformInterstitialAd | null) | undefined+createRewardedAd: ((adUnitId: string) => PlatformRewardedAd | null) | undefinedcreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefinedcreateTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined@@ -4880,6 +4921,7 @@ now: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefined+onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefinedrasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined@@ -4888,6 +4930,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+share: ((options: PlatformShareOptions) => void) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6247,6 +6290,14 @@ sensorEntity: numbervisitorEntity: number```+## ServicesPlugin — class+```+build: (app: App) => void+name: string+static new (): ServicesPlugin+static prototype: ServicesPlugin+```+## ShaderHandle — type```number@@ -6291,6 +6342,25 @@ Circle = 0RoundedRect = 2```+## Share — const+```+ResourceDef<ShareAPI>+```++## ShareAPI — class+```+available: boolean+setShareCard: (card: ShareCard | (() => ShareCard)) => void+share: (card?: ShareCard) => boolean+static new (): ShareAPI+static prototype: ShareAPI+```++## ShareCard — type+```+PlatformShareOptions+```+## SideModuleHost — interface```acquire: (id: SideModuleId) => Promise<SideModule | null>@@ -8896,6 +8966,11 @@ Plugin(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]```+## createMockAdProvider — function+```+(options?: MockAdProviderOptions): AdProvider+```+## createNativeApp — function```(bridge: NativeBridge, scope?: Record<string, unknown>): App@@ -10331,6 +10406,11 @@ Plugin(asset: TimelineAsset, indent?: number): string```+## servicesPlugin — const+```+ServicesPlugin+```+## setAnimatorConditions — function```(def: AnimatorControllerDef, from: string, index: number, conditions: AnimatorCondition[]): AnimatorControllerDefdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 4f82eaf4b..54c8997fa 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1379 stable · 19 beta · 1 deprecated+Symbols: 1390 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -37,6 +37,12 @@ ranges: ActivationRange[]type: "activation"```+## AdProvider — interface+```+createInterstitialAd: (adUnitId: string) => PlatformInterstitialAd+createRewardedAd: (adUnitId: string) => PlatformRewardedAd+```+## Added — function```<T extends AnyComponentDef>(component: T): AddedWrapper<T>@@ -90,6 +96,31 @@ bundleMode: stringlabels: string[]```+## Ads — const+```+ResourceDef<AdsAPI>+```++## AdsAPI — class+```+available: boolean+preloadRewarded: (adUnitId: string) => Promise<void>+setProvider: (provider: AdProvider | null) => void+showInterstitial: (adUnitId: string) => Promise<void>+showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>+showing: boolean+static new (host: AdsHost): AdsAPI+static prototype: AdsAPI+```++## AdsHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## AiAction — type```(@@ -679,6 +710,7 @@ preload: (url: string) => Promise<void>preloadAll: (urls: string[]) => Promise<void>preloadFromData: (url: string, data: ArrayBuffer) => Promise<void>releaseBuffer: (url: string) => void+resume: () => voidretainBuffer: (url: string) => booleansetAssetResolver: (resolver: (url: string) => ArrayBuffer | null) => voidsetBufferBudget: (bytes: number | null) => void@@ -692,6 +724,7 @@ setSFXVolume: (volume: number) => voidsetUIVolume: (volume: number) => voidstopAll: () => voidstopBGM: (fadeOut?: number) => void+suspend: () => voidtrimBufferCache: () => numberupdateDucking: () => voidupdateFades: (dt: number) => void@@ -4082,6 +4115,12 @@ static new (missing: MissingAsset[]): MissingAssetsErrorstatic prototype: MissingAssetsError```+## MockAdProviderOptions — interface+```+completed: boolean | undefined+durationMs: number | undefined+```+## Modifiers — interface```alt: boolean@@ -4702,6 +4741,8 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImage+createInterstitialAd: ((adUnitId: string) => PlatformInterstitialAd | null) | undefined+createRewardedAd: ((adUnitId: string) => PlatformRewardedAd | null) | undefinedcreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefinedcreateTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined@@ -4719,6 +4760,7 @@ now: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefined+onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefinedrasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined@@ -4727,6 +4769,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+share: ((options: PlatformShareOptions) => void) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6076,6 +6119,14 @@ sensorEntity: numbervisitorEntity: number```+## ServicesPlugin — class+```+build: (app: App) => void+name: string+static new (): ServicesPlugin+static prototype: ServicesPlugin+```+## ShaderHandle — type```number@@ -6120,6 +6171,25 @@ Circle = 0RoundedRect = 2```+## Share — const+```+ResourceDef<ShareAPI>+```++## ShareAPI — class+```+available: boolean+setShareCard: (card: ShareCard | (() => ShareCard)) => void+share: (card?: ShareCard) => boolean+static new (): ShareAPI+static prototype: ShareAPI+```++## ShareCard — type+```+PlatformShareOptions+```+## SideModuleHost — interface```acquire: (id: SideModuleId) => Promise<SideModule | null>@@ -8705,6 +8775,11 @@ Plugin(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]```+## createMockAdProvider — function+```+(options?: MockAdProviderOptions): AdProvider+```+## createPackagedAssetSource — function```(index: PackagedAssetIndex, options?: PackagedAssetSourceOptions): RuntimeAssetSource@@ -10120,6 +10195,11 @@ Plugin(asset: TimelineAsset, indent?: number): string```+## servicesPlugin — const+```+ServicesPlugin+```+## setAnimatorConditions — function```(def: AnimatorControllerDef, from: string, index: number, conditions: AnimatorCondition[]): AnimatorControllerDefdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 6d7ab5b69..547f984fd 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1400 stable · 17 beta · 1 deprecated+Symbols: 1411 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -37,6 +37,12 @@ ranges: ActivationRange[]type: "activation"```+## AdProvider — interface+```+createInterstitialAd: (adUnitId: string) => PlatformInterstitialAd+createRewardedAd: (adUnitId: string) => PlatformRewardedAd+```+## Added — function```<T extends AnyComponentDef>(component: T): AddedWrapper<T>@@ -90,6 +96,31 @@ bundleMode: stringlabels: string[]```+## Ads — const+```+ResourceDef<AdsAPI>+```++## AdsAPI — class+```+available: boolean+preloadRewarded: (adUnitId: string) => Promise<void>+setProvider: (provider: AdProvider | null) => void+showInterstitial: (adUnitId: string) => Promise<void>+showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>+showing: boolean+static new (host: AdsHost): AdsAPI+static prototype: AdsAPI+```++## AdsHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## AiAction — type```(@@ -679,6 +710,7 @@ preload: (url: string) => Promise<void>preloadAll: (urls: string[]) => Promise<void>preloadFromData: (url: string, data: ArrayBuffer) => Promise<void>releaseBuffer: (url: string) => void+resume: () => voidretainBuffer: (url: string) => booleansetAssetResolver: (resolver: (url: string) => ArrayBuffer | null) => voidsetBufferBudget: (bytes: number | null) => void@@ -692,6 +724,7 @@ setSFXVolume: (volume: number) => voidsetUIVolume: (volume: number) => voidstopAll: () => voidstopBGM: (fadeOut?: number) => void+suspend: () => voidtrimBufferCache: () => numberupdateDucking: () => voidupdateFades: (dt: number) => void@@ -4099,6 +4132,8 @@ connectSocket: (opts: { url: string; protocols?: string[]; }) => MiniGameSocketTcreateCanvas: () => MiniGameCanvascreateImage: () => MiniGameImagecreateInnerAudioContext: () => MiniGameInnerAudioContext+createInterstitialAd: ((opts: { adUnitId: string; }) => MiniGameInterstitialAd) | undefined+createRewardedVideoAd: ((opts: { adUnitId: string; }) => MiniGameRewardedVideoAd) | undefinedgetFileSystemManager: () => MiniGameFileSystemManagergetStorageInfoSync: () => MiniGameStorageInfogetStorageSync: (key: string) => unknown@@ -4115,6 +4150,7 @@ onHide: ((cb: () => void) => void) | undefinedonKeyDown: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefinedonKeyUp: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefinedonMemoryWarning: ((cb: () => void) => void) | undefined+onShareAppMessage: ((cb: () => MiniGameShareOptions) => void) | undefinedonShow: ((cb: () => void) => void) | undefinedonTouchCancel: ((cb: (res: MiniGameTouchEvent) => void) => void) | undefinedonTouchEnd: (cb: (res: MiniGameTouchEvent) => void) => void@@ -4123,6 +4159,7 @@ onTouchStart: (cb: (res: MiniGameTouchEvent) => void) => voidremoveStorageSync: (key: string) => voidrequest: (opts: MiniGameRequestOptions) => voidsetStorageSync: (key: string, value: string) => void+shareAppMessage: ((opts: MiniGameShareOptions) => void) | undefined```## MiniGameImage — interface@@ -4165,6 +4202,8 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: () => PlatformAudioBackendcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImage+createInterstitialAd: (adUnitId: string) => PlatformInterstitialAd | null+createRewardedAd: (adUnitId: string) => PlatformRewardedAd | nullcreateScreenCanvas: () => MiniGameCanvascreateSocket: (options: PlatformSocketOptions) => PlatformSocketcreateVideoBackend: (ctx: VideoBackendContext) => PlatformVideoBackend@@ -4180,10 +4219,12 @@ loadSubpackage: (name: string) => Promise<void>name: PlatformNamenow: () => numberonMemoryWarning: (callback: () => void) => () => void+onShareRequest: (provide: () => PlatformShareOptions) => voidreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>removeStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+share: (options: PlatformShareOptions) => voidunbindInputEvents: () => voidstatic new (profile: MiniGameProfile): MiniGamePlatformAdapterstatic prototype: MiniGamePlatformAdapter@@ -4297,6 +4338,12 @@ static new (missing: MissingAsset[]): MissingAssetsErrorstatic prototype: MissingAssetsError```+## MockAdProviderOptions — interface+```+completed: boolean | undefined+durationMs: number | undefined+```+## Modifiers — interface```alt: boolean@@ -4917,6 +4964,8 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImage+createInterstitialAd: ((adUnitId: string) => PlatformInterstitialAd | null) | undefined+createRewardedAd: ((adUnitId: string) => PlatformRewardedAd | null) | undefinedcreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefinedcreateTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined@@ -4934,6 +4983,7 @@ now: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefined+onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefinedrasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined@@ -4942,6 +4992,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+share: ((options: PlatformShareOptions) => void) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6291,6 +6342,14 @@ sensorEntity: numbervisitorEntity: number```+## ServicesPlugin — class+```+build: (app: App) => void+name: string+static new (): ServicesPlugin+static prototype: ServicesPlugin+```+## ShaderHandle — type```number@@ -6335,6 +6394,25 @@ Circle = 0RoundedRect = 2```+## Share — const+```+ResourceDef<ShareAPI>+```++## ShareAPI — class+```+available: boolean+setShareCard: (card: ShareCard | (() => ShareCard)) => void+share: (card?: ShareCard) => boolean+static new (): ShareAPI+static prototype: ShareAPI+```++## ShareCard — type+```+PlatformShareOptions+```+## SideModuleHost — interface```acquire: (id: SideModuleId) => Promise<SideModule | null>@@ -8925,6 +9003,11 @@ Plugin(factories: MiniGameSideModuleFactories): SideModuleHost```+## createMockAdProvider — function+```+(options?: MockAdProviderOptions): AdProvider+```+## createPackagedAssetSource — function```(index: PackagedAssetIndex, options?: PackagedAssetSourceOptions): RuntimeAssetSource@@ -10340,6 +10423,11 @@ Plugin(asset: TimelineAsset, indent?: number): string```+## servicesPlugin — const+```+ServicesPlugin+```+## setAnimatorConditions — function```(def: AnimatorControllerDef, from: string, index: number, conditions: AnimatorCondition[]): AnimatorControllerDefdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex f227de07c..1270e86b3 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1390 stable · 17 beta · 1 deprecated+Symbols: 1401 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -37,6 +37,12 @@ ranges: ActivationRange[]type: "activation"```+## AdProvider — interface+```+createInterstitialAd: (adUnitId: string) => PlatformInterstitialAd+createRewardedAd: (adUnitId: string) => PlatformRewardedAd+```+## Added — function```<T extends AnyComponentDef>(component: T): AddedWrapper<T>@@ -90,6 +96,31 @@ bundleMode: stringlabels: string[]```+## Ads — const+```+ResourceDef<AdsAPI>+```++## AdsAPI — class+```+available: boolean+preloadRewarded: (adUnitId: string) => Promise<void>+setProvider: (provider: AdProvider | null) => void+showInterstitial: (adUnitId: string) => Promise<void>+showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>+showing: boolean+static new (host: AdsHost): AdsAPI+static prototype: AdsAPI+```++## AdsHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## AiAction — type```(@@ -679,6 +710,7 @@ preload: (url: string) => Promise<void>preloadAll: (urls: string[]) => Promise<void>preloadFromData: (url: string, data: ArrayBuffer) => Promise<void>releaseBuffer: (url: string) => void+resume: () => voidretainBuffer: (url: string) => booleansetAssetResolver: (resolver: (url: string) => ArrayBuffer | null) => voidsetBufferBudget: (bytes: number | null) => void@@ -692,6 +724,7 @@ setSFXVolume: (volume: number) => voidsetUIVolume: (volume: number) => voidstopAll: () => voidstopBGM: (fadeOut?: number) => void+suspend: () => voidtrimBufferCache: () => numberupdateDucking: () => voidupdateFades: (dt: number) => void@@ -4089,6 +4122,12 @@ static new (missing: MissingAsset[]): MissingAssetsErrorstatic prototype: MissingAssetsError```+## MockAdProviderOptions — interface+```+completed: boolean | undefined+durationMs: number | undefined+```+## Modifiers — interface```alt: boolean@@ -4709,6 +4748,8 @@ clearStorage: (prefix: string) => voidcreateAudioBackend: (() => PlatformAudioBackend) | undefinedcreateCanvas: (width: number, height: number) => PlatformCanvascreateImage: () => PlatformImage+createInterstitialAd: ((adUnitId: string) => PlatformInterstitialAd | null) | undefined+createRewardedAd: ((adUnitId: string) => PlatformRewardedAd | null) | undefinedcreateSocket: ((options: PlatformSocketOptions) => PlatformSocket) | undefinedcreateTextEditor: (() => PlatformTextEditor | null) | undefinedcreateVideoBackend: ((ctx: VideoBackendContext) => PlatformVideoBackend) | undefined@@ -4726,6 +4767,7 @@ now: () => numberonAppHide: ((callback: () => void) => () => void) | undefinedonAppShow: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefined+onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefinedrasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefinedreadCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined@@ -4734,6 +4776,7 @@ readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+share: ((options: PlatformShareOptions) => void) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6083,6 +6126,14 @@ sensorEntity: numbervisitorEntity: number```+## ServicesPlugin — class+```+build: (app: App) => void+name: string+static new (): ServicesPlugin+static prototype: ServicesPlugin+```+## ShaderHandle — type```number@@ -6127,6 +6178,25 @@ Circle = 0RoundedRect = 2```+## Share — const+```+ResourceDef<ShareAPI>+```++## ShareAPI — class+```+available: boolean+setShareCard: (card: ShareCard | (() => ShareCard)) => void+share: (card?: ShareCard) => boolean+static new (): ShareAPI+static prototype: ShareAPI+```++## ShareCard — type+```+PlatformShareOptions+```+## SideModuleHost — interface```acquire: (id: SideModuleId) => Promise<SideModule | null>@@ -8729,6 +8799,11 @@ Plugin(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]```+## createMockAdProvider — function+```+(options?: MockAdProviderOptions): AdProvider+```+## createPackagedAssetSource — function```(index: PackagedAssetIndex, options?: PackagedAssetSourceOptions): RuntimeAssetSource@@ -10139,6 +10214,11 @@ Plugin(asset: TimelineAsset, indent?: number): string```+## servicesPlugin — const+```+ServicesPlugin+```+## setAnimatorConditions — function```(def: AnimatorControllerDef, from: string, index: number, conditions: AnimatorCondition[]): AnimatorControllerDefdiff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.tsindex 0ee6a0084..df43568d0 100644--- a/sdk/src/app/pluginSets.ts+++ b/sdk/src/app/pluginSets.ts@@ -36,14 +36,18 @@ import { lifecyclePlugin } from '../ecs/lifecycle';import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from '../ai';import { eventBindingPlugin } from '../eventBinding';import { replicationPlugin } from '../net/replication';+import { servicesPlugin } from '../services';/*** The simulation: timers/lifecycle, gameplay AI, audio (silent on a host with no- * device) and replication. What an authoritative server runs.+ * device), replication, and platform services (ads/share — unavailable on a host+ * with no such surface, and gameplay code gates on `Ads.available` the same way+ * audio degrades). What an authoritative server runs.*/export const simulationBasePlugins = (): Plugin[] => [timerPlugin, velocityPlugin, lifecyclePlugin, audioPlugin,perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,+ servicesPlugin,];/** What exists to be seen. Every entry drives the engine through `engineApi`. */@@ -61,4 +65,5 @@ export const webBasePlugins = (): Plugin[] => [timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin,perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,+ servicesPlugin,];diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.tsindex 06c2bf325..e7c0d3e03 100644--- a/sdk/src/audio/Audio.ts+++ b/sdk/src/audio/Audio.ts@@ -414,6 +414,21 @@ export class AudioAPI {}}+ /**+ * Suspend the whole audio device (every voice, every bus) without touching+ * any volume the user set — the device-level pause a fullscreen takeover+ * (a rewarded ad, an OS interruption) wants, where per-bus volumes would+ * fight the mixer's own state. Balanced by {@link resume}.+ */+ suspend(): void {+ this.backend_.suspend();+ }++ /** Resume the audio device after {@link suspend}. */+ resume(): void {+ this.backend_.resume();+ }+setMasterVolume(volume: number): void {if (this.mixer_) {this.mixer_.master.volume = volume;diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex a2df7d0e2..93431911e 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -398,6 +398,17 @@ export {type PooledAudioNode,} from './audio';+// =============================================================================+// Platform services (ads, share)+// =============================================================================++export {+ Ads, AdsAPI, createMockAdProvider,+ Share, ShareAPI,+ ServicesPlugin, servicesPlugin,+ type AdProvider, type AdsHost, type MockAdProviderOptions, type ShareCard,+} from './services';+// =============================================================================// Video// =============================================================================diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex 5f626fb56..ec7f14f3a 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -253,6 +253,52 @@ export function platformSetStorageItem(key: string, value: string): void {getPlatform().setStorageItem(key, value);}+/** Whether this platform can mint ad units at all, without minting one (a+ * mini-game host materializes a real host object per created unit). */+export function platformCanCreateAds(): boolean {+ return isPlatformInitialized() && getPlatform().createRewardedAd !== undefined;+}++/** One rewarded ad unit from the platform, or null where the platform has no ad+ * system (web, native, playable, an uninitialized platform in tests). Null is+ * an answer, not an error: the services layer substitutes its mock provider or+ * fails loud with the reason, which is a decision this layer cannot make. */+export function platformCreateRewardedAd(adUnitId: string): import('./types').PlatformRewardedAd | null {+ if (!isPlatformInitialized()) return null;+ return getPlatform().createRewardedAd?.(adUnitId) ?? null;+}++/** One interstitial ad unit, or null — same availability story as rewarded. */+export function platformCreateInterstitialAd(adUnitId: string): import('./types').PlatformInterstitialAd | null {+ if (!isPlatformInitialized()) return null;+ return getPlatform().createInterstitialAd?.(adUnitId) ?? null;+}++/** Whether this platform can open a share sheet at all, without opening one. */+export function platformCanShare(): boolean {+ return isPlatformInitialized() && getPlatform().share !== undefined;+}++/** Actively open the host's share sheet; false when this platform cannot share+ * (web, native, tests) so the caller can hide its share button honestly. */+export function platformShare(options: import('./types').PlatformShareOptions): boolean {+ if (!isPlatformInitialized()) return false;+ const p = getPlatform();+ if (!p.share) return false;+ p.share(options);+ return true;+}++/** Register the passive-share card provider; false when the platform has no+ * passive share surface. The host asks the provider at share time. */+export function platformOnShareRequest(provide: () => import('./types').PlatformShareOptions): boolean {+ if (!isPlatformInitialized()) return false;+ const p = getPlatform();+ if (!p.onShareRequest) return false;+ p.onShareRequest(provide);+ return true;+}+export function platformDevicePixelRatio(): number {if (currentPlatform) {return currentPlatform.devicePixelRatio();diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex a1f154c8a..a0f9b247c 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -54,6 +54,12 @@ export {platformSetStorageItem,platformDevicePixelRatio,platformLanguage,+ platformCanCreateAds,+ platformCreateRewardedAd,+ platformCreateInterstitialAd,+ platformCanShare,+ platformShare,+ platformOnShareRequest,} from './base';// Note: webAdapter is exported here for initializationdiff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex a4f8114c2..283e842af 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -23,6 +23,10 @@ import type {PlatformImage,PlatformSocket,PlatformSocketOptions,+ PlatformRewardedAd,+ PlatformRewardedAdResult,+ PlatformInterstitialAd,+ PlatformShareOptions,} from '../types';import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';@@ -114,6 +118,69 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {});}+ /** 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);+ }++ /** Register the passive-share card provider (the host's own share menu). */+ onShareRequest(provide: () => PlatformShareOptions): void {+ this.g_.onShareAppMessage?.call(this.g_, provide);+ }+onMemoryWarning(callback: () => void): () => void {const on = this.g_.onMemoryWarning;const off = this.g_.offMemoryWarning;diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.tsindex 35cedfd2d..4b8f3ae33 100644--- a/sdk/src/platform/minigame/api.ts+++ b/sdk/src/platform/minigame/api.ts@@ -116,6 +116,46 @@ export interface MiniGameInnerAudioContext {onError(cb: (res: { errMsg: string }) => void): void;}+/**+ * A rewarded video ad, as every mini-game host shapes it: WeChat's+ * `RewardedVideoAd` and Douyin's are structurally identical, which is what+ * makes ads a FAMILY capability rather than a per-vendor override. `onClose`+ * reports whether the video was watched to the end (`isEnded`); some hosts+ * omit the record entirely on older runtimes, which callers must treat as+ * "completed" — the platform granted the reward and simply didn't say so.+ */+export interface MiniGameRewardedVideoAd {+ load(): Promise<void>;+ show(): Promise<void>;+ onLoad(cb: () => void): void;+ offLoad(cb: () => void): void;+ onError(cb: (err: { errMsg: string; errCode?: number }) => void): void;+ offError(cb: (err: { errMsg: string; errCode?: number }) => void): void;+ onClose(cb: (res?: { isEnded: boolean }) => void): void;+ offClose(cb: (res?: { isEnded: boolean }) => void): void;+}++/** An interstitial ad. Same family shape as rewarded, plus `destroy` (the+ * hosts document interstitials as destroyable; rewarded ads are singletons). */+export interface MiniGameInterstitialAd {+ load(): Promise<void>;+ show(): Promise<void>;+ destroy(): void;+ onLoad(cb: () => void): void;+ offLoad(cb: () => void): void;+ onError(cb: (err: { errMsg: string; errCode?: number }) => void): void;+ offError(cb: (err: { errMsg: string; errCode?: number }) => void): void;+ onClose(cb: () => void): void;+ offClose(cb: () => void): void;+}++/** The share card a host shows for an active or passive share. */+export interface MiniGameShareOptions {+ title?: string;+ imageUrl?: string;+ query?: string;+}+/** The socket task `connectSocket()` returns. WeChat's `SocketTask` fits. */export interface MiniGameSocketTask {send(opts: { data: string | ArrayBuffer }): void;@@ -173,6 +213,15 @@ export interface MiniGameGlobal {onShow?(cb: () => void): void;onHide?(cb: () => void): void;+ /** Monetization + share — optional like every capability a vendor may lack+ * (or a game may not have configured): the adapter probes at use time. */+ createRewardedVideoAd?(opts: { adUnitId: string }): MiniGameRewardedVideoAd;+ createInterstitialAd?(opts: { adUnitId: string }): MiniGameInterstitialAd;+ shareAppMessage?(opts: MiniGameShareOptions): void;+ /** Passive share: what the card says when the player shares from the host's+ * own menu. The host calls `cb` at share time, not at registration. */+ onShareAppMessage?(cb: () => MiniGameShareOptions): void;+getStorageSync(key: string): unknown;setStorageSync(key: string, value: string): void;removeStorageSync(key: string): void;diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 992eadc18..ff70ac4ae 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -491,6 +491,22 @@ export interface PlatformAdapter {* Optional; web falls through to navigator.language. */language?(): string;+ /** One rewarded ad unit. Mini-game hosts implement it over their+ * RewardedVideoAd; platforms without an ad system (web, native until a+ * mediation SDK is wired, playable — networks forbid nested ads) omit the+ * method, and a family adapter whose PARTICULAR host lacks the capability+ * returns null. Both answers mean the same thing to the services layer:+ * substitute the mock provider or fail loud with the reason. */+ createRewardedAd?(adUnitId: string): PlatformRewardedAd | null;+ /** One interstitial ad unit — same availability story as rewarded. */+ createInterstitialAd?(adUnitId: string): PlatformInterstitialAd | null;+ /** Actively open the host's share sheet. Fire-and-forget: since 2021 no+ * mini-game host reports whether the player actually shared. */+ share?(options: PlatformShareOptions): void;+ /** Provide the card for PASSIVE shares (the host's own share menu). The+ * host asks at share time, so the provider can answer with live state. */+ onShareRequest?(provide: () => PlatformShareOptions): void;+devicePixelRatio(): number;getStorageItem(key: string): string | null;@@ -499,6 +515,42 @@ export interface PlatformAdapter {clearStorage(prefix: string): void;}+// =============================================================================+// Monetization / share services+// =============================================================================++/** How a rewarded ad ended: `completed` is whether the reward was earned. */+export interface PlatformRewardedAdResult {+ completed: boolean;+}++/**+ * One rewarded ad unit. `show()` resolves when the ad CLOSED (however that+ * went), never while it is covering the game — the services layer wraps the+ * whole span in pause/resume. Implementations own the host's load/show dance+ * (load on demand, one reload retry on a stale instance).+ */+export interface PlatformRewardedAd {+ preload(): Promise<void>;+ show(): Promise<PlatformRewardedAdResult>;+ destroy(): void;+}++/** One interstitial ad unit. Same contract as rewarded, minus the reward. */+export interface PlatformInterstitialAd {+ preload(): Promise<void>;+ show(): Promise<void>;+ destroy(): void;+}++/** The share card for an active or passive share. `query` rides the launch+ * options of whoever opens the shared card (invite links, room codes). */+export interface PlatformShareOptions {+ title?: string;+ imageUrl?: string;+ query?: string;+}+// =============================================================================// Platform Detection// =============================================================================diff --git a/sdk/src/services/ads.ts b/sdk/src/services/ads.tsnew file mode 100644index 000000000..c7c6451fc--- /dev/null+++ b/sdk/src/services/ads.ts@@ -0,0 +1,181 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ads.ts+ * @brief Rewarded / interstitial ads as an engine service.+ *+ * The platform supplies the ad (wx/tt on mini-game hosts, the mock provider in+ * the editor and in tests); this layer supplies what every game otherwise+ * hand-rolls around `wx.createRewardedVideoAd` and usually gets subtly wrong:+ * the game CLOCK pauses while an ad covers the screen (a rewarded video must+ * not cost the player their run) and the audio DEVICE suspends without touching+ * any volume the user set — both restored however the ad ends, including in+ * error paths. `showRewarded` resolves with whether the reward was earned.+ */+import { defineResource } from '../ecs/resource';+import { platformCreateRewardedAd, platformCreateInterstitialAd, platformCanCreateAds } from '../platform';+import type { PlatformRewardedAd, PlatformInterstitialAd, PlatformRewardedAdResult } from '../platform/types';+import { log } from '../util/logger';++/**+ * A drop-in ad source for hosts that have none: the editor's play mode, unit+ * tests, a web dev build. `create*` mirrors the platform factories so one seam+ * serves both; {@link createMockAdProvider} is the standard implementation.+ */+export interface AdProvider {+ createRewardedAd(adUnitId: string): PlatformRewardedAd;+ createInterstitialAd(adUnitId: string): PlatformInterstitialAd;+}++export interface MockAdProviderOptions {+ /** How long the pretend ad stays "on screen" (ms). Default 600 — long+ * enough that a broken pause/resume would be seen, short enough to iterate. */+ durationMs?: number;+ /** What `showRewarded` reports. Default true; set false to exercise the+ * player-abandoned path. */+ completed?: boolean;+}++/** The mock ad source: resolves after a short pretend playback. The pause /+ * audio-suspend ceremony still runs for real, so the editor exercises the+ * exact frames a device would. */+export function createMockAdProvider(options: MockAdProviderOptions = {}): AdProvider {+ const duration = options.durationMs ?? 600;+ const completed = options.completed ?? true;+ const wait = (): Promise<void> => new Promise((r) => setTimeout(r, duration));+ return {+ createRewardedAd: (adUnitId) => ({+ preload: () => Promise.resolve(),+ show: async () => {+ log.info('services', `mock rewarded ad "${adUnitId}" (${duration}ms, completed=${completed})`);+ await wait();+ return { completed };+ },+ destroy: () => {},+ }),+ createInterstitialAd: (adUnitId) => ({+ preload: () => Promise.resolve(),+ show: async () => {+ log.info('services', `mock interstitial ad "${adUnitId}" (${duration}ms)`);+ await wait();+ },+ destroy: () => {},+ }),+ };+}++/** What the ads service asks of the app around a fullscreen takeover. Injected+ * so the service stays a pure orchestration (and the tests stay honest). */+export interface AdsHost {+ setPaused(paused: boolean): void;+ isPaused(): boolean;+ suspendAudio(): void;+ resumeAudio(): void;+}++export class AdsAPI {+ private readonly host_: AdsHost;+ private provider_: AdProvider | null = null;+ private readonly rewarded_ = new Map<string, PlatformRewardedAd>();+ private readonly interstitials_ = new Map<string, PlatformInterstitialAd>();+ private showing_ = false;++ constructor(host: AdsHost) {+ this.host_ = host;+ }++ /** Whether SOME ad source exists here — the platform's or an installed+ * provider. False is what a menu reads to hide its "watch ad" button. */+ get available(): boolean {+ return this.provider_ !== null || platformCanCreateAds();+ }++ /** True while an ad covers the game (the clock is paused, audio suspended). */+ get showing(): boolean {+ return this.showing_;+ }++ /**+ * Install (or clear with null) an {@link AdProvider} that answers INSTEAD of+ * the platform. The editor's play mode installs the mock; a native shell+ * with a mediation SDK installs a real one. Clearing drops cached units.+ */+ setProvider(provider: AdProvider | null): void {+ this.provider_ = provider;+ this.dropCachedUnits_();+ }++ /** Warm a rewarded unit so `showRewarded` has a fill ready. Best-effort:+ * a preload failure only means show() pays the load. */+ preloadRewarded(adUnitId: string): Promise<void> {+ const ad = this.rewardedUnit_(adUnitId);+ return ad ? ad.preload().catch(() => {}) : Promise.resolve();+ }++ /**+ * Show a rewarded video and resolve with whether the reward was earned —+ * after the ad closed and the game is running again. Rejects when this+ * platform has no ad source (check {@link available} first) or the host+ * genuinely has no fill; the game state is restored in every path.+ */+ showRewarded(adUnitId: string): Promise<PlatformRewardedAdResult> {+ const ad = this.rewardedUnit_(adUnitId);+ if (!ad) return Promise.reject(new Error(AdsAPI.NO_SOURCE));+ return this.withTakeover_(() => ad.show());+ }++ /** Show an interstitial; resolves when it closed. Same contract as+ * {@link showRewarded}, minus the reward. */+ showInterstitial(adUnitId: string): Promise<void> {+ const ad = this.interstitialUnit_(adUnitId);+ if (!ad) return Promise.reject(new Error(AdsAPI.NO_SOURCE));+ return this.withTakeover_(() => ad.show());+ }++ private static readonly NO_SOURCE =+ 'no ad source on this platform — check Ads.available, or install a provider (the editor installs a mock in play mode)';++ /** The pause/suspend ceremony around a fullscreen takeover. A game the+ * DEVELOPER already paused stays paused afterwards — the ceremony restores+ * the state it found, it does not assert one. */+ private async withTakeover_<T>(show: () => Promise<T>): Promise<T> {+ const wasPaused = this.host_.isPaused();+ this.showing_ = true;+ if (!wasPaused) this.host_.setPaused(true);+ this.host_.suspendAudio();+ try {+ return await show();+ } finally {+ this.showing_ = false;+ this.host_.resumeAudio();+ if (!wasPaused) this.host_.setPaused(false);+ }+ }++ private rewardedUnit_(adUnitId: string): PlatformRewardedAd | null {+ let ad = this.rewarded_.get(adUnitId) ?? null;+ if (!ad) {+ ad = this.provider_?.createRewardedAd(adUnitId) ?? platformCreateRewardedAd(adUnitId);+ if (ad) this.rewarded_.set(adUnitId, ad);+ }+ return ad;+ }++ private interstitialUnit_(adUnitId: string): PlatformInterstitialAd | null {+ let ad = this.interstitials_.get(adUnitId) ?? null;+ if (!ad) {+ ad = this.provider_?.createInterstitialAd(adUnitId) ?? platformCreateInterstitialAd(adUnitId);+ if (ad) this.interstitials_.set(adUnitId, ad);+ }+ return ad;+ }++ private dropCachedUnits_(): void {+ for (const ad of this.rewarded_.values()) ad.destroy();+ for (const ad of this.interstitials_.values()) ad.destroy();+ this.rewarded_.clear();+ this.interstitials_.clear();+ }+}++export const Ads = defineResource<AdsAPI>(null!, 'Ads');diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.tsnew file mode 100644index 000000000..290b29570--- /dev/null+++ b/sdk/src/services/index.ts@@ -0,0 +1,8 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export {+ Ads, AdsAPI, createMockAdProvider,+ type AdProvider, type AdsHost, type MockAdProviderOptions,+} from './ads';+export { Share, ShareAPI, type ShareCard } from './share';+export { ServicesPlugin, servicesPlugin } from './servicesPlugin';diff --git a/sdk/src/services/servicesPlugin.ts b/sdk/src/services/servicesPlugin.tsnew file mode 100644index 000000000..ba572e4fe--- /dev/null+++ b/sdk/src/services/servicesPlugin.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file servicesPlugin.ts+ * @brief Installs the platform-services resources (Ads, Share).+ *+ * Resources only — no systems, no per-frame cost. The ads service is handed+ * the app's clock and the audio device as two narrow hooks, so a fullscreen+ * takeover can pause the game it covers without the service knowing the App.+ */+import type { App, Plugin } from '../app/app';+import { Audio } from '../audio';+import { Ads, AdsAPI } from './ads';+import { Share, ShareAPI } from './share';++export class ServicesPlugin implements Plugin {+ name = 'Services';++ build(app: App): void {+ app.insertResource(Ads, new AdsAPI({+ setPaused: (p) => app.setPaused(p),+ isPaused: () => app.isPaused(),+ // Resolved per call: the audio plugin builds in the same pass and+ // insertion order must not matter. A host with no audio device has+ // a Null backend behind the same API — suspending silence is free.+ suspendAudio: () => app.getResource(Audio)?.suspend(),+ resumeAudio: () => app.getResource(Audio)?.resume(),+ }));+ app.insertResource(Share, new ShareAPI());+ }+}++export const servicesPlugin = new ServicesPlugin();diff --git a/sdk/src/services/share.ts b/sdk/src/services/share.tsnew file mode 100644index 000000000..f26cb2e8c--- /dev/null+++ b/sdk/src/services/share.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file share.ts+ * @brief Host share sheet as an engine service.+ *+ * Two share surfaces exist on a mini-game host and a game should configure+ * both: ACTIVE (the game's own share button → `share()`) and PASSIVE (the+ * host's built-in menu → `setShareCard`). The card provider is asked at share+ * time, so it can answer with live state — a room code, the current score.+ * Fire-and-forget by design: no host reports whether the player shared.+ */+import { defineResource } from '../ecs/resource';+import { platformShare, platformCanShare, platformOnShareRequest } from '../platform';+import type { PlatformShareOptions } from '../platform/types';++export type ShareCard = PlatformShareOptions;++export class ShareAPI {+ private card_: ShareCard | (() => ShareCard) | null = null;+ private registered_ = false;++ /** Whether this platform can open a share sheet at all — what a menu reads+ * to hide its share button honestly (web and native cannot). */+ get available(): boolean {+ return platformCanShare();+ }++ /** Open the host's share sheet with `card`, falling back to the default+ * card when omitted. Returns whether a sheet could be opened at all. */+ share(card?: ShareCard): boolean {+ return platformShare(card ?? this.resolveCard_() ?? {});+ }++ /**+ * Set the DEFAULT card: what passive shares (the host's own menu) say, and+ * what `share()` without arguments uses. A function is asked at share time,+ * so the card can carry live state.+ */+ setShareCard(card: ShareCard | (() => ShareCard)): void {+ this.card_ = card;+ if (!this.registered_) {+ this.registered_ = platformOnShareRequest(() => this.resolveCard_() ?? {});+ }+ }++ private resolveCard_(): ShareCard | null {+ return typeof this.card_ === 'function' ? this.card_() : this.card_;+ }+}++export const Share = defineResource<ShareAPI>(null!, 'Share');diff --git a/sdk/tests/minigame-ads.test.ts b/sdk/tests/minigame-ads.test.tsnew file mode 100644index 000000000..11ae4f62e--- /dev/null+++ b/sdk/tests/minigame-ads.test.ts@@ -0,0 +1,108 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The mini-game adapter's ad/share family surface over a fake host+ * global: the load/show retry dance, onClose → completed semantics+ * (including the host that grants a reward without saying so), and+ * capability probing on a vendor without ads.+ */+import { describe, it, expect } from 'vitest';+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';+import type { MiniGameGlobal, MiniGameProfile, MiniGameRewardedVideoAd, MiniGameShareOptions } from '../src/platform/minigame/api';++function fakeRewarded(behavior: {+ showFailsUntilLoaded?: boolean;+ closeRes?: { isEnded: boolean } | undefined;+}): MiniGameRewardedVideoAd & { loads: number; shows: number; close(): void } {+ let closeCb: ((res?: { isEnded: boolean }) => void) | null = null;+ let loaded = !behavior.showFailsUntilLoaded;+ const ad = {+ loads: 0,+ shows: 0,+ load() { ad.loads++; loaded = true; return Promise.resolve(); },+ show() {+ ad.shows++;+ if (!loaded) return Promise.reject(new Error('no fill'));+ // The host closes the ad later; the test drives it via close().+ return Promise.resolve();+ },+ close() { closeCb?.(behavior.closeRes); },+ onLoad() {}, offLoad() {},+ onError() {}, offError() {},+ onClose(cb: (res?: { isEnded: boolean }) => void) { closeCb = cb; },+ offClose() { closeCb = null; },+ };+ return ad;+}++function adapterOver(globalPatch: Partial<MiniGameGlobal>): MiniGamePlatformAdapter {+ // The adapter touches only what a test exercises; the rest can be absent.+ const profile: MiniGameProfile = {+ id: 'wechat',+ hostLabel: 'Test',+ global: { getSystemInfoSync: () => ({ pixelRatio: 1, screenWidth: 1, screenHeight: 1, platform: 'devtools', language: 'zh_CN' }), ...globalPatch } as unknown as MiniGameGlobal,+ };+ return new MiniGamePlatformAdapter(profile);+}++describe('mini-game rewarded ads', () => {+ it('resolves completed=true when the host reports isEnded', async () => {+ const ad = fakeRewarded({ closeRes: { isEnded: true } });+ const adapter = adapterOver({ createRewardedVideoAd: () => ad });+ const unit = adapter.createRewardedAd('u')!;+ const shown = unit.show();+ ad.close();+ await expect(shown).resolves.toEqual({ completed: true });+ });++ it('resolves completed=false only on an explicit abandoned video', async () => {+ const ad = fakeRewarded({ closeRes: { isEnded: false } });+ const adapter = adapterOver({ createRewardedVideoAd: () => ad });+ const shown = adapter.createRewardedAd('u')!.show();+ ad.close();+ await expect(shown).resolves.toEqual({ completed: false });+ });++ it('treats a host that omits the close record as completed', async () => {+ const ad = fakeRewarded({ closeRes: undefined });+ const adapter = adapterOver({ createRewardedVideoAd: () => ad });+ const shown = adapter.createRewardedAd('u')!.show();+ ad.close();+ await expect(shown).resolves.toEqual({ completed: true });+ });++ it('retries the documented dance once: show → load → show', async () => {+ const ad = fakeRewarded({ showFailsUntilLoaded: true, closeRes: { isEnded: true } });+ const adapter = adapterOver({ createRewardedVideoAd: () => ad });+ const shown = adapter.createRewardedAd('u')!.show();+ // First show rejects (no fill) → load() → second show succeeds → host closes.+ await new Promise((r) => setTimeout(r, 0));+ ad.close();+ await expect(shown).resolves.toEqual({ completed: true });+ expect(ad.loads).toBe(1);+ expect(ad.shows).toBe(2);+ });++ it('answers null on a vendor without an ad API', () => {+ const adapter = adapterOver({});+ expect(adapter.createRewardedAd('u')).toBeNull();+ });+});++describe('mini-game share', () => {+ it('routes the card to the host share sheet', () => {+ const sent: MiniGameShareOptions[] = [];+ const adapter = adapterOver({ shareAppMessage: (o: MiniGameShareOptions) => { sent.push(o); } });+ adapter.share({ title: 'hi', query: 'room=7' });+ expect(sent).toEqual([{ title: 'hi', query: 'room=7' }]);+ });++ it('asks the passive provider at share time', () => {+ let provider: (() => MiniGameShareOptions) | null = null;+ const adapter = adapterOver({ onShareAppMessage: (cb: () => MiniGameShareOptions) => { provider = cb; } });+ let title = 'before';+ adapter.onShareRequest(() => ({ title }));+ title = 'after';+ expect(provider!().title).toBe('after');+ });+});diff --git a/sdk/tests/services-ads.test.ts b/sdk/tests/services-ads.test.tsnew file mode 100644index 000000000..4ec4e8d76--- /dev/null+++ b/sdk/tests/services-ads.test.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Platform services: the ads takeover ceremony and the share card.+ *+ * The contract under test is the part every game hand-rolls wrong: the game+ * clock pauses and the audio device suspends for exactly the span of the ad,+ * restored in EVERY exit path — and a game the developer paused before the ad+ * stays paused after it.+ */+import { describe, it, expect } from 'vitest';+import { AdsAPI, createMockAdProvider, type AdsHost, type AdProvider } from '../src/services/ads';+import { ShareAPI } from '../src/services/share';++function recordingHost(): AdsHost & { events: string[]; paused: boolean } {+ const h = {+ events: [] as string[],+ paused: false,+ setPaused(p: boolean) { h.paused = p; h.events.push(p ? 'pause' : 'unpause'); },+ isPaused() { return h.paused; },+ suspendAudio() { h.events.push('audio-off'); },+ resumeAudio() { h.events.push('audio-on'); },+ };+ return h;+}++describe('AdsAPI takeover ceremony', () => {+ it('pauses the clock and suspends audio for exactly the span of the ad', async () => {+ const host = recordingHost();+ const ads = new AdsAPI(host);+ ads.setProvider(createMockAdProvider({ durationMs: 1 }));++ const r = await ads.showRewarded('unit-1');+ expect(r.completed).toBe(true);+ expect(host.events).toEqual(['pause', 'audio-off', 'audio-on', 'unpause']);+ expect(host.paused).toBe(false);+ expect(ads.showing).toBe(false);+ });++ it('restores state when the ad errors (no fill twice)', async () => {+ const host = recordingHost();+ const ads = new AdsAPI(host);+ const failing: AdProvider = {+ createRewardedAd: () => ({+ preload: () => Promise.reject(new Error('no fill')),+ show: () => Promise.reject(new Error('no fill')),+ destroy: () => {},+ }),+ createInterstitialAd: () => { throw new Error('unused'); },+ };+ ads.setProvider(failing);++ await expect(ads.showRewarded('unit-1')).rejects.toThrow('no fill');+ expect(host.events).toEqual(['pause', 'audio-off', 'audio-on', 'unpause']);+ expect(host.paused).toBe(false);+ expect(ads.showing).toBe(false);+ });++ it('a game the developer paused stays paused after the ad', async () => {+ const host = recordingHost();+ host.paused = true;+ const ads = new AdsAPI(host);+ ads.setProvider(createMockAdProvider({ durationMs: 1 }));++ await ads.showRewarded('unit-1');+ // The ceremony restored what it found: no pause/unpause events at all.+ expect(host.events).toEqual(['audio-off', 'audio-on']);+ expect(host.paused).toBe(true);+ });++ it('reports an abandoned video as not completed', async () => {+ const ads = new AdsAPI(recordingHost());+ ads.setProvider(createMockAdProvider({ durationMs: 1, completed: false }));+ const r = await ads.showRewarded('unit-1');+ expect(r.completed).toBe(false);+ });++ it('rejects loud when no ad source exists, and says how to get one', async () => {+ const ads = new AdsAPI(recordingHost());+ expect(ads.available).toBe(false);+ await expect(ads.showRewarded('unit-1')).rejects.toThrow(/no ad source/);+ });++ it('caches units per id and drops them when the provider changes', async () => {+ let created = 0;+ const counting: AdProvider = {+ createRewardedAd: () => {+ created++;+ return { preload: () => Promise.resolve(), show: async () => ({ completed: true }), destroy: () => {} };+ },+ createInterstitialAd: () => { throw new Error('unused'); },+ };+ const ads = new AdsAPI(recordingHost());+ ads.setProvider(counting);+ await ads.showRewarded('a');+ await ads.showRewarded('a');+ expect(created).toBe(1);+ ads.setProvider(counting);+ await ads.showRewarded('a');+ expect(created).toBe(2);+ });+});++describe('ShareAPI', () => {+ it('is honestly unavailable off-platform, and share() says so', () => {+ const share = new ShareAPI();+ expect(share.available).toBe(false);+ expect(share.share({ title: 'hi' })).toBe(false);+ });++ it('resolves a functional default card at share time', () => {+ const share = new ShareAPI();+ let score = 1;+ share.setShareCard(() => ({ title: `score ${score}` }));+ score = 42;+ // Off-platform share() returns false, but the card resolution itself is+ // what passive shares consume — reach it through the resolver.+ expect((share as unknown as { resolveCard_(): { title: string } }).resolveCard_().title).toBe('score 42');+ });+});