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.

feat(crazygames): connect Web ads storage and host audio policy

yhh4644df2f84cb
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 0da65ba95..c59469608 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -68,6 +68,10 @@ jobs:
node pipeline/bin/estella.mjs export examples/mobile-controls --profile poki --wasm build/wasm/web --out output/poki-training-ci-export --json output/poki-training-ci-export.json
node pipeline/bin/estella.mjs export examples/mobile-controls --platform web --wasm build/wasm/web --out output/poki-training-ci-standalone --json output/poki-training-ci-standalone.json
node tools/tests/poki-training.e2e.mjs --dir output/poki-training-ci-export --standalone output/poki-training-ci-standalone --out output/poki-training-ci-check
+ - name: Check CrazyGames gameplay, storage and host mute in SDK mocks
+ run: |
+ node pipeline/bin/estella.mjs export examples/mobile-controls --profile crazygames --wasm build/wasm/web --out output/crazygames-training-ci-export --json output/crazygames-training-ci-export.json
+ node tools/tests/crazygames-training.e2e.mjs --dir output/crazygames-training-ci-export --out output/crazygames-training-ci-check
- name: Upload hash-bound local observations and screenshots
if: always()
uses: actions/upload-artifact@v7
@@ -82,6 +86,13 @@ jobs:
name: poki-training-local-mock-checks
path: output/poki-training-ci-*
retention-days: 3
+ - name: Upload CrazyGames training local observations and screenshots
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: crazygames-training-local-mock-checks
+ path: output/crazygames-training-ci-*
+ retention-days: 3
# The engine binaries, and nothing else: every gate below waits on this job, so
# a step here that no downstream job reads is a delay on all of them.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98575198d..8c6338a55 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,10 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **CrazyGames Web exports connect the official v3 SDK.** Channel profiles initialize loading notifications, rewarded and midgame ads, SDK Data storage and host audio mute. Failed initialization disables host services without blocking training; save errors remain explicit, and engine storage clearing preserves other publisher data. Unused achievement services defer their storage read so unavailable saving does not block startup. The editor offers channel selection and the Mobile Controls profile reports authored gameplay transitions. Leaderboards and official platform/device acceptance remain pending.
+
### Changed
- **Poki training documents the official Inspector URL workflow.** A localhost export can be checked with the real SDK without starting the editor. The guide distinguishes observed SDK initialization, loading, gameplay and reward events from the remaining manual QA, device acceptance and production ad behavior.
diff --git a/desktop b/desktop
index 5154e0f67..f90131c03 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 5154e0f678ef716c4e024746c51286392b9e93f0
+Subproject commit f90131c03dbb90d3b8eb2275ffdce9712b07d179
diff --git a/examples/mobile-controls/README.md b/examples/mobile-controls/README.md
index e1f53f25a..8ade6b57d 100644
--- a/examples/mobile-controls/README.md
+++ b/examples/mobile-controls/README.md
@@ -83,3 +83,33 @@ resuming, watching a rewarded ad, completing the round and replaying. Let the
SDK's test ad finish naturally; no callbacks are replaced by this workflow.
The SDK Basics checklist and the other QA modules must be evaluated individually.
A clear event log is not full platform or device acceptance.
+
+## CrazyGames Web training profile
+
+Export with `node pipeline/bin/estella.mjs export examples/mobile-controls
+--profile crazygames --out output/crazygames-training-web`. This profile uses
+the same authored room and START / PAUSE / REPLAY / WATCH AD controls. Gameplay
+events go to `CrazyGames.SDK.game`; focus changes do not emit gameplay events,
+because the SDK handles focus itself. Credits in this training example remain
+session-only.
+
+The export host awaits the official v3 SDK, reports loading, and connects the
+existing Ads service to rewarded and midgame callbacks. Only `adFinished`
+grants a rewarded credit. SDK initialization failure leaves training playable
+with ads unavailable. Host audio mute overrides game audio and video controls
+without changing the player's own mute or suspension preference.
+
+On this channel the engine's `Storage` API uses SDK Data for both guests and
+signed-in players. Enable Progress Save in the CrazyGames submission settings.
+Disabled saving, invalid stored data and SDK failures surface as errors; there
+is no silent localStorage fallback. Engine keys share the `estella.storage.v1`
+envelope, and `Storage.clear()` preserves other publisher data. The SDK's
+overall 1 MB limit still applies. A synchronous save is not acknowledgment of
+cloud backup or proof of cross-account restoration.
+
+Leaderboard integration, official platform QA and physical-device acceptance
+remain separate work. This profile does not claim those checks are complete.
+See the official [SDK introduction](https://docs.crazygames.com/sdk/intro/),
+[game lifecycle](https://docs.crazygames.com/sdk/game/),
+[video ads](https://docs.crazygames.com/sdk/video-ads/) and
+[Data module](https://docs.crazygames.com/sdk/data/).
diff --git a/examples/mobile-controls/project.esproject b/examples/mobile-controls/project.esproject
index 9696cd31b..6b3537fc7 100644
--- a/examples/mobile-controls/project.esproject
+++ b/examples/mobile-controls/project.esproject
@@ -12,6 +12,14 @@
"spineVersion": "none",
"packaging": {
"profiles": {
+ "crazygames": {
+ "platform": "web",
+ "platforms": {
+ "web": {
+ "channel": "crazygames"
+ }
+ }
+ },
"poki": {
"platform": "web",
"platforms": {
diff --git a/examples/mobile-controls/src/main.ts b/examples/mobile-controls/src/main.ts
index ddc101c9f..af1a2a094 100644
--- a/examples/mobile-controls/src/main.ts
+++ b/examples/mobile-controls/src/main.ts
@@ -4,7 +4,7 @@ import {
UIEvents, Text, Name, UINode, UIPositionType, spawnUIEntity, createButton, px, Device,
Ads, type World, type Entity, type DeviceResult,
} from 'esengine';
-import { setupPokiTraining } from './pokiTrainingUI';
+import { setupWebTraining } from './pokiTrainingUI';
import type { TrainingSession } from './pokiTraining';
const controls = new InputMap({ Move: Axis2D(Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD'), Virtual('move')),
@@ -76,7 +76,7 @@ addStartupSystem(defineSystem([Res(UIEvents), Res(Ads), GetWorld()], (events, ad
if (player !== null && target !== null) {
const playerStart = { ...world.get(player, Transform).position };
const targetStart = { ...world.get(target, Transform).position };
- trainer = setupPokiTraining(world, events, canvas, ads, () => {
+ trainer = setupWebTraining(world, events, canvas, ads, () => {
hits = 0; misses = 0; hitFlash = 0; recoil = 0;
for (const [entity, position] of [[player, playerStart], [target, targetStart]] as const) {
const transform = world.get(entity, Transform); transform.position = { ...position };
diff --git a/examples/mobile-controls/src/pokiTraining.ts b/examples/mobile-controls/src/pokiTraining.ts
index 0615ec11b..7def23db4 100644
--- a/examples/mobile-controls/src/pokiTraining.ts
+++ b/examples/mobile-controls/src/pokiTraining.ts
@@ -20,14 +20,14 @@ export class TrainingSession {
message = 'Press START to begin a three-hit training round.';
private hidden = false;
private disposed = false;
- constructor(private readonly ads: TrainingAds, private readonly hooks: TrainingHooks) {}
+ constructor(private readonly ads: TrainingAds, private readonly hooks: TrainingHooks, private readonly adUnit = 'poki') {}
async begin(): Promise<void> {
if (this.disposed || this.hidden || this.phase === 'playing' || this.phase === 'ad') return;
const previous = this.phase;
if (previous !== 'menu' && this.ads.available) {
this.phase = 'ad'; this.message = 'Commercial break. Training is paused.'; this.hooks.changed();
- try { await this.ads.showInterstitial('poki'); }
+ try { await this.ads.showInterstitial(this.adUnit); }
catch { this.message = 'No commercial available. Continue training.'; }
}
if (this.disposed) return;
@@ -59,7 +59,7 @@ export class TrainingSession {
if (previous === 'playing') this.hooks.gameplayStop();
this.phase = 'ad'; this.message = 'Rewarded break. Watch to earn one training credit.'; this.hooks.changed();
try {
- const result = await this.ads.showRewarded('poki');
+ const result = await this.ads.showRewarded(this.adUnit);
if (this.disposed) return;
if (result.completed) { this.credits++; this.message = 'Reward earned: +1 training credit.'; }
else this.message = 'Video not completed. No reward granted.';
diff --git a/examples/mobile-controls/src/pokiTrainingUI.ts b/examples/mobile-controls/src/pokiTrainingUI.ts
index e668ee122..b6eaf8751 100644
--- a/examples/mobile-controls/src/pokiTrainingUI.ts
+++ b/examples/mobile-controls/src/pokiTrainingUI.ts
@@ -6,15 +6,19 @@ import { TrainingSession } from './pokiTraining';
type ButtonOptions = Parameters<typeof createButton>[0];
interface PokiGameplay { gameplayStart(): void; gameplayStop(): void }
-export function setupPokiTraining(
+export function setupWebTraining(
world: ButtonOptions['world'], events: ButtonOptions['events'], parent: NonNullable<ButtonOptions['parent']>,
ads: AdsAPI, reset: () => void, refresh: () => void,
): TrainingSession | null {
- if (typeof document === 'undefined' || document.documentElement?.dataset?.webChannel !== 'poki') return null;
+ if (typeof document === 'undefined') return null;
+ const channel = document.documentElement?.dataset?.webChannel;
+ if (channel !== 'poki' && channel !== 'crazygames') return null;
const notify = (event: keyof PokiGameplay): void => {
- const sdk = (globalThis as unknown as { PokiSDK?: PokiGameplay }).PokiSDK;
+ if (channel === 'crazygames' && document.documentElement.dataset.webSdkReady !== 'true') return;
+ const hosts = globalThis as unknown as { PokiSDK?: PokiGameplay; CrazyGames?: { SDK?: { game?: PokiGameplay } } };
+ const sdk = channel === 'poki' ? hosts.PokiSDK : hosts.CrazyGames?.SDK?.game;
try { sdk?.[event](); }
- catch (error) { console.warn('[training] Poki gameplay event failed', event, error); }
+ catch (error) { console.warn('[training] Gameplay event failed', channel, event, error); }
};
const controls: Array<{ button: ReturnType<typeof createButton>; label: ReturnType<typeof spawnUIEntity> }> = [];
const update = (): void => {
@@ -30,7 +34,7 @@ export function setupPokiTraining(
};
const session = new TrainingSession(ads, {
gameplayStart: () => notify('gameplayStart'), gameplayStop: () => notify('gameplayStop'), reset, changed: update,
- });
+ }, channel);
const actions = [() => { void session.begin(); }, () => session.pause(), () => { void session.reward(); }];
for (let index = 0; index < 3; index++) {
const button = createButton({ world, events, parent, userGesture: true,
@@ -43,9 +47,12 @@ export function setupPokiTraining(
}
const onVisibility = () => session.visibility(document.hidden);
const onHide = () => session.visibility(true);
- document.addEventListener('visibilitychange', onVisibility);
- window.addEventListener('pagehide', onHide);
- window.addEventListener('pageshow', onVisibility);
+ // CrazyGames manages focus itself; its gameplay events describe game state only.
+ if (channel === 'poki') {
+ document.addEventListener('visibilitychange', onVisibility);
+ window.addEventListener('pagehide', onHide);
+ window.addEventListener('pageshow', onVisibility);
+ }
const offDespawn = world.onDespawn(entity => {
if (entity !== parent) return;
document.removeEventListener('visibilitychange', onVisibility);
@@ -54,7 +61,7 @@ export function setupPokiTraining(
offDespawn(); session.dispose();
controls.forEach(({ button }) => button.dispose());
});
- session.visibility(document.hidden);
+ if (channel === 'poki') session.visibility(document.hidden);
update();
return session;
}
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index 7b227da68..4dca72884 100644
--- a/pipeline/src/export/exportGame.ts
+++ b/pipeline/src/export/exportGame.ts
@@ -338,7 +338,7 @@ function externalEngineImports(metafile: { outputs: Record<string, { imports?: {
* for desktop (the Electron shell sizes its own window). */
function indexHtml(
title: string, map: EngineImportMap, look: SplashLook, orientation?: ScreenOrientation,
- debugChannel?: DebugChannelConfig, webChannel?: 'poki',
+ debugChannel?: DebugChannelConfig, webChannel?: 'poki' | 'crazygames',
): string {
// The editor a development build dials is the one address beyond 'self' the
// page may connect to; a build without a channel lists none.
@@ -347,13 +347,13 @@ function indexHtml(
const inlineScripts = [map.cspHash, ...(orientation ? [orientationLockCspHash(orientation)] : [])]
.map((h) => `'${h}'`)
.join(' ');
- // Poki owns third-party ad frames, scripts and requests; its host policy is
+ // Channel SDKs own third-party ad frames, scripts and requests; their policy is
// incompatible with the standalone page's same-origin resource restriction.
- const channelPolicy = webChannel === 'poki'
+ const channelPolicy = webChannel === 'poki' || webChannel === 'crazygames'
? `default-src 'self' data: blob: https:; script-src 'self' 'unsafe-eval' blob: https: ${inlineScripts}; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: blob: https:; connect-src 'self' data: blob: https:${connect}; frame-src https:; media-src 'self' data: blob: https:; worker-src 'self' blob:;`
: `default-src 'self'; script-src 'self' 'unsafe-eval' blob: ${inlineScripts}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' data: blob:${connect}; worker-src 'self' blob:;`;
return `<!doctype html>
-<html lang="en" data-web-channel="${webChannel === 'poki' ? 'poki' : 'standalone'}">
+<html lang="en" data-web-channel="${webChannel === 'poki' ? 'poki' : webChannel === 'crazygames' ? 'crazygames' : 'standalone'}">
<head>
<meta charset="UTF-8" />
<meta
@@ -362,7 +362,7 @@ function indexHtml(
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>${title}</title>
- ${webChannel === 'poki' ? '<script src="https://game-cdn.poki.com/scripts/v2/poki-sdk.js"></script>' : ''}
+ ${webChannel === 'poki' ? '<script src="https://game-cdn.poki.com/scripts/v2/poki-sdk.js"></script>' : webChannel === 'crazygames' ? '<script src="https://sdk.crazygames.com/crazygames-sdk-v3.js"></script>' : ''}
<script type="importmap">${map.json}</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
@@ -477,7 +477,7 @@ export interface ExportGameOptions {
/** Project-relative startup entry (e.g. src/main.ts) → bundled to scripts.mjs. */
scriptsEntry?: string;
/** Browser distribution channel; standalone leaves the original Web policy intact. */
- webChannel?: 'poki';
+ webChannel?: 'poki' | 'crazygames';
sdkDistDir: string;
/** The engine runtime to copy. */
wasmDir: string;
diff --git a/pipeline/src/export/projectExportOptions.ts b/pipeline/src/export/projectExportOptions.ts
index 7b16947e2..0b38b4e7c 100644
--- a/pipeline/src/export/projectExportOptions.ts
+++ b/pipeline/src/export/projectExportOptions.ts
@@ -106,7 +106,7 @@ export async function projectExportOptions(
...(platform === 'android' && plat?.android?.releaseKey
? { androidKey: () => androidReleaseKey(root, plat.android!.releaseKey!, secrets.androidKeyPassphrase) }
: {}),
- ...(platform === 'web' && plat?.web?.channel === 'poki' ? { webChannel: 'poki' as const } : {}),
+ ...(platform === 'web' && (plat?.web?.channel === 'poki' || plat?.web?.channel === 'crazygames') ? { webChannel: plat.web.channel } : {}),
desktopProductName: plat?.desktop?.productName,
desktopChannel: plat?.desktop?.channel,
steam: plat?.desktop?.steam,
diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.ts
index e8d19e97a..7a4dccf2b 100644
--- a/pipeline/src/project/format.ts
+++ b/pipeline/src/project/format.ts
@@ -409,7 +409,7 @@ export interface ProjectPackaging {
/** Per-platform packaging config: each target's slice of the app identity, plus
* whatever only it has (a WeChat appid, an Android versionCode). */
platforms?: {
- web?: { channel?: 'standalone' | 'poki' };
+ web?: { channel?: 'standalone' | 'poki' | 'crazygames' };
wechat?: WeChatPackaging;
douyin?: MiniGamePackaging;
bilibili?: MiniGamePackaging;
@@ -911,10 +911,10 @@ export function parseManifest(raw: unknown): ProjectManifest {
const platforms: NonNullable<ProjectPackaging['platforms']> = {};
const web = pl.web as Record<string, unknown> | undefined;
if (web && typeof web === 'object') {
- if (web.channel !== undefined && web.channel !== 'standalone' && web.channel !== 'poki') {
- throw new Error('packaging.platforms.web.channel must be standalone or poki');
+ if (web.channel !== undefined && web.channel !== 'standalone' && web.channel !== 'poki' && web.channel !== 'crazygames') {
+ throw new Error('packaging.platforms.web.channel must be standalone, poki or crazygames');
}
- if (web.channel) platforms.web = { channel: web.channel as 'standalone' | 'poki' };
+ if (web.channel) platforms.web = { channel: web.channel as 'standalone' | 'poki' | 'crazygames' };
}
const wx = pl.wechat as Record<string, unknown> | undefined;
if (wx && typeof wx === 'object') {
diff --git a/pipeline/src/runtime/crazyGamesProfile.ts b/pipeline/src/runtime/crazyGamesProfile.ts
new file mode 100644
index 000000000..8fda6588d
--- /dev/null
+++ b/pipeline/src/runtime/crazyGamesProfile.ts
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type { AdProvider, PlatformAdapter } from 'esengine';
+
+export interface CrazyGamesData {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+ removeItem(key: string): void;
+}
+export interface CrazyGamesSdk {
+ init(): Promise<void>;
+ ad: { requestAd(type: 'rewarded' | 'midgame', callbacks: {
+ adStarted(): void; adFinished(): void; adError(error: unknown): void;
+ }): void };
+ data: CrazyGamesData;
+ game: {
+ loadingStart(): void; loadingStop(): void;
+ settings: { muteAudio?: boolean };
+ addSettingsChangeListener(listener: (settings: { muteAudio?: boolean }) => void): void;
+ removeSettingsChangeListener(listener: (settings: { muteAudio?: boolean }) => void): void;
+ };
+}
+
+export function crazyGamesAdProvider(sdk: CrazyGamesSdk): AdProvider {
+ const unit = <T>(type: 'rewarded' | 'midgame', finish: () => T) => {
+ let destroyed = false;
+ return {
+ preload: async () => { if (destroyed) throw new Error('CrazyGames ad unit destroyed'); },
+ show: () => new Promise<T>((resolve, reject) => {
+ if (destroyed) { reject(new Error('CrazyGames ad unit destroyed')); return; }
+ let settled = false;
+ const fail = (error: unknown) => {
+ if (settled) return; settled = true;
+ reject(error instanceof Error ? error : new Error('CrazyGames ad request failed'));
+ };
+ try {
+ sdk.ad.requestAd(type, {
+ adStarted() {}, // The existing Ads service already holds the takeover.
+ adFinished() { if (!settled) { settled = true; resolve(finish()); } },
+ adError: fail,
+ });
+ } catch (error) { fail(error); }
+ }),
+ destroy() { destroyed = true; },
+ };
+ };
+ return {
+ createRewardedAd: () => unit('rewarded', () => ({ completed: true })),
+ createInterstitialAd: () => unit('midgame', () => undefined),
+ };
+}
+
+export const CRAZYGAMES_STORAGE_KEY = 'estella.storage.v1';
+type StorageAdapter = Pick<PlatformAdapter, 'getStorageItem' | 'setStorageItem' | 'removeStorageItem' | 'clearStorage'>;
+
+/** One engine-owned envelope supports prefix clearing without deleting other SDK data. */
+export function crazyGamesStorage(data: CrazyGamesData | undefined): StorageAdapter {
+ const requireData = (): CrazyGamesData => {
+ if (!data) throw new Error('CrazyGames storage unavailable; no local fallback was written');
+ return data;
+ };
+ const read = (): Record<string, string> => {
+ const raw = requireData().getItem(CRAZYGAMES_STORAGE_KEY);
+ const parsed: unknown = raw === null ? {} : JSON.parse(raw);
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)
+ || Object.values(parsed).some(value => typeof value !== 'string')) {
+ throw new Error('Invalid CrazyGames engine storage envelope');
+ }
+ return Object.assign(Object.create(null) as Record<string, string>, parsed);
+ };
+ const write = (values: Record<string, string>): void => {
+ const value = JSON.stringify(values);
+ if (new TextEncoder().encode(value).length + CRAZYGAMES_STORAGE_KEY.length > 1_000_000) {
+ throw new Error('CrazyGames engine storage envelope exceeds 1 MB');
+ }
+ requireData().setItem(CRAZYGAMES_STORAGE_KEY, value);
+ };
+ return {
+ getStorageItem(key) { return read()[key] ?? null; },
+ setStorageItem(key, value) { const values = read(); values[key] = value; write(values); },
+ removeStorageItem(key) { const values = read(); delete values[key]; write(values); },
+ clearStorage(prefix) {
+ const values = read();
+ for (const key of Object.keys(values)) if (key.startsWith(prefix)) delete values[key];
+ write(values);
+ },
+ };
+}
+
+export async function initializeCrazyGames(
+ sdk: CrazyGamesSdk | undefined, warn: (message: string, error?: unknown) => void, timeoutMs = 10000,
+) {
+ let initialized = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ if (!sdk) warn('[CrazyGames] SDK unavailable; continuing without ads or SDK storage');
+ else {
+ try {
+ await Promise.race([sdk.init(), new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('CrazyGames initialization timed out')), timeoutMs);
+ })]);
+ initialized = true;
+ sdk.game.loadingStart();
+ } catch (error) { warn('[CrazyGames] Initialization/loading notification failed', error); }
+ finally { if (timer !== undefined) clearTimeout(timer); }
+ }
+ let loaded = false;
+ return {
+ provider: initialized && sdk ? crazyGamesAdProvider(sdk) : null,
+ storage: crazyGamesStorage(initialized ? sdk?.data : undefined),
+ onAudioMute(callback: (muted: boolean) => void): () => void {
+ if (!initialized || !sdk) { callback(false); return () => {}; }
+ let active = true;
+ const listener = (settings: { muteAudio?: boolean }) => { if (active) callback(settings.muteAudio === true); };
+ listener(sdk.game.settings);
+ try { sdk.game.addSettingsChangeListener(listener); }
+ catch (error) { warn('[CrazyGames] Settings listener unavailable', error); }
+ return () => {
+ active = false;
+ try { sdk.game.removeSettingsChangeListener(listener); }
+ catch (error) { warn('[CrazyGames] Settings listener cleanup failed', error); }
+ };
+ },
+ loaded() {
+ if (loaded || !initialized || !sdk) return;
+ loaded = true;
+ try { sdk.game.loadingStop(); } catch (error) { warn('[CrazyGames] Loading notification failed', error); }
+ },
+ };
+}
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index dfdee6e67..39f3b92f5 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -12,7 +12,7 @@
* (shared with the play realm's import-map work).
*/
import {
- createWebApp, setEditorMode, setPlayMode, Assets, Ads,
+ createWebApp, setEditorMode, setPlayMode, Assets, Ads, extendPlatform,
indexPackagedManifest, createPackagedAssetSource, applyAssetRefResolvers, initRuntime,
HttpBackend, fetchDecodePixels, registerPackagedSideModules,
packagedAppOptions, packagedRuntimeInit, Transform, SceneManager, UINode,
@@ -61,6 +61,7 @@ import type { ESEngineModule } from 'esengine/wasm';
import { attachSplash, type Splash } from '../export/splash';
import { countedStream, engineDownloadTotal } from './engineDownload';
import { initializePoki, type PokiSdk } from './pokiProfile';
+import { initializeCrazyGames, type CrazyGamesSdk } from './crazyGamesProfile';
/**
* Fetch the engine binary through a stream we can count, and hand the SAME
@@ -110,6 +111,13 @@ async function boot(): Promise<void> {
const poki = cfg.webChannel === 'poki'
? await initializePoki((window as unknown as { PokiSDK?: PokiSdk }).PokiSDK, (message, error) => console.warn(message, error))
: null;
+ const crazyGames = cfg.webChannel === 'crazygames'
+ ? await initializeCrazyGames((window as unknown as { CrazyGames?: { SDK: CrazyGamesSdk } }).CrazyGames?.SDK, (message, error) => console.warn(message, error))
+ : null;
+ if (crazyGames) {
+ extendPlatform({ ...crazyGames.storage, onAudioMute: crazyGames.onAudioMute });
+ document.documentElement.dataset.webSdkReady = String(crazyGames.provider !== null);
+ }
// Before the engine boots, so a boot that fails is still heard by the editor.
if (cfg.debugChannel) startDebugChannel(cfg.debugChannel);
@@ -207,6 +215,7 @@ async function boot(): Promise<void> {
wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
});
if (poki?.provider) app.getResource(Ads)?.setProvider(poki.provider);
+ if (crazyGames?.provider) app.getResource(Ads)?.setProvider(crazyGames.provider);
splash?.reach('app');
setEditorMode(false);
setPlayMode(true);
@@ -896,6 +905,7 @@ async function boot(): Promise<void> {
...packagedRuntimeInit(cfg),
});
poki?.loaded();
+ crazyGames?.loaded();
splash?.reach('assets');
// Before run(), not after: run() may hand control to the emscripten loop and
// never return, and the fade is what the first frames should arrive through.
diff --git a/pipeline/tests/crazygames-profile.test.ts b/pipeline/tests/crazygames-profile.test.ts
new file mode 100644
index 000000000..7f433aa72
--- /dev/null
+++ b/pipeline/tests/crazygames-profile.test.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, vi } from 'vitest';
+import { crazyGamesAdProvider, crazyGamesStorage, initializeCrazyGames, CRAZYGAMES_STORAGE_KEY, type CrazyGamesSdk } from '../src/runtime/crazyGamesProfile';
+import { parseManifest } from '../src/project/format';
+import { projectExportOptions } from '../src/export/projectExportOptions';
+
+function fixture() {
+ const values = new Map<string, string>();
+ const callbacks: Array<Parameters<CrazyGamesSdk['ad']['requestAd']>[1]> = [];
+ const listeners = new Set<(settings: { muteAudio?: boolean }) => void>();
+ const sdk: CrazyGamesSdk = {
+ init: vi.fn(async () => {}),
+ ad: { requestAd: vi.fn((_type, callback) => { callbacks.push(callback); }) },
+ data: { getItem: key => values.get(key) ?? null, setItem: (key, value) => { values.set(key, value); }, removeItem: key => { values.delete(key); } },
+ game: { loadingStart: vi.fn(), loadingStop: vi.fn(), settings: { muteAudio: true },
+ addSettingsChangeListener: listener => { listeners.add(listener); }, removeSettingsChangeListener: listener => { listeners.delete(listener); } },
+ };
+ return { sdk, values, callbacks, listeners };
+}
+
+describe('CrazyGames channel adapter', () => {
+ it('preserves the named Web channel and rejects misspellings', async () => {
+ const manifest = parseManifest({ name: 'Game', packaging: { profiles: { cg: { platform: 'web', platforms: { web: { channel: 'crazygames' } } } } } });
+ expect((await projectExportOptions(process.cwd(), manifest, 'web', 'cg')).webChannel).toBe('crazygames');
+ expect(() => parseManifest({ name: 'Game', packaging: { platforms: { web: { channel: 'crazygams' } } } })).toThrow('web.channel');
+ });
+ it('initializes before loading events, then reports loading stop once', async () => {
+ const { sdk } = fixture(); const session = await initializeCrazyGames(sdk, vi.fn());
+ expect(sdk.init).toHaveBeenCalledTimes(1); expect(sdk.game.loadingStart).toHaveBeenCalledTimes(1);
+ expect(sdk.game.loadingStop).not.toHaveBeenCalled(); session.loaded(); session.loaded();
+ expect(sdk.game.loadingStop).toHaveBeenCalledTimes(1); expect(session.provider).not.toBeNull();
+ });
+ it('SDK failure exposes neither ads nor a local-save fallback', async () => {
+ const { sdk } = fixture(); sdk.init = async () => { throw new Error('blocked'); };
+ const session = await initializeCrazyGames(sdk, vi.fn());
+ expect(session.provider).toBeNull(); expect(() => session.storage.setStorageItem('save', '1')).toThrow('unavailable');
+ session.loaded(); expect(sdk.game.loadingStart).not.toHaveBeenCalled(); expect(sdk.game.loadingStop).not.toHaveBeenCalled();
+ });
+ it('times out without activating a provider on late SDK initialization', async () => {
+ vi.useFakeTimers();
+ try {
+ const { sdk } = fixture(); let finish!: () => void;
+ sdk.init = () => new Promise<void>(resolve => { finish = resolve; });
+ const pending = initializeCrazyGames(sdk, vi.fn(), 50); await vi.advanceTimersByTimeAsync(51);
+ const session = await pending; finish(); await Promise.resolve();
+ expect(session.provider).toBeNull(); expect(() => session.storage.getStorageItem('save')).toThrow('unavailable');
+ } finally { vi.useRealTimers(); }
+ });
+ it('grants rewards only after adFinished and ignores repeated callbacks', async () => {
+ const { sdk, callbacks } = fixture(); const ad = crazyGamesAdProvider(sdk).createRewardedAd('ignored');
+ let finished = false; const showing = ad.show().then(result => { finished = true; return result; });
+ expect(sdk.ad.requestAd).toHaveBeenCalledWith('rewarded', expect.any(Object));
+ callbacks[0].adStarted(); await Promise.resolve(); expect(finished).toBe(false);
+ callbacks[0].adFinished(); callbacks[0].adError(new Error('late')); callbacks[0].adFinished();
+ expect(await showing).toEqual({ completed: true });
+ });
+ it('maps midgame completion and ad errors without inventing a reward', async () => {
+ const { sdk, callbacks } = fixture(); const provider = crazyGamesAdProvider(sdk);
+ const commercial = provider.createInterstitialAd('ignored').show(); callbacks[0].adFinished(); await commercial;
+ expect(sdk.ad.requestAd).toHaveBeenCalledWith('midgame', expect.any(Object));
+ const reward = provider.createRewardedAd('ignored').show(); const rejected = expect(reward).rejects.toThrow('failed');
+ callbacks[1].adError({ code: 'no-fill' }); callbacks[1].adFinished(); await rejected;
+ });
+ it('preserves synchronous request errors and rejects destroyed units', async () => {
+ const { sdk } = fixture(); sdk.ad.requestAd = () => { throw new Error('request rejected'); };
+ const ad = crazyGamesAdProvider(sdk).createRewardedAd('ignored');
+ await expect(ad.show()).rejects.toThrow('request rejected'); ad.destroy();
+ await expect(ad.preload()).rejects.toThrow('destroyed'); await expect(ad.show()).rejects.toThrow('destroyed');
+ });
+ it('destroying an active unit does not prematurely end its takeover', async () => {
+ const { sdk, callbacks } = fixture(); const ad = crazyGamesAdProvider(sdk).createInterstitialAd('ignored');
+ let done = false; const pending = ad.show().then(() => { done = true; }); ad.destroy();
+ await Promise.resolve(); expect(done).toBe(false); callbacks[0].adFinished(); await pending;
+ });
+ it('applies initial mute and removes the listener before allowing stale emissions', async () => {
+ const { sdk, listeners } = fixture(); const session = await initializeCrazyGames(sdk, vi.fn());
+ const muted: boolean[] = []; const off = session.onAudioMute(value => muted.push(value));
+ const listener = [...listeners][0]; listener({ muteAudio: false }); off(); listener({ muteAudio: true });
+ expect(muted).toEqual([true, false]); expect(listeners.size).toBe(0);
+ });
+});
+
+describe('CrazyGames SDK data envelope', () => {
+ it('persists strings, reads a fresh SDK state and never clears unrelated SDK data', () => {
+ const { sdk, values } = fixture(); values.set('publisher.other', 'keep');
+ const storage = crazyGamesStorage(sdk.data); storage.setStorageItem('esengine:score', '42'); storage.setStorageItem('asset-cache', 'keep');
+ expect(crazyGamesStorage(sdk.data).getStorageItem('esengine:score')).toBe('42');
+ storage.clearStorage('esengine:'); expect(storage.getStorageItem('esengine:score')).toBeNull();
+ expect(storage.getStorageItem('asset-cache')).toBe('keep'); expect(values.get('publisher.other')).toBe('keep');
+ storage.removeStorageItem('asset-cache'); expect(storage.getStorageItem('asset-cache')).toBeNull();
+ });
+ it('supports prototype-like keys without changing the object prototype', () => {
+ const { sdk } = fixture(); const storage = crazyGamesStorage(sdk.data);
+ storage.setStorageItem('__proto__', 'safe'); storage.setStorageItem('constructor', 'also safe');
+ expect(storage.getStorageItem('__proto__')).toBe('safe'); expect(storage.getStorageItem('constructor')).toBe('also safe');
+ expect(storage.getStorageItem('toString')).toBeNull();
+ });
+ for (const corrupt of ['bad JSON', '[]', '{"score":10}', 'null']) {
+ it(`does not overwrite corrupt data: ${corrupt}`, () => {
+ const { sdk, values } = fixture(); values.set(CRAZYGAMES_STORAGE_KEY, corrupt);
+ expect(() => crazyGamesStorage(sdk.data).setStorageItem('score', '1')).toThrow();
+ expect(values.get(CRAZYGAMES_STORAGE_KEY)).toBe(corrupt);
+ });
+ }
+ it('rejects an oversized UTF-8 envelope before touching the SDK', () => {
+ const { sdk, values } = fixture(); const storage = crazyGamesStorage(sdk.data); storage.setStorageItem('score', '1');
+ const before = values.get(CRAZYGAMES_STORAGE_KEY);
+ expect(() => storage.setStorageItem('large', '汉'.repeat(340000))).toThrow('1 MB');
+ expect(values.get(CRAZYGAMES_STORAGE_KEY)).toBe(before);
+ });
+ it('surfaces disabled saving instead of silently writing localStorage', () => {
+ const { sdk } = fixture(); sdk.data.setItem = () => { throw new Error('Progress Save disabled'); };
+ expect(() => crazyGamesStorage(sdk.data).setStorageItem('save', '1')).toThrow('Progress Save disabled');
+ });
+});
diff --git a/pipeline/tests/export-splash.test.ts b/pipeline/tests/export-splash.test.ts
index 59ee3ce46..6d25ffea1 100644
--- a/pipeline/tests/export-splash.test.ts
+++ b/pipeline/tests/export-splash.test.ts
@@ -50,7 +50,7 @@ beforeAll(() => {
afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
/** Export for web and hand back the page plus whatever the build said about it. */
-async function page(splash?: ProjectPackaging['splash'], webChannel?: 'poki'): Promise<{ html: string; warnings: string[]; splashBytes?: number }> {
+async function page(splash?: ProjectPackaging['splash'], webChannel?: 'poki' | 'crazygames'): Promise<{ html: string; warnings: string[]; splashBytes?: number }> {
const outDir = path.join(root, `dist-${Math.random().toString(36).slice(2)}`);
const res = await exportGame({
root,
@@ -130,6 +130,16 @@ describe('the exported page’s start screen', () => {
describe('Poki host page', () => {
+ it('loads CrazyGames v3 before the game without injecting Poki', async () => {
+ const { html } = await page(undefined, 'crazygames');
+ const script = '<script src="https://sdk.crazygames.com/crazygames-sdk-v3.js"></script>';
+ expect(html.indexOf(script)).toBeGreaterThan(html.indexOf('<head>'));
+ expect(html.indexOf(script)).toBeLessThan(html.indexOf('</head>'));
+ expect(html.indexOf(script)).toBeLessThan(html.indexOf('src="./game.js"'));
+ expect(html).toContain('data-web-channel="crazygames"');
+ expect(html).toContain('frame-src https:');
+ expect(html).not.toContain('poki-sdk');
+ });
it('loads the official SDK in the head before the game, with its channel policy', async () => {
const { html } = await page(undefined, 'poki');
const script = '<script src="https://game-cdn.poki.com/scripts/v2/poki-sdk.js"></script>';
@@ -144,6 +154,7 @@ describe('Poki host page', () => {
const { html } = await page();
expect(html).toContain('data-web-channel="standalone"');
expect(html).not.toContain('poki-sdk');
+ expect(html).not.toContain('crazygames-sdk');
expect(html).not.toContain('frame-src https:');
expect(html).toContain("default-src 'self';");
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 58f0c0899..cde5f8e21 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5562,7 +5562,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | undefined
+webChannel: "poki" | "crazygames" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -5992,6 +5992,7 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onAudioMute: ((handler: (muted: boolean) => void) => () => void) | undefined
onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index cfadedcf8..60c72fcba 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5765,7 +5765,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | undefined
+webChannel: "poki" | "crazygames" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -6195,6 +6195,7 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onAudioMute: ((handler: (muted: boolean) => void) => () => void) | undefined
onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index df483c4f3..409a01c6a 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -5557,7 +5557,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | undefined
+webChannel: "poki" | "crazygames" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -5987,6 +5987,7 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onAudioMute: ((handler: (muted: boolean) => void) => () => void) | undefined
onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 5591eb80b..4523cc99d 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5850,7 +5850,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | undefined
+webChannel: "poki" | "crazygames" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -6280,6 +6280,7 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onAudioMute: ((handler: (muted: boolean) => void) => () => void) | undefined
onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index cff5da43e..71a59987a 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5564,7 +5564,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | undefined
+webChannel: "poki" | "crazygames" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -5994,6 +5994,7 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onAudioMute: ((handler: (muted: boolean) => void) => () => void) | undefined
onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.ts
index 1f28930da..b9bb441c7 100644
--- a/sdk/src/audio/AudioPlugin.ts
+++ b/sdk/src/audio/AudioPlugin.ts
@@ -4,10 +4,10 @@ import type { App, Plugin } from '../app/app';
import type { Entity, Vec3 } from '../types';
import { defineSystem, Schedule } from '../ecs/system';
import { Res, Time, type TimeData } from '../ecs/resource';
-import { Audio, AudioAPI } from './Audio';
+import { Audio, AudioAPI, setAudioHostSuspended } from './Audio';
import { AudioSource, AudioListener, type AudioSourceData, type AudioListenerData } from './AudioComponents';
import { WorldTransform, type WorldTransformData } from '../ecs/component';
-import { platformCreateAudioBackend, platformOnMemoryWarning } from '../platform/base';
+import { getPlatform, platformCreateAudioBackend, platformOnMemoryWarning } from '../platform/base';
import { q } from '../math/quat';
import { calculateAttenuation, calculatePanning, spatialDistance, type SpatialAudioConfig, AttenuationModel } from './SpatialAudio';
import type { AudioHandle } from './PlatformAudioBackend';
@@ -45,6 +45,7 @@ interface AudioPluginState {
audio: AudioAPI;
released: boolean;
offMemoryWarning: () => void;
+ offAudioMute: () => void;
offDespawn: () => void;
}
@@ -77,6 +78,8 @@ export class AudioPlugin implements Plugin {
const mixer = backend.mixer;
const audio = new AudioAPI(backend, mixer);
app.insertResource(Audio, audio);
+ const muteOwner = {};
+ const offAudioMute = getPlatform().onAudioMute?.(muted => setAudioHostSuspended(audio, muteOwner, muted)) ?? (() => {});
// OS memory pressure → drop the decoded-buffer warm cache. Held
// buffers keep playing; re-fetch cost returns only for evicted ones.
@@ -102,7 +105,7 @@ export class AudioPlugin implements Plugin {
}
playedEntities.delete(entity);
});
- const state = { activeSourceHandles, playedEntities, audio, offMemoryWarning, offDespawn, released: false };
+ const state = { activeSourceHandles, playedEntities, audio, offMemoryWarning, offAudioMute, offDespawn, released: false };
this.states_.set(app, state);
this.latestState_ = state;
const stopVoice = (id: number): void => {
@@ -323,6 +326,7 @@ export class AudioPlugin implements Plugin {
state.released = true;
if (app) this.states_.delete(app);
if (state === this.latestState_) this.latestState_ = null;
+ state.offAudioMute();
state.offMemoryWarning();
state.offDespawn();
this.stopSources_(state);
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index e0d8c4120..4451e74a0 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -669,6 +669,9 @@ export interface PlatformAdapter {
* Absent on hosts without a safe-area source. */
safeAreaInsets?(): { top: number; bottom: number; left: number; right: number };
+ /** Host audio policy; game volume/resume controls cannot override it. */
+ onAudioMute?(handler: (muted: boolean) => void): () => void;
+
getStorageItem(key: string): string | null;
setStorageItem(key: string, value: string): void;
removeStorageItem(key: string): void;
diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.ts
index 42cc20fef..f9595ee05 100644
--- a/sdk/src/runtime/packagedRuntime.ts
+++ b/sdk/src/runtime/packagedRuntime.ts
@@ -38,7 +38,7 @@ import type { AotManifest } from '../ecs/aot/AotSystems';
*/
export interface PackagedGameConfig {
/** External Web distribution SDK selected by this export. */
- webChannel?: 'poki';
+ webChannel?: 'poki' | 'crazygames';
/** Project-relative path of the scene the game boots into. */
entryScene: string;
/** Every switchable scene (SceneManager name + cooked path); includes the entry. */
diff --git a/sdk/src/services/achievements.ts b/sdk/src/services/achievements.ts
index 734d7e735..bbfac958c 100644
--- a/sdk/src/services/achievements.ts
+++ b/sdk/src/services/achievements.ts
@@ -62,21 +62,25 @@ export function createLocalAchievements(): AchievementProvider {
const raw = Storage.getJSON<LocalState>(STORAGE_KEY);
return { unlocked: raw?.unlocked ?? [], stats: raw?.stats ?? {} };
};
- let state = read();
- const flush = () => Storage.setJSON(STORAGE_KEY, state);
+ // Creating an unused service must not require persistence permission.
+ // A failed read remains retryable, and actual storage operations still fail explicitly.
+ let state: LocalState | undefined;
+ const current = () => state ??= read();
+ const flush = () => Storage.setJSON(STORAGE_KEY, current());
return {
platformBacked: false,
unlock: (id) => {
+ const state = current();
if (!state.unlocked.includes(id)) {
state.unlocked.push(id);
flush();
}
return Promise.resolve();
},
- unlocked: (id) => state.unlocked.includes(id),
- setStat: (name, value) => { state.stats[name] = value; flush(); },
- getStat: (name) => state.stats[name] ?? 0,
+ unlocked: (id) => current().unlocked.includes(id),
+ setStat: (name, value) => { current().stats[name] = value; flush(); },
+ getStat: (name) => current().stats[name] ?? 0,
store: () => Promise.resolve(),
reset: () => {
state = { unlocked: [], stats: {} };
diff --git a/sdk/src/video/VideoAPI.ts b/sdk/src/video/VideoAPI.ts
index 8f421a3b4..42fcbac7b 100644
--- a/sdk/src/video/VideoAPI.ts
+++ b/sdk/src/video/VideoAPI.ts
@@ -6,6 +6,7 @@ import type { ESEngineModule } from '../wasm';
import type { PlatformVideoBackend, VideoStreamHandle, VideoStreamOptions } from './PlatformVideoBackend';
import { defineResource } from '../ecs/resource';
import { log } from '../util/logger';
+import { getPlatform, isPlatformInitialized } from '../platform/base';
export type VideoHandle = VideoStreamHandle;
export type VideoPlayOptions = VideoStreamOptions;
@@ -15,10 +16,20 @@ export class VideoAPI {
private readonly handles_ = new Set<VideoStreamHandle>();
private refResolver_: ((ref: string) => string) | null = null;
private disposed_ = false;
+ private hostMuted_ = false;
+ private readonly muteTargets_ = new Map<VideoStreamHandle, () => void>();
+ private readonly offHostMute_: () => void;
+ private readonly hasHostMute_: boolean;
baseUrl = '';
constructor(backend: PlatformVideoBackend) {
this.backend_ = backend;
+ const subscribe = isPlatformInitialized() ? getPlatform().onAudioMute : undefined;
+ this.hasHostMute_ = subscribe !== undefined;
+ this.offHostMute_ = subscribe?.call(getPlatform(), muted => {
+ this.hostMuted_ = muted;
+ for (const apply of this.muteTargets_.values()) apply();
+ }) ?? (() => {});
}
get backendName(): string { return this.backend_.name; }
@@ -36,10 +47,33 @@ export class VideoAPI {
}
play(source: string, options: VideoPlayOptions = {}): VideoStreamHandle {
- const handle = this.backend_.createStream(this.resolveUrl_(source), {
+ let userMuted = options.muted ?? false;
+ const stream = this.backend_.createStream(this.resolveUrl_(source), {
...options,
+ ...(this.hasHostMute_ ? { muted: userMuted || this.hostMuted_ } : {}),
audioTrackUrl: options.audioTrackUrl ?? this.resolveAudioTrack_(source),
});
+ let handle = stream;
+ if (this.hasHostMute_) {
+ const setMuted = stream.setMuted.bind(stream);
+ const methods = new Set(['play', 'pause', 'stop', 'seek', 'setVolume', 'setLoop', 'setPlaybackRate', 'pump']);
+ const bindings = new Map<PropertyKey, { original: unknown; bound: unknown }>();
+ const overrideMuted = (muted: boolean) => { userMuted = muted; setMuted(userMuted || this.hostMuted_); };
+ handle = new Proxy(stream, {
+ get(target, key) {
+ if (key === 'setMuted') return overrideMuted;
+ const value = Reflect.get(target, key, target);
+ if (typeof key === 'string' && methods.has(key) && typeof value === 'function') {
+ let entry = bindings.get(key);
+ if (!entry || entry.original !== value) { entry = { original: value, bound: value.bind(target) }; bindings.set(key, entry); }
+ return entry.bound;
+ }
+ return value;
+ },
+ set(target, key, value) { return Reflect.set(target, key, value, target); },
+ });
+ this.muteTargets_.set(handle, () => setMuted(userMuted || this.hostMuted_));
+ }
this.handles_.add(handle);
return handle;
}
@@ -67,6 +101,7 @@ export class VideoAPI {
} catch (err) {
log.error('video', `pump failed for stream #${handle.id} — stopping it`, err);
this.handles_.delete(handle);
+ this.muteTargets_.delete(handle);
try { handle.stop(); } catch { /* already broken */ }
handle.onError?.(err);
}
@@ -74,17 +109,20 @@ export class VideoAPI {
}
stop(handle: VideoStreamHandle): void {
+ this.muteTargets_.delete(handle);
if (this.handles_.delete(handle)) handle.stop();
}
stopAll(): void {
for (const handle of this.handles_) handle.stop();
this.handles_.clear();
+ this.muteTargets_.clear();
}
dispose(): void {
if (this.disposed_) return;
this.disposed_ = true;
+ this.offHostMute_();
this.stopAll();
this.backend_.dispose();
}
diff --git a/sdk/tests/achievements.test.ts b/sdk/tests/achievements.test.ts
index 4ffd2c516..64aba470e 100644
--- a/sdk/tests/achievements.test.ts
+++ b/sdk/tests/achievements.test.ts
@@ -55,6 +55,16 @@ describe('the unknown-id guard', () => {
});
describe('the local provider', () => {
+ it('defers storage until used and retries reads after permission recovery', () => {
+ const read = vi.spyOn(Storage, 'getJSON').mockImplementation(() => { throw new Error('saving unavailable'); });
+ try {
+ const api = new AchievementsAPI();
+ expect(api.available).toBe(false); expect(read).not.toHaveBeenCalled();
+ expect(() => api.getStat('kills')).toThrow('saving unavailable');
+ read.mockReturnValue({ unlocked: ['A'], stats: { kills: 2 } });
+ expect(api.unlocked('A')).toBe(true); expect(api.getStat('kills')).toBe(2);
+ } finally { read.mockRestore(); }
+ });
it('records an unlock and survives a restart', async () => {
const api = new AchievementsAPI();
await api.unlock('FIRST_BLOOD');
diff --git a/sdk/tests/audio-plugin-lifecycle.test.ts b/sdk/tests/audio-plugin-lifecycle.test.ts
index b1a89a869..cdf5880ef 100644
--- a/sdk/tests/audio-plugin-lifecycle.test.ts
+++ b/sdk/tests/audio-plugin-lifecycle.test.ts
@@ -3,8 +3,14 @@
import { afterEach, expect, it, vi } from 'vitest';
import type { PlatformAudioBackend, AudioHandle } from '../src/audio/PlatformAudioBackend';
const backends: PlatformAudioBackend[] = [], listeners = new Set<() => void>();
+const muteListeners = new Set<(muted: boolean) => void>();
+let hostMuted = false;
vi.mock('../src/platform/base', async original => ({
...await original<typeof import('../src/platform/base')>(),
+ getPlatform: () => ({ onAudioMute: (callback: (muted: boolean) => void) => {
+ muteListeners.add(callback); callback(hostMuted);
+ return () => muteListeners.delete(callback);
+ } }),
platformCreateAudioBackend: () => {
const backend = { name: 'Mock', mixer: null, isReady: true,
initialize: vi.fn().mockResolvedValue(undefined), ensureResumed: vi.fn().mockResolvedValue(undefined),
@@ -24,7 +30,18 @@ const { Audio } = await import('../src/audio/Audio');
const { AudioSource } = await import('../src/audio/AudioComponents');
const apps: ReturnType<typeof App.new>[] = [];
function build(plugin: InstanceType<typeof AudioPlugin>) { const app=App.new(); apps.push(app); app.addPlugin(plugin); return app; }
-afterEach(() => { for(const app of apps.splice(0)) app.quit(); backends.length=0; listeners.clear(); });
+afterEach(() => { for(const app of apps.splice(0)) app.quit(); backends.length=0; listeners.clear(); muteListeners.clear(); hostMuted=false; });
+it('host mute overrides game resume and preserves explicit suspension after host unmute', () => {
+ hostMuted = true;
+ const app = build(new AudioPlugin()), audio = app.getResource(Audio), backend = backends[0];
+ expect(backend.suspend).toHaveBeenCalledOnce();
+ audio.resume(); expect(backend.resume).not.toHaveBeenCalled();
+ audio.suspend();
+ for (const callback of muteListeners) callback(false);
+ expect(backend.resume).not.toHaveBeenCalled();
+ audio.resume(); expect(backend.resume).toHaveBeenCalledOnce();
+ app.quit(); expect(muteListeners.size).toBe(0);
+});
it('quitting an older app releases its backend and preserves the newer app voice and subscription', async () => {
const plugin=new AudioPlugin(), first=build(plugin), second=build(plugin);
const a=first.getResource(Audio), b=second.getResource(Audio);
diff --git a/sdk/tests/video-host-mute.test.ts b/sdk/tests/video-host-mute.test.ts
new file mode 100644
index 000000000..44a47bd00
--- /dev/null
+++ b/sdk/tests/video-host-mute.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, expect, it, vi } from 'vitest';
+import { VideoAPI } from '../src/video/VideoAPI';
+import { NullVideoBackend } from '../src/video/NullVideoBackend';
+
+const policy = vi.hoisted(() => ({ enabled: true, muted: true, listeners: new Set<(muted: boolean) => void>() }));
+vi.mock('../src/platform/base', () => ({
+ isPlatformInitialized: () => true,
+ getPlatform: () => ({ onAudioMute: policy.enabled ? (callback: (muted: boolean) => void) => {
+ policy.listeners.add(callback); callback(policy.muted);
+ return () => policy.listeners.delete(callback);
+ } : undefined }),
+}));
+const services: VideoAPI[] = [];
+afterEach(() => { for (const api of services.splice(0)) api.dispose(); policy.listeners.clear(); policy.enabled=true; policy.muted=true; });
+function build() {
+ const backend = new NullVideoBackend();
+ const original = backend.createStream;
+ const create = vi.spyOn(backend, 'createStream');
+ create.mockImplementation((url, options) => {
+ const stream = original.call(backend, url, options);
+ vi.spyOn(stream, 'setMuted'); return stream;
+ });
+ const api = new VideoAPI(backend); services.push(api);
+ return { api, create };
+}
+function mute(value: boolean) { policy.muted=value; for (const callback of policy.listeners) callback(value); }
+it('mutes new streams and prevents game controls from overriding host policy', () => {
+ const { api, create } = build(), handle = api.play('clip.mp4');
+ const raw = create.mock.results[0].value;
+ expect(create.mock.calls[0][1].muted).toBe(true);
+ handle.setMuted(false); expect(raw.setMuted).toHaveBeenLastCalledWith(true);
+ mute(false); expect(raw.setMuted).toHaveBeenLastCalledWith(false);
+ handle.setMuted(true); mute(true); mute(false);
+ expect(raw.setMuted).toHaveBeenLastCalledWith(true);
+});
+it('preserves stream method receivers, getters and callback identity', () => {
+ const { api } = build(), handle = api.play('clip.mp4');
+ handle.pause(); expect(handle.isPlaying).toBe(false);
+ handle.play(); expect(handle.isPlaying).toBe(true);
+ expect(handle.play).toBe(handle.play);
+ const callback = vi.fn(); handle.onEnded=callback;
+ expect(handle.onEnded).toBe(callback);
+});
+it('retires mute targets on stop and unsubscribes on disposal', () => {
+ const { api, create } = build(), handle=api.play('clip.mp4');
+ const raw=create.mock.results[0].value;
+ api.stop(handle); mute(false); expect(raw.setMuted).not.toHaveBeenCalled();
+ api.dispose(); expect(policy.listeners.size).toBe(0);
+});
+it('keeps raw handle identity on platforms without host audio policy', () => {
+ policy.enabled=false;
+ const { api, create }=build(), handle=api.play('clip.mp4');
+ expect(handle).toBe(create.mock.results[0].value);
+ expect(create.mock.calls[0][1].muted).toBeUndefined();
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 796df7b75..518b74ce7 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -30,6 +30,10 @@ export const NOTES_FLOOR = 'v0.65.0';
export const NOTED = {
'perf(ui): keep text measurement atlases off GPU':
{ note: 'Text measurement avoids GPU glyph pages.' },
+ 'feat(crazygames): connect Web ads storage and host audio policy':
+ { note: 'CrazyGames Web exports connect the official v3 SDK.' },
+ 'feat(settings): add CrazyGames Web channel selection':
+ { note: 'CrazyGames Web exports connect the official v3 SDK.' },
'fix(ui): scope inline text cleanup and release measurement pages':
{ note: 'Inline rich text releases its own measurement atlas.' },
'docs(poki): document official Inspector URL validation':
diff --git a/tools/tests/crazygames-training.e2e.mjs b/tools/tests/crazygames-training.e2e.mjs
new file mode 100644
index 000000000..16a033fce
--- /dev/null
+++ b/tools/tests/crazygames-training.e2e.mjs
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/** Exported game against explicit SDK mocks; never opens a visible window. */
+import fs from 'node:fs';
+import path from 'node:path';
+import http from 'node:http';
+import crypto from 'node:crypto';
+import assert from 'node:assert/strict';
+import { chromium } from 'playwright';
+
+const args=process.argv.slice(2);
+const flag=name=>args[args.indexOf(name)+1];
+if (!args.includes('--dir')) throw new Error('Expected --dir <CrazyGames Web export>');
+const root=fs.realpathSync(flag('--dir')), out=path.resolve(args.includes('--out') ? flag('--out') : 'output/crazygames-training-check');
+fs.mkdirSync(out,{recursive:true});
+const sha=file=>crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
+const files=(under='')=>fs.readdirSync(path.join(root,under),{withFileTypes:true}).flatMap(entry=>{
+ const file=under ? `${under}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) return files(file);
+ if (!entry.isFile()) throw new Error(`Unsupported entry ${file}`);
+ return [file];
+});
+const identities=Object.fromEntries(files().map(file=>[file,sha(path.join(root,file))]));
+const mime={'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.wasm':'application/wasm','.png':'image/png'};
+const server=http.createServer((req,res)=>{
+ try {
+ const name=decodeURIComponent(new URL(req.url,'http://localhost').pathname).slice(1) || 'index.html';
+ const file=fs.realpathSync(path.resolve(root,name));
+ if (!file.startsWith(root+path.sep) || !fs.statSync(file).isFile()) throw new Error('Outside export');
+ res.setHeader('Content-Type',mime[path.extname(file)] ?? 'application/octet-stream');res.end(fs.readFileSync(file));
+ } catch {res.writeHead(404);res.end();}
+});
+await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
+const origin=`http://127.0.0.1:${server.address().port}`;
+const browser=await chromium.launch({headless:true,args:['--enable-unsafe-swiftshader','--use-angle=swiftshader','--mute-audio']});
+const report={mode:'local-mock',headless:true,status:'failed',identities,verifierSha256:sha(new URL(import.meta.url)),cases:[],
+ pending:['Official CrazyGames QA','Production ad fill','Cross-account cloud restoration','Physical-device and audible quality acceptance','Leaderboards']};
+try {
+ for (const mode of ['normal','init-failed','sdk-missing','save-disabled']) {
+ const context=await browser.newContext({viewport:{width:800,height:450}}), page=await context.newPage();
+ const observation={mode,status:'failed',errors:[],unexpectedRequests:[]};report.cases.push(observation);
+ page.on('pageerror',error=>observation.errors.push(String(error)));
+ await page.addInitScript(()=>{
+ window.__audioContexts=[];const Original=window.AudioContext;
+ if (Original) window.AudioContext=class extends Original {constructor(...args){super(...args);window.__audioContexts.push(this);}};
+ });
+ await context.route('**/*',async route=>{
+ const url=route.request().url();
+ if (url.startsWith(origin+'/')) return route.continue();
+ if (url==='https://sdk.crazygames.com/crazygames-sdk-v3.js') return route.fulfill({contentType:'text/javascript',body:mode==='sdk-missing' ? '' : `
+ window.__events=[];window.__settingsListeners=new Set();window.__data=new Map();
+ const record=event=>__events.push(event);
+ window.CrazyGames={SDK:{
+ init(){record('init');return ${mode==='init-failed' ? 'Promise.reject(new Error("blocked"))' : 'Promise.resolve()'}},
+ game:{settings:{muteAudio:true},loadingStart(){record('loading')},loadingStop(){record('loaded')},
+ gameplayStart(){record('start')},gameplayStop(){record('stop')},
+ addSettingsChangeListener(cb){__settingsListeners.add(cb)},removeSettingsChangeListener(cb){__settingsListeners.delete(cb)}},
+ ad:{requestAd(type,cb){record(type);window.__ad=cb;cb.adStarted()}},
+ data:{getItem(key){${mode==='save-disabled' ? 'throw new Error("Progress Save disabled");' : 'return __data.get(key) ?? null;'}},
+ setItem(key,value){__data.set(key,value)},removeItem(key){__data.delete(key)}}
+ }};
+ window.__mute=value=>{CrazyGames.SDK.game.settings.muteAudio=value;for(const cb of __settingsListeners)cb({muteAudio:value})};
+ `});
+ observation.unexpectedRequests.push(url);return route.abort();
+ });
+ try {
+ await page.goto(origin+'/?headless');
+ await page.waitForFunction(()=>window.__estellaCooked?.probe(['DeviceStatus']).at.DeviceStatus?.text,{}, {timeout:30000});
+ await page.waitForFunction(()=>!document.getElementById('es-splash'));
+ const click=async name=>{
+ const box=await page.evaluate(n=>__estellaCooked.probe([n]).at[n],name);assert(box,`Missing ${name}`);
+ await page.mouse.click(400+box.x,225-box.y);
+ };
+ const phase=value=>page.waitForFunction(v=>__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text.startsWith(v),value.toUpperCase());
+ const active=mode==='normal'||mode==='save-disabled';
+ assert.deepEqual(await page.evaluate(()=>window.__events ?? []),mode==='sdk-missing' ? [] : active ? ['init','loading','loaded'] : ['init']);
+ await click('TrainingStart');await phase('playing');
+ if (active) {
+ await page.waitForFunction(()=>__audioContexts.length>0 && __audioContexts.every(c=>c.state==='suspended'));
+ await page.evaluate(()=>__mute(false));
+ await page.waitForFunction(()=>__audioContexts.every(c=>c.state==='running'));
+ const before=await page.evaluate(()=>__events.slice());
+ await page.evaluate(()=>{document.dispatchEvent(new Event('visibilitychange'));window.dispatchEvent(new Event('pagehide'));window.dispatchEvent(new Event('pageshow'));});
+ assert.deepEqual(await page.evaluate(()=>__events),before);
+ await phase('playing');
+ await page.evaluate(()=>__mute(true));
+ await click('TrainingReward');await phase('ad');
+ await page.evaluate(()=>__ad.adFinished());await phase('playing');
+ await page.waitForFunction(()=>__audioContexts.every(c=>c.state==='suspended'));
+ await page.evaluate(()=>__mute(false));
+ await page.waitForFunction(()=>__audioContexts.every(c=>c.state==='running'));
+ assert.match(await page.evaluate(()=>__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text),/Credits: 1/);
+ await click('TrainingReward');await phase('ad');await page.evaluate(()=>__ad.adError(new Error('no fill')));await phase('playing');
+ assert.match(await page.evaluate(()=>__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text),/Credits: 1/);
+ await click('TrainingPause');await phase('paused');await click('TrainingStart');await phase('ad');
+ await page.evaluate(()=>__ad.adFinished());await phase('playing');
+ observation.storage=await page.evaluate(async()=>{
+ const {Storage}=await import('esengine');
+ try {Storage.setString('training-check','retained');const restored=Storage.getString('training-check');
+ CrazyGames.SDK.data.setItem('publisher-data','keep');Storage.clear();
+ return {restored,cleared:Storage.has('training-check'),publisher:CrazyGames.SDK.data.getItem('publisher-data')};
+ } catch(error) {return {error:String(error),localFallback:localStorage.getItem('esengine:training-check')};}
+ });
+ if (mode==='normal') assert.deepEqual(observation.storage,{restored:'retained',cleared:false,publisher:'keep'});
+ else {assert.match(observation.storage.error,/Progress Save disabled/);assert.equal(observation.storage.localFallback,null);}
+ assert.deepEqual(await page.evaluate(()=>__events),['init','loading','loaded','start','stop','rewarded','start','stop','rewarded','start','stop','midgame','start']);
+ } else {
+ assert.match(await page.evaluate(()=>__estellaCooked.probe(['TrainingReward']).at.TrainingReward ? __estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text : ''),/Credits: 0/);
+ observation.storage=await page.evaluate(async()=>{try{(await import('esengine')).Storage.setString('training-check','bad');return 'unexpected success';}catch(error){return String(error);}});
+ assert.match(observation.storage,/storage unavailable/);
+ assert.deepEqual(await page.evaluate(()=>window.__events ?? []),mode==='sdk-missing' ? [] : ['init']);
+ }
+ const screenshot=`${mode}.png`;await page.screenshot({path:path.join(out,screenshot)});
+ observation.screenshot={file:screenshot,sha256:sha(path.join(out,screenshot))};
+ assert.deepEqual(observation.errors,[]);assert.deepEqual(observation.unexpectedRequests,[]);
+ observation.events=await page.evaluate(()=>window.__events ?? []);observation.status='passed';
+ } catch(error) {observation.failure=String(error);throw error;}
+ finally {await context.close();}
+ }
+ assert.deepEqual(Object.fromEntries(files().map(file=>[file,sha(path.join(root,file))])),identities);
+ report.status='checks-passed';
+} finally {
+ fs.writeFileSync(path.join(out,'runtime-check.json'),JSON.stringify(report,null,2));
+ await browser.close();await new Promise(resolve=>server.close(resolve));
+}
+console.log(`CrazyGames local mock checks: ${report.cases.length} passed`);
diff --git a/tools/tests/poki-training.test.ts b/tools/tests/poki-training.test.ts
index 31311ec4b..ef0c86553 100644
--- a/tools/tests/poki-training.test.ts
+++ b/tools/tests/poki-training.test.ts
@@ -17,6 +17,15 @@ function harness() {
}
describe('authored Poki training flow', () => {
+ it('routes both ad types through the selected Web channel', async () => {
+ const ids: string[] = [];
+ const session = new TrainingSession({ available: true,
+ showRewarded: async id => { ids.push(id); return { completed: true }; },
+ showInterstitial: async id => { ids.push(id); },
+ }, { gameplayStart() {}, gameplayStop() {}, reset() {}, changed() {} }, 'crazygames');
+ await session.begin(); session.pause(); await session.begin(); await session.reward();
+ expect(ids).toEqual(['crazygames', 'crazygames']);
+ });
it('menu hits and construction emit no gameplay; first intent starts once', async () => {
const { session, events } = harness(); session.hit(); session.hit();
expect(session.hits).toBe(0); expect(events).toEqual([]);