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(youtube): connect Playables readiness pause and cloud saves

yhh6510d1271335
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index afd2f2622..3507e0072 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -78,6 +78,10 @@ jobs:
run: |
node tools/tests/export-execution-hold-fixture.mjs --wasm build/wasm/web --out output/execution-hold-ci-export
node tools/tests/execution-hold.e2e.mjs --dir output/execution-hold-ci-export --out output/execution-hold-ci-check
+ - name: Check YouTube readiness, SDK pause and cloud saves in SDK mocks
+ run: |
+ node pipeline/bin/estella.mjs export examples/mobile-controls --profile youtube --wasm build/wasm/web --out output/youtube-training-ci-export
+ node tools/tests/youtube-training.e2e.mjs --dir output/youtube-training-ci-export --out output/youtube-training-ci-check
- name: Upload hash-bound local observations and screenshots
if: always()
uses: actions/upload-artifact@v7
@@ -106,6 +110,13 @@ jobs:
name: execution-hold-headless-checks
path: output/execution-hold-ci-*
retention-days: 3
+ - name: Upload YouTube training local mock observations
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: youtube-training-local-mock-checks
+ path: output/youtube-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/AGENTS.md b/AGENTS.md
index 7b13c8fc4..977fa0d54 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,3 +19,6 @@
- After completing appropriate verification, commit and push changes directly to
the main branch (currently master). Do not create pull requests unless the user
explicitly requests one.
+
+- Routine roadmap work must not bump versions, create tags, or publish releases.
+ Release actions require an explicit user request.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76b6489ab..c104e4fea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,10 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **YouTube Playables Web exports honor host readiness and persistence.** The editor offers the channel and named example profile. Exports load the official SDK, report painted loading and interactive readiness, follow SDK pause/audio policy, and await cloud save acknowledgment before sending the saved highest score. Failed or unreadable cloud loads preserve progress; SDK no-ops disable host services. Headless SDK mock checks cover readiness, pause, reward credits and reloads; official certification and devices remain pending.
+
## [0.84.0] - 2026-10-15
### Added
diff --git a/desktop b/desktop
index 12d84fb36..84633e5ad 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 12d84fb362e7fa3589dc2be6acbafe39a2064057
+Subproject commit 84633e5adb0a3ec64e009a1f99393c22e70a2b8c
diff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdx
index 4b22d0c3e..874747a29 100644
--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx
+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx
@@ -352,3 +352,25 @@ running for the session; the Inspector supplies its testing context. This path
has been checked with the training example's real SDK initialization, loading,
play/pause and rewarded completion. Complete the remaining QA modules before
submission; these observations do not certify devices or production ad fill.
+
+## YouTube Playables Web exports
+
+Select **YouTube Playables** in Web packaging or set
+`packaging.platforms.web.channel` to `"youtube"`. The Mobile Controls example
+provides a named `youtube` profile. The official SDK loads before game code;
+`firstFrameReady` reports the painted loading screen and `gameReady` waits
+until the scene is interactive and the loading overlay has disappeared.
+
+SDK pause/resume holds engine frames, input, audio and video independently of
+player pause. Game-owned asynchronous work must cooperate with execution
+notifications. Visibility events do not override SDK pause. Reward credits
+require a true SDK result. Cloud data must load successfully before writes;
+failed or unreadable loads preserve existing progress. Await `Storage.flush()`
+or `SaveManager.saveAsync()` to observe SDK save acknowledgment. Saves above
+3 MiB are rejected; pause-time saves above 64 KiB remain pending. The example
+sends the highest score only after saving that value successfully.
+
+Outside the Playables environment, local SDK no-ops do not enable ads, scores
+or cloud saving. Headless SDK mock checks are separate from official Test Suite
+certification, real cloud restoration and physical-device acceptance. See the
+[official integration requirements](https://developers.google.com/youtube/gaming/playables/certification/requirements_integration).
diff --git a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx
index ec3d848ea..636a5a547 100644
--- a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx
+++ b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx
@@ -312,3 +312,21 @@ CI 使用真正无头 Chromium、SDK 模拟和同提交 Web WASM 检查这些流
Inspector 会提供测试上下文。训练示例的真实 SDK 初始化、加载、开始/暂停
和奖励完成已通过这条入口核实;提交前仍须逐项完成其余 QA 模块,不能把
这些观察等同于设备验收或正式投放的广告填充保证。
+
+## YouTube Playables Web 导出
+
+在 Web 打包设置选择 **YouTube Playables**,或将
+`packaging.platforms.web.channel` 设置为 `"youtube"`。Mobile Controls
+提供同名导出档。官方 SDK 在游戏代码前加载:加载画面绘制后通知
+`firstFrameReady`,场景可交互且加载遮罩消失后通知 `gameReady`。
+
+SDK 的暂停/恢复独立控制引擎帧、输入、音频和视频,保留玩家暂停选择。
+游戏自有异步任务须配合执行状态通知;页面可见性事件不能覆盖宿主暂停。
+奖励只有在 SDK 返回 true 时发放。云数据读取成功前不能写入,读取失败或
+数据无法识别时保留已有进度。通过 `await Storage.flush()` 或
+`SaveManager.saveAsync()` 等待 SDK 保存确认。存档上限为 3 MiB;暂停时
+超过 64 KiB 的保存保持待重试,不截断数据。示例保存最高分成功后才提交同一分数。
+
+本地 SDK 的空操作不启用广告、分数或云存档。无头 SDK 模拟检查与官方
+Test Suite 认证、真实云恢复和物理设备验收分别记录。参见
+[官方接入要求](https://developers.google.com/youtube/gaming/playables/certification/requirements_integration)。
diff --git a/examples/mobile-controls/README.md b/examples/mobile-controls/README.md
index 998bf239a..bdd8d07f1 100644
--- a/examples/mobile-controls/README.md
+++ b/examples/mobile-controls/README.md
@@ -129,3 +129,29 @@ See the official [SDK introduction](https://docs.crazygames.com/sdk/intro/),
[Data module](https://docs.crazygames.com/sdk/data/).
For scores, see [leaderboard requirements](https://docs.crazygames.com/sdk/leaderboards/)
and [client score submission](https://docs.crazygames.com/sdk/leaderboards-client/).
+
+## YouTube Playables Web training profile
+
+Export with `node pipeline/bin/estella.mjs export examples/mobile-controls
+--profile youtube --out output/youtube-training-web`. The editor also exposes
+YouTube Playables under Web channel settings. The official SDK loads before
+game code. The host reports the painted loading screen with `firstFrameReady`
+and waits until the scene is interactive and the loading overlay has gone
+before reporting `gameReady`.
+
+SDK pause/resume events hold engine frames, input, audio and video. Browser
+visibility events never override a host pause. Game-owned asynchronous work
+must cooperate with pause; execution holds cannot cancel already running JavaScript.
+
+Cloud data must load successfully before any write. Missing SDKs, local SDK
+no-ops, failed reads and unreadable saves disable cloud writes without a local
+fallback. Use `await Storage.flush()` or `SaveManager.saveAsync()` to observe
+SDK acknowledgment. The envelope has a 3 MiB limit; pause-time saves above
+64 KiB remain pending rather than being truncated. The training UI restores
+reward credits, grants rewards only when the SDK returns true, and submits
+the highest score only after that same value has been saved successfully.
+
+Headless checks use explicit SDK mocks. Official Playables invitation,
+Test Suite certification, real cloud restoration and device acceptance remain
+pending. See the official [integration requirements](https://developers.google.com/youtube/gaming/playables/certification/requirements_integration)
+and [SDK reference](https://developers.google.com/youtube/gaming/playables/reference/sdk).
diff --git a/examples/mobile-controls/project.esproject b/examples/mobile-controls/project.esproject
index 6b3537fc7..c89adac8b 100644
--- a/examples/mobile-controls/project.esproject
+++ b/examples/mobile-controls/project.esproject
@@ -12,6 +12,14 @@
"spineVersion": "none",
"packaging": {
"profiles": {
+ "youtube": {
+ "platform": "web",
+ "platforms": {
+ "web": {
+ "channel": "youtube"
+ }
+ }
+ },
"crazygames": {
"platform": "web",
"platforms": {
diff --git a/examples/mobile-controls/src/pokiTrainingUI.ts b/examples/mobile-controls/src/pokiTrainingUI.ts
index 0a5ee8322..6ead578c0 100644
--- a/examples/mobile-controls/src/pokiTrainingUI.ts
+++ b/examples/mobile-controls/src/pokiTrainingUI.ts
@@ -13,10 +13,12 @@ export function setupWebTraining(
): TrainingSession | null {
if (typeof document === 'undefined') return null;
const channel = document.documentElement?.dataset?.webChannel;
- if (channel !== 'poki' && channel !== 'crazygames') return null;
- const save = channel === 'crazygames' ? new TrainingSave(Storage) : null;
+ if (channel !== 'poki' && channel !== 'crazygames' && channel !== 'youtube') return null;
+ const compact = channel !== 'poki';
+ const save = compact ? new TrainingSave(Storage) : null;
let submittingScore = false;
const notify = (event: keyof PokiGameplay): void => {
+ if (channel === 'youtube') return;
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;
@@ -25,9 +27,9 @@ export function setupWebTraining(
};
const controls: Array<{ button: ReturnType<typeof createButton>; label: ReturnType<typeof spawnUIEntity> }> = [];
const update = (): void => {
- if (controls.length !== (channel === 'crazygames' ? 4 : 3) || !world.valid(parent) || world.isDestructionPending(parent)) return;
+ if (controls.length !== (compact ? 4 : 3) || !world.valid(parent) || world.isDestructionPending(parent)) return;
const phase = session.phase;
- const labels = [phase === 'menu' ? 'START' : phase === 'finished' ? 'REPLAY' : 'RESUME', 'PAUSE', ads.available ? (channel === 'crazygames' ? 'AD +1' : 'WATCH AD +1') : (channel === 'crazygames' ? 'NO ADS' : 'ADS UNAVAILABLE'), Scores.available ? 'SEND SCORE' : 'NO SCORES'];
+ const labels = [phase === 'menu' ? 'START' : phase === 'finished' ? 'REPLAY' : 'RESUME', 'PAUSE', ads.available ? (compact ? 'AD +1' : 'WATCH AD +1') : (compact ? 'NO ADS' : 'ADS UNAVAILABLE'), Scores.available ? 'SEND SCORE' : 'NO SCORES'];
controls.forEach(({ button, label }, index) => {
button.setDisabled(submittingScore || (index === 0 ? phase === 'playing' || phase === 'ad'
: index === 1 ? phase !== 'playing' : index === 2 ? !ads.available || phase === 'ad' : !Scores.available || phase !== 'finished'));
@@ -37,14 +39,30 @@ export function setupWebTraining(
};
const session = new TrainingSession(ads, {
gameplayStart: () => notify('gameplayStart'), gameplayStop: () => notify('gameplayStop'), reset, changed: update,
- rewardGranted: credits => { save?.save(credits); if (save) session.saveMessage = save.message; },
+ rewardGranted: credits => {
+ if (!save) return;
+ if (channel === 'youtube') {
+ const pending = save.saveAsync(credits); session.saveMessage = save.message;
+ void pending.then(() => { session.saveMessage = save.message; update(); });
+ } else { save.save(credits); session.saveMessage = save.message; }
+ },
}, channel);
if (save) { session.credits = save.load(); session.saveMessage = save.message; }
const actions = [() => { void session.begin(); }, () => session.pause(), () => { void session.reward(); }];
- if (channel === 'crazygames') actions.push(() => {
+ if (compact) actions.push(() => {
if (submittingScore || session.phase !== 'finished' || !Scores.available) return;
submittingScore = true; session.message = 'Sending round score...'; update();
- void Scores.submit(session.hits).then(() => {
+ const send = async () => {
+ let score = session.hits;
+ if (channel === 'youtube') {
+ const key = 'mobile-controls.training-best-score', raw = Storage.getString(key);
+ const previous = raw === undefined ? 0 : Number(raw);
+ if (!Number.isSafeInteger(previous) || previous < 0) throw new Error('Invalid saved best score');
+ score = Math.max(score, previous); Storage.setNumber(key, score); await Storage.flush();
+ }
+ await Scores.submit(score);
+ };
+ void send().then(() => {
session.message = 'Score sent. Platform ranking validation is pending.';
}, () => { session.message = 'Score submission failed. You can retry.'; }).finally(() => {
submittingScore = false; update();
@@ -52,7 +70,7 @@ export function setupWebTraining(
});
for (let index = 0; index < actions.length; index++) {
const button = createButton({ world, events, parent, userGesture: true,
- node: { position: UIPositionType.Absolute, insetLeft: px(channel === 'crazygames' ? 220 + index * 92 : 232 + index * 118), insetTop: px(346), width: px(channel === 'crazygames' ? 88 : 112), height: px(36) },
+ node: { position: UIPositionType.Absolute, insetLeft: px(compact ? 220 + index * 92 : 232 + index * 118), insetTop: px(346), width: px(compact ? 88 : 112), height: px(36) },
onClick: actions[index],
});
world.insert(button.entity, Name, { value: ['TrainingStart', 'TrainingPause', 'TrainingReward', 'TrainingScore'][index] });
diff --git a/examples/mobile-controls/src/trainingSave.ts b/examples/mobile-controls/src/trainingSave.ts
index a6e1138ce..f85b6555e 100644
--- a/examples/mobile-controls/src/trainingSave.ts
+++ b/examples/mobile-controls/src/trainingSave.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-export interface CreditStorage { getString(key: string): string | undefined; setString(key: string, value: string): void }
+export interface CreditStorage { getString(key: string): string | undefined; setString(key: string, value: string): void; flush?(): Promise<void> }
const KEY = 'mobile-controls.training-credits.v1';
/** Demonstrates SDK saving while preserving unreadable or externally changed progress. */
@@ -8,6 +8,7 @@ export class TrainingSave {
message = '';
private snapshot: string | undefined;
private loaded = false;
+ private saveEpoch = 0;
constructor(private readonly storage: CreditStorage) {}
load(): number {
try {
@@ -25,18 +26,26 @@ export class TrainingSave {
return 0;
}
}
- save(credits: number): void {
- if (!this.loaded) return;
+ save(credits: number): boolean {
+ if (!this.loaded) return false;
try {
if (!Number.isSafeInteger(credits) || credits < 0) throw new Error('invalid credits');
if (this.storage.getString(KEY) !== this.snapshot) {
this.loaded = false;
this.message = 'Saved progress changed; reload before saving';
- return;
+ return false;
}
const raw = JSON.stringify({ version: 1, credits });
this.storage.setString(KEY, raw); this.snapshot = raw;
this.message = 'Saved to SDK; cloud backup pending';
- } catch { this.message = 'Save failed; progress kept in this session'; }
+ return true;
+ } catch { this.message = 'Save failed; progress kept in this session'; return false; }
+ }
+ async saveAsync(credits: number): Promise<void> {
+ const epoch = ++this.saveEpoch;
+ if (!this.save(credits) || !this.storage.flush) return;
+ this.message = 'Saving progress...';
+ try { await this.storage.flush(); if (epoch === this.saveEpoch) this.message = 'Save acknowledged by host'; }
+ catch { if (epoch === this.saveEpoch) this.message = 'Save failed; progress kept in this session'; }
}
}
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index d6802744f..55c2cf7e7 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' | 'crazygames',
+ debugChannel?: DebugChannelConfig, webChannel?: 'poki' | 'crazygames' | 'youtube',
): 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.
@@ -349,11 +349,11 @@ function indexHtml(
.join(' ');
// 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' || webChannel === 'crazygames'
+ const channelPolicy = webChannel === 'poki' || webChannel === 'crazygames' || webChannel === 'youtube'
? `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' : webChannel === 'crazygames' ? 'crazygames' : 'standalone'}">
+<html lang="en" data-web-channel="${webChannel === 'poki' ? 'poki' : webChannel === 'crazygames' ? 'crazygames' : webChannel === 'youtube' ? 'youtube' : '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 === 'crazygames' ? '<script src="https://sdk.crazygames.com/crazygames-sdk-v3.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>' : webChannel === 'youtube' ? '<script src="https://www.youtube.com/game_api/v1"></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' | 'crazygames';
+ webChannel?: 'poki' | 'crazygames' | 'youtube';
leaderboardEncryptionKey?: string;
sdkDistDir: string;
/** The engine runtime to copy. */
diff --git a/pipeline/src/export/projectExportOptions.ts b/pipeline/src/export/projectExportOptions.ts
index a2d45a9bf..bcd8f462c 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' || plat?.web?.channel === 'crazygames') ? { webChannel: plat.web.channel } : {}),
+ ...(platform === 'web' && (plat?.web?.channel === 'poki' || plat?.web?.channel === 'crazygames' || plat?.web?.channel === 'youtube') ? { webChannel: plat.web.channel } : {}),
...(platform === 'web' && plat?.web?.channel === 'crazygames' && plat.web.leaderboardEncryptionKey
? { leaderboardEncryptionKey: plat.web.leaderboardEncryptionKey } : {}),
desktopProductName: plat?.desktop?.productName,
diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.ts
index 3b1a7e6b7..891c33d83 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' | 'crazygames'; leaderboardEncryptionKey?: string };
+ web?: { channel?: 'standalone' | 'poki' | 'crazygames' | 'youtube'; leaderboardEncryptionKey?: string };
wechat?: WeChatPackaging;
douyin?: MiniGamePackaging;
bilibili?: MiniGamePackaging;
@@ -911,11 +911,11 @@ 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' && web.channel !== 'crazygames') {
- throw new Error('packaging.platforms.web.channel must be standalone, poki or crazygames');
+ if (web.channel !== undefined && web.channel !== 'standalone' && web.channel !== 'poki' && web.channel !== 'crazygames' && web.channel !== 'youtube') {
+ throw new Error('packaging.platforms.web.channel must be standalone, poki, crazygames or youtube');
}
const config: NonNullable<NonNullable<ProjectPackaging['platforms']>['web']> = {};
- if (web.channel) config.channel = web.channel as 'standalone' | 'poki' | 'crazygames';
+ if (web.channel) config.channel = web.channel as 'standalone' | 'poki' | 'crazygames' | 'youtube';
if (web.leaderboardEncryptionKey !== undefined && web.leaderboardEncryptionKey !== '') {
if (typeof web.leaderboardEncryptionKey !== 'string' || !/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/.test(web.leaderboardEncryptionKey)) {
throw new Error('packaging.platforms.web.leaderboardEncryptionKey must be a base64-encoded 32-byte client encryption key');
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 0fe630f3f..8e0bd292b 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, extendPlatform,
+ createWebApp, setEditorMode, setPlayMode, Assets, Ads, extendPlatform, getPlatform,
indexPackagedManifest, createPackagedAssetSource, applyAssetRefResolvers, initRuntime,
HttpBackend, fetchDecodePixels, registerPackagedSideModules,
packagedAppOptions, packagedRuntimeInit, Transform, SceneManager, UINode,
@@ -62,6 +62,7 @@ import { attachSplash, type Splash } from '../export/splash';
import { countedStream, engineDownloadTotal } from './engineDownload';
import { initializePoki, type PokiSdk } from './pokiProfile';
import { initializeCrazyGames, type CrazyGamesSdk } from './crazyGamesProfile';
+import { initializeYouTube, type YouTubeSdk } from './youtubeProfile';
/**
* Fetch the engine binary through a stream we can count, and hand the SAME
@@ -108,6 +109,24 @@ async function boot(): Promise<void> {
const cfg = (await (await fetch('./game.config.json')).json()) as PackagedGameConfig;
splash?.reach('config');
+ const youtube = cfg.webChannel === 'youtube'
+ ? initializeYouTube((window as unknown as { ytgame?: YouTubeSdk }).ytgame, (message, error) => console.warn(message, error))
+ : null;
+ if (youtube) {
+ await youtube.waitActive();
+ // A painted loading screen qualifies as the first frame; it precedes cloud loading.
+ await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
+ await youtube.waitActive();
+ youtube.firstFrameReady();
+ await youtube.load();
+ const fetchFromHost = getPlatform().fetch.bind(getPlatform());
+ extendPlatform({ ...youtube.storage, onAudioMute: youtube.onAudioMute, submitScore: youtube.submitScore,
+ fetch: async (url, options) => {
+ await youtube.waitActive(); const response = await fetchFromHost(url, options); await youtube.waitActive(); return response;
+ },
+ });
+ document.documentElement.dataset.webSdkReady = String(youtube.provider !== null);
+ }
const poki = cfg.webChannel === 'poki'
? await initializePoki((window as unknown as { PokiSDK?: PokiSdk }).PokiSDK, (message, error) => console.warn(message, error))
: null;
@@ -120,6 +139,7 @@ async function boot(): Promise<void> {
}
// Before the engine boots, so a boot that fails is still heard by the editor.
if (cfg.debugChannel) startDebugChannel(cfg.debugChannel);
+ await youtube?.waitActive();
// The project's own components and systems. The config SAYS whether this build
// has any, so a load failure is a failure rather than a build that turned out
@@ -159,7 +179,9 @@ async function boot(): Promise<void> {
? (cfg.scenes ?? []).find((s) => s.name === wanted)?.path
: cfg.entryScene;
if (!chosen) throw new Error(`[estella] no scene named "${wanted}" in this package`);
+ await youtube?.waitActive();
const sceneData = (await (await fetch(`./${chosen}`)).json()) as SceneData;
+ await youtube?.waitActive();
// The cooked worlds this build carries. Fetched beside the entry scene because
// residency answers for the entry scene from its first frame, and a manifest
@@ -216,6 +238,15 @@ async function boot(): Promise<void> {
});
if (poki?.provider) app.getResource(Ads)?.setProvider(poki.provider);
if (crazyGames?.provider) app.getResource(Ads)?.setProvider(crazyGames.provider);
+ if (youtube) app.addPlugin({ name: 'YouTubeHost', build(host) {
+ if (youtube.provider) host.getResource(Ads)?.setProvider(youtube.provider);
+ let release: (() => void) | null = null;
+ const off = youtube.onPause(paused => {
+ if (paused && !release) release = host.holdExecution();
+ else if (!paused && release) { const finish = release; release = null; finish(); }
+ });
+ this.cleanup = () => { off(); release?.(); youtube.dispose(); };
+ } });
splash?.reach('app');
setEditorMode(false);
setPlayMode(true);
@@ -911,6 +942,17 @@ async function boot(): Promise<void> {
// never return, and the fade is what the first frames should arrive through.
splash?.reach('ready');
splash?.done();
+ if (youtube) {
+ let sent = false;
+ const offFrame = app.onFrameEnd(() => {
+ if (sent) return; sent = true; offFrame();
+ const ready = async () => {
+ while (document.getElementById('es-splash')) await new Promise<void>(resolve => setTimeout(resolve, 30));
+ await youtube.gameReady();
+ };
+ void ready().catch(error => console.warn('[YouTube] Ready notification failed', error));
+ });
+ }
app.run();
}
diff --git a/pipeline/src/runtime/youtubeProfile.ts b/pipeline/src/runtime/youtubeProfile.ts
new file mode 100644
index 000000000..8a5b3c15b
--- /dev/null
+++ b/pipeline/src/runtime/youtubeProfile.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type { AdProvider } from 'esengine';
+import { createAsyncStorage } from './asyncStorage';
+
+export interface YouTubeSdk {
+ IN_PLAYABLES_ENV: boolean;
+ game: { firstFrameReady(): void; gameReady(): void; loadData(): Promise<string>; saveData(data: string): Promise<void> };
+ system: {
+ isAudioEnabled(): boolean;
+ onAudioEnabledChange(callback: (enabled: boolean) => void): () => void;
+ onPause(callback: () => void): () => void;
+ onResume(callback: () => void): () => void;
+ };
+ ads: { requestInterstitialAd(): Promise<void>; requestRewardedAd(rewardId: string): Promise<boolean> };
+ engagement: { sendScore(score: { value: number }): Promise<void> };
+}
+
+export function initializeYouTube(sdk: YouTubeSdk | undefined, warn: (message: string, error?: unknown) => void, loadTimeoutMs = 10000) {
+ const active = sdk?.IN_PLAYABLES_ENV === true;
+ let disposed = false, paused = false, muted = true, firstFrame = false, ready = false;
+ const pauseListeners = new Set<(paused: boolean) => void>(), muteListeners = new Set<(muted: boolean) => void>();
+ const waiters = new Set<{ resolve(): void; reject(error: Error): void }>(), cleanup: Array<() => void> = [];
+ const requireActive = () => { if (!active || disposed) throw new Error('YouTube host service unavailable; no local fallback was written'); };
+ const notify = <T>(listeners: Set<(value: T) => void>, value: T) => {
+ for (const callback of [...listeners]) { try { callback(value); } catch (error) { warn('[YouTube] Host policy listener failed', error); } }
+ };
+ const waitActive = (): Promise<void> => {
+ if (disposed) return Promise.reject(new Error('YouTube session disposed'));
+ if (!paused) return Promise.resolve();
+ return new Promise((resolve, reject) => { waiters.add({ resolve, reject }); });
+ };
+ const emitMute = () => notify(muteListeners, muted || paused);
+ const storage = createAsyncStorage({
+ async load() {
+ requireActive(); await waitActive();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try { return await Promise.race([sdk!.game.loadData(), new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('YouTube cloud loading timed out')), loadTimeoutMs);
+ })]); } finally { if (timer !== undefined) clearTimeout(timer); }
+ },
+ async save(data) {
+ requireActive();
+ // Pause is the SDK's short eviction-save window, with a smaller keepalive allowance.
+ if (paused && new TextEncoder().encode(data).byteLength > 64 * 1024) throw new Error('YouTube pause save exceeds 64 KiB');
+ await sdk!.game.saveData(data);
+ },
+ }, { maxBytes: 3 * 1024 * 1024, autoSave: true, warn: error => warn('[YouTube] Save failed; progress remains pending', error) });
+ if (!active) warn('[YouTube] Outside Playables environment; host ads, scores and cloud saving disabled');
+ else {
+ try { muted = !sdk!.system.isAudioEnabled(); } catch (error) { warn('[YouTube] Initial audio policy unavailable; muted', error); }
+ cleanup.push(sdk!.system.onAudioEnabledChange(enabled => { if (!disposed) { muted = !enabled; emitMute(); } }));
+ cleanup.push(sdk!.system.onPause(() => {
+ if (disposed || paused) return; paused = true;
+ emitMute(); notify(pauseListeners, true);
+ if (storage.dirty) void storage.adapter.flushStorage!().catch(error => warn('[YouTube] Pause save failed', error));
+ }));
+ cleanup.push(sdk!.system.onResume(() => {
+ if (disposed || !paused) return; paused = false;
+ emitMute(); notify(pauseListeners, false);
+ for (const waiter of waiters) waiter.resolve(); waiters.clear();
+ }));
+ }
+ const unit = <T>(show: () => Promise<T>) => {
+ let destroyed = false;
+ return {
+ async preload() { requireActive(); if (destroyed) throw new Error('YouTube ad unit destroyed'); },
+ async show() { requireActive(); if (destroyed) throw new Error('YouTube ad unit destroyed'); await waitActive(); requireActive(); if (destroyed) throw new Error('YouTube ad unit destroyed'); return show(); },
+ destroy() { destroyed = true; },
+ };
+ };
+ const provider: AdProvider | null = active ? {
+ createRewardedAd: id => unit(async () => ({ completed: (await sdk!.ads.requestRewardedAd(id)) === true })),
+ createInterstitialAd: () => unit(() => sdk!.ads.requestInterstitialAd()),
+ } : null;
+ return {
+ provider, storage: storage.adapter, waitActive,
+ async load() { try { await storage.load(); } catch (error) { warn('[YouTube] Load failed; existing progress was preserved', error); } await waitActive(); },
+ onAudioMute(callback: (muted: boolean) => void) { muteListeners.add(callback); callback(active && (muted || paused)); return () => { muteListeners.delete(callback); }; },
+ onPause(callback: (paused: boolean) => void) { pauseListeners.add(callback); callback(paused); return () => { pauseListeners.delete(callback); }; },
+ submitScore: active ? async (score: number) => {
+ if (!Number.isSafeInteger(score)) throw new Error('YouTube scores must be safe integers');
+ await waitActive(); requireActive(); await sdk!.engagement.sendScore({ value: score });
+ } : undefined,
+ firstFrameReady() {
+ if (firstFrame || disposed || !sdk) return;
+ sdk.game.firstFrameReady(); firstFrame = true;
+ },
+ async gameReady() {
+ await waitActive();
+ if (ready || disposed || !sdk) return;
+ if (!firstFrame) throw new Error('YouTube firstFrameReady must precede gameReady');
+ sdk.game.gameReady(); ready = true;
+ },
+ dispose() {
+ if (disposed) return; disposed = true;
+ for (const off of cleanup) {
+ try { off(); } catch (error) { warn('[YouTube] Host subscription cleanup failed', error); }
+ }
+ cleanup.length = 0;
+ for (const waiter of waiters) waiter.reject(new Error('YouTube session disposed')); waiters.clear();
+ pauseListeners.clear(); muteListeners.clear();
+ },
+ };
+}
diff --git a/pipeline/tests/export-splash.test.ts b/pipeline/tests/export-splash.test.ts
index 2ba93b983..cfd922d76 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' | 'crazygames', leaderboardEncryptionKey?: string): Promise<{ html: string; config: Record<string, unknown>; warnings: string[]; splashBytes?: number }> {
+async function page(splash?: ProjectPackaging['splash'], webChannel?: 'poki' | 'crazygames' | 'youtube', leaderboardEncryptionKey?: string): Promise<{ html: string; config: Record<string, unknown>; warnings: string[]; splashBytes?: number }> {
const outDir = path.join(root, `dist-${Math.random().toString(36).slice(2)}`);
const res = await exportGame({
root,
@@ -130,6 +130,15 @@ describe('the exported page’s start screen', () => {
describe('Poki host page', () => {
+ it('loads YouTube SDK before game code and carries its fixed channel marker', async () => {
+ const { html, config } = await page(undefined, 'youtube');
+ const script = '<script src="https://www.youtube.com/game_api/v1"></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="youtube"'); expect(config.webChannel).toBe('youtube');
+ expect(html).not.toContain('crazygames-sdk'); expect(html).not.toContain('poki-sdk');
+ });
it('packages the client leaderboard key only for CrazyGames', async () => {
const key = Buffer.alloc(32, 7).toString('base64');
expect((await page(undefined, 'crazygames', key)).config.leaderboardEncryptionKey).toBe(key);
diff --git a/pipeline/tests/youtube-profile.test.ts b/pipeline/tests/youtube-profile.test.ts
new file mode 100644
index 000000000..4beeb0784
--- /dev/null
+++ b/pipeline/tests/youtube-profile.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { expect, it, vi } from 'vitest';
+import { initializeYouTube, type YouTubeSdk } from '../src/runtime/youtubeProfile';
+import { parseManifest } from '../src/project/format';
+import { projectExportOptions } from '../src/export/projectExportOptions';
+function fixture() {
+ const pause=new Set<()=>void>(),resume=new Set<()=>void>(),audio=new Set<(enabled:boolean)=>void>();
+ const sdk:YouTubeSdk={IN_PLAYABLES_ENV:true,
+ game:{firstFrameReady:vi.fn(),gameReady:vi.fn(),loadData:vi.fn(async()=>''),saveData:vi.fn(async(_data:string)=>{})},
+ system:{isAudioEnabled:()=>false,onPause:cb=>{pause.add(cb);return()=>{pause.delete(cb);};},onResume:cb=>{resume.add(cb);return()=>{resume.delete(cb);};},
+ onAudioEnabledChange:cb=>{audio.add(cb);return()=>{audio.delete(cb);};}},
+ ads:{requestInterstitialAd:vi.fn(async()=>{}),requestRewardedAd:vi.fn(async(_id:string)=>true)},
+ engagement:{sendScore:vi.fn(async(_score:{value:number})=>{})},};
+ return{sdk,pause:()=>{for(const cb of pause)cb();},resume:()=>{for(const cb of resume)cb();},audio:(value:boolean)=>{for(const cb of audio)cb(value);},listeners:()=>pause.size+resume.size+audio.size};
+}
+it('round-trips the named YouTube channel profile',async()=>{
+ const manifest=parseManifest({name:'Game',packaging:{profiles:{youtube:{platform:'web',platforms:{web:{channel:'youtube'}}}}}});
+ expect((await projectExportOptions(process.cwd(),manifest,'web','youtube')).webChannel).toBe('youtube');
+});
+it('loads before exposing storage, flushes through SDK and reports ordered readiness once',async()=>{
+ const {sdk}=fixture(),session=initializeYouTube(sdk,vi.fn());
+ expect(()=>session.storage.setStorageItem('key','wrong')).toThrow('load must succeed');
+ await expect(session.gameReady()).rejects.toThrow('firstFrameReady');session.firstFrameReady();session.firstFrameReady();
+ await session.load();session.storage.setStorageItem('key','value');await session.storage.flushStorage!();await session.gameReady();await session.gameReady();
+ expect(sdk.game.firstFrameReady).toHaveBeenCalledOnce();expect(sdk.game.gameReady).toHaveBeenCalledOnce();
+ expect(JSON.parse(vi.mocked(sdk.game.saveData).mock.calls[0][0]).items).toEqual({key:'value'});session.dispose();
+});
+it('disables no-op local and missing SDK services instead of acknowledging fake saves',async()=>{
+ for(const missing of [false,true]) {
+ const {sdk}=fixture();sdk.IN_PLAYABLES_ENV=false;const session=initializeYouTube(missing?undefined:sdk,vi.fn());
+ await session.load();expect(session.provider).toBeNull();expect(session.submitScore).toBeUndefined();
+ expect(()=>session.storage.setStorageItem('key','bad')).toThrow('unavailable');expect(sdk.game.loadData).not.toHaveBeenCalled();expect(sdk.game.saveData).not.toHaveBeenCalled();session.dispose();
+ }
+});
+it('preserves failed/corrupt cloud loads without writes',async()=>{
+ for(const raw of ['bad','{"version":2,"items":{}}']) {
+ const{sdk}=fixture();vi.mocked(sdk.game.loadData).mockResolvedValue(raw);const session=initializeYouTube(sdk,vi.fn());await session.load();
+ expect(()=>session.storage.setStorageItem('key','new')).toThrow('unavailable');expect(sdk.game.saveData).not.toHaveBeenCalled();session.dispose();
+ }
+});
+it('honors pause independently of audio mute and releases waiters only on resume',async()=>{
+ const f=fixture(),session=initializeYouTube(f.sdk,vi.fn()),mutes:boolean[]=[],pauses:boolean[]=[];
+ session.onAudioMute(value=>mutes.push(value));session.onPause(value=>pauses.push(value));f.audio(true);f.pause();f.pause();
+ let active=false;const pending=session.waitActive().then(()=>{active=true;});await Promise.resolve();expect(active).toBe(false);
+ f.audio(true);expect(mutes.at(-1)).toBe(true);f.resume();await pending;expect(mutes.at(-1)).toBe(false);expect(pauses).toEqual([false,true,false]);
+ session.dispose();expect(f.listeners()).toBe(0);
+});
+it('rejects pending work after disposal and ignores late SDK events',async()=>{
+ const f=fixture(),session=initializeYouTube(f.sdk,vi.fn());f.pause();const pending=expect(session.waitActive()).rejects.toThrow('disposed');
+ session.dispose();await pending;f.resume();await expect(session.waitActive()).rejects.toThrow('disposed');
+});
+it('grants only true rewarded results and preserves reward IDs, ad failures and score requirements',async()=>{
+ const{sdk}=fixture(),session=initializeYouTube(sdk,vi.fn()),reward=session.provider!.createRewardedAd!('training-credit');
+ expect(await reward.show()).toEqual({completed:true});expect(sdk.ads.requestRewardedAd).toHaveBeenCalledWith('training-credit');
+ vi.mocked(sdk.ads.requestRewardedAd).mockResolvedValueOnce(false);expect(await reward.show()).toEqual({completed:false});
+ vi.mocked(sdk.ads.requestRewardedAd).mockRejectedValueOnce(new Error('no fill'));await expect(reward.show()).rejects.toThrow('no fill');
+ await session.submitScore!(3);expect(sdk.engagement.sendScore).toHaveBeenCalledWith({value:3});
+ await expect(session.submitScore!(1.5)).rejects.toThrow('safe integers');reward.destroy?.();await expect(reward.show()).rejects.toThrow('destroyed');session.dispose();
+});
+it('keeps oversized pause flushes dirty without sending a truncated or oversized save',async()=>{
+ const f=fixture(),warn=vi.fn(),session=initializeYouTube(f.sdk,warn);await session.load();session.storage.setStorageItem('large','x'.repeat(70000));f.pause();
+ await expect(session.storage.flushStorage!()).rejects.toThrow('64 KiB');expect(f.sdk.game.saveData).not.toHaveBeenCalled();
+ f.resume();await session.storage.flushStorage!();expect(f.sdk.game.saveData).toHaveBeenCalledOnce();session.dispose();
+});
+it('does not activate a cloud load after its timeout or start an abandoned paused ad',async()=>{
+ const f=fixture();let finish!:(data:string)=>void;
+ vi.mocked(f.sdk.game.loadData).mockReturnValue(new Promise(resolve=>{finish=resolve;}));
+ const session=initializeYouTube(f.sdk,vi.fn(),5);await session.load();finish('');await Promise.resolve();
+ expect(()=>session.storage.setStorageItem('key','bad')).toThrow('unavailable');
+ f.pause();const unit=session.provider!.createRewardedAd!('credit'),pending=expect(unit.show()).rejects.toThrow('destroyed');
+ unit.destroy?.();f.resume();await pending;expect(f.sdk.ads.requestRewardedAd).not.toHaveBeenCalled();session.dispose();
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index b6015e1da..af0d7eb47 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5567,7 +5567,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | "crazygames" | undefined
+webChannel: "poki" | "crazygames" | "youtube" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index c1f9a0bb6..77ebf7a01 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5770,7 +5770,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | "crazygames" | undefined
+webChannel: "poki" | "crazygames" | "youtube" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e1eb9970d..bf4b86850 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.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" | "crazygames" | undefined
+webChannel: "poki" | "crazygames" | "youtube" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index f7e423be5..90815168d 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5855,7 +5855,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | "crazygames" | undefined
+webChannel: "poki" | "crazygames" | "youtube" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 6ebbdf2f2..3e650e062 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5569,7 +5569,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
-webChannel: "poki" | "crazygames" | undefined
+webChannel: "poki" | "crazygames" | "youtube" | undefined
worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.ts
index 8718a296e..b7d37bc68 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' | 'crazygames';
+ webChannel?: 'poki' | 'crazygames' | 'youtube';
/** Public client encryption key for invited CrazyGames leaderboards; never a server API key. */
leaderboardEncryptionKey?: string;
/** Project-relative path of the scene the game boots into. */
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index fdb337071..88feefed0 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,10 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(youtube): connect Playables readiness pause and cloud saves':
+ { note: 'YouTube Playables Web exports honor host readiness and persistence.' },
+ 'feat(settings): add YouTube Playables Web channel':
+ { note: 'YouTube Playables Web exports honor host readiness and persistence.' },
'perf(text): reclaim unused glyph pages at frame boundaries':
{ note: 'Unused text atlas pages retire at frame boundaries.' },
'feat(app): hold execution across frames input and media':
diff --git a/tools/tests/training-save.test.ts b/tools/tests/training-save.test.ts
index a4899ecee..8e904f7a7 100644
--- a/tools/tests/training-save.test.ts
+++ b/tools/tests/training-save.test.ts
@@ -38,3 +38,16 @@ it('surfaces unreadable storage as session-only progress without writing fallbac
const save=new TrainingSave(storage);expect(save.load()).toBe(0);save.save(1);
expect(storage.setString).not.toHaveBeenCalled();expect(save.message).toContain('session');
});
+it('reports async saving only after acknowledgment and preserves pending status for newer writes',async()=>{
+ const {storage}=fixture();let first!:()=>void,second!:()=>void;
+ const flush=vi.fn().mockImplementationOnce(()=>new Promise<void>(resolve=>{first=resolve;}))
+ .mockImplementationOnce(()=>new Promise<void>(resolve=>{second=resolve;}));
+ const save=new TrainingSave({...storage,flush});save.load();const a=save.saveAsync(1),b=save.saveAsync(2);
+ first();await a;expect(save.message).toBe('Saving progress...');second();await b;expect(save.message).toContain('acknowledged');
+});
+it('does not acknowledge failed async writes or unreadable progress',async()=>{
+ const {storage}=fixture(),flush=vi.fn(async()=>{throw new Error('offline');}),save=new TrainingSave({...storage,flush});save.load();
+ await save.saveAsync(1);expect(save.message).toContain('Save failed');
+ storage.getString.mockImplementation(()=>{throw new Error('unavailable');});save.load();flush.mockClear();await save.saveAsync(2);
+ expect(flush).not.toHaveBeenCalled();
+});
diff --git a/tools/tests/youtube-training.e2e.mjs b/tools/tests/youtube-training.e2e.mjs
new file mode 100644
index 000000000..6189927f6
--- /dev/null
+++ b/tools/tests/youtube-training.e2e.mjs
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/** Explicit SDK mocks for the exported YouTube profile; official certification is separate. */
+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),flag=name=>args[args.indexOf(name)+1];if(!args.includes('--dir'))throw Error('Expected --dir <YouTube export>');
+const root=fs.realpathSync(flag('--dir')),out=path.resolve(args.includes('--out')?flag('--out'):'output/youtube-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 Error('Unsupported entry');return[file];});
+const identities=Object.fromEntries(files().map(file=>[file,sha(path.join(root,file))]));
+const report={headless:true,mode:'local-mock',status:'failed',identities,verifierSha256:sha(new URL(import.meta.url)),cases:[]};
+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',file=fs.realpathSync(path.resolve(root,name));
+ if(!file.startsWith(root+path.sep)||!fs.statSync(file).isFile())throw 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']});
+try {
+ for(const mode of ['normal','local-noop','sdk-missing','load-failed','paused-boot']) {
+ 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);__audioContexts.push(this);}};});
+ await context.route('**/*',route=>{
+ const url=route.request().url();if(url.startsWith(origin+'/'))return route.continue();
+ if(url==='https://www.youtube.com/game_api/v1')return route.fulfill({contentType:'text/javascript',body:mode==='sdk-missing'?'':`
+ window.__events=[];window.__pauseListeners=new Set();window.__resumeListeners=new Set();window.__muteListeners=new Set();window.__scores=[];
+ ${mode==='normal'?`if(localStorage.getItem('__youtube_mock_data')===null)localStorage.setItem('__youtube_mock_data',JSON.stringify({version:1,items:{'esengine:mobile-controls.training-best-score':'5'}}));`:''}
+ const record=event=>__events.push(event);const sdk={IN_PLAYABLES_ENV:${mode!=='local-noop'},
+ game:{firstFrameReady(){record('first');window.__firstLoading=!!document.getElementById('es-splash')},
+ gameReady(){record('ready');window.__readyLoading=!!document.getElementById('es-splash')},
+ loadData(){record('load');return ${mode==='load-failed'?'Promise.reject(new Error("offline"))':'Promise.resolve(localStorage.getItem("__youtube_mock_data")??"")'}},
+ saveData(data){record('save');localStorage.setItem('__youtube_mock_data',data);return Promise.resolve()}},
+ system:{isAudioEnabled(){return false},onAudioEnabledChange(cb){__muteListeners.add(cb);return()=>__muteListeners.delete(cb)},
+ onPause(cb){__pauseListeners.add(cb);${mode==='paused-boot'?'cb();':''}return()=>__pauseListeners.delete(cb)},onResume(cb){__resumeListeners.add(cb);return()=>__resumeListeners.delete(cb)}},
+ ads:{requestRewardedAd(id){record('reward');window.__rewardId=id;return new Promise((resolve,reject)=>{window.__rewardResolve=resolve;window.__rewardReject=reject;})},
+ requestInterstitialAd(){record('midgame');return Promise.resolve()}},engagement:{sendScore(score){record('score');__scores.push(score);return Promise.resolve()}}};
+ window.ytgame=sdk;window.__pause=()=>{for(const cb of __pauseListeners)cb()};window.__resume=()=>{for(const cb of __resumeListeners)cb()};
+ window.__audio=value=>{for(const cb of __muteListeners)cb(value)};
+ `});
+ observation.unexpectedRequests.push(url);return route.abort();
+ });
+ try {
+ await page.goto(origin+'/?headless');
+ if(mode==='paused-boot') {
+ await page.waitForFunction(()=>window.__resumeListeners?.size>0);await page.waitForTimeout(150);
+ assert.deepEqual(await page.evaluate(()=>__events),[]);assert.equal(await page.evaluate(()=>!!window.__estellaCooked),false);await page.evaluate(()=>__resume());
+ }
+ await page.waitForFunction(()=>window.__estellaCooked?.probe(['DeviceStatus']).at.DeviceStatus?.text,{}, {timeout:30000});
+ await page.waitForFunction(()=>!document.getElementById('es-splash'));
+ if(mode!=='sdk-missing') {await page.waitForFunction(()=>__events.includes('ready'));assert(await page.evaluate(()=>__firstLoading));assert.equal(await page.evaluate(()=>__readyLoading),false);}
+ const phase=value=>page.waitForFunction(v=>window.__estellaCooked?.probe(['DeviceStatus']).at.DeviceStatus?.text?.startsWith(v),value.toUpperCase());
+ const click=async name=>{const box=await page.evaluate(n=>__estellaCooked.probe([n]).at[n],name);assert(box);await page.mouse.click(400+box.x,225-box.y);};
+ const hosted=mode!=='local-noop'&&mode!=='sdk-missing';
+ await click('TrainingStart');await phase('playing');
+ if(hosted) {
+ await page.waitForFunction(()=>__audioContexts.length>0&&__audioContexts.every(c=>c.state==='suspended'));await page.evaluate(()=>__audio(true));
+ await page.waitForFunction(()=>__audioContexts.every(c=>c.state==='running'));
+ await page.evaluate(()=>__pause());await page.waitForFunction(()=>__audioContexts.every(c=>c.state==='suspended'));
+ const held=await page.evaluate(()=>__estellaCooked.probe(['Player']).at.Player);
+ await page.keyboard.press('KeyD');await click('TrainingPause');await page.waitForTimeout(150);await phase('playing');
+ assert.deepEqual(await page.evaluate(()=>__estellaCooked.probe(['Player']).at.Player),held);
+ await page.evaluate(()=>{document.dispatchEvent(new Event('visibilitychange'));window.dispatchEvent(new Event('pageshow'));});
+ assert(await page.evaluate(()=>__audioContexts.every(c=>c.state==='suspended')));await page.evaluate(()=>__resume());
+ await page.waitForFunction(()=>__audioContexts.every(c=>c.state==='running'));
+ await click('TrainingReward');await phase('ad');await page.evaluate(()=>__rewardResolve(true));await phase('playing');
+ assert.match(await page.evaluate(()=>__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text),/Credits: 1/);
+ if(mode!=='load-failed') {
+ await page.waitForFunction(()=>__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text.includes('Save acknowledged'));
+ }
+ const at=await page.evaluate(()=>__estellaCooked.probe(['Player','Target']).at);
+ if(Math.abs(at.Target.y-at.Player.y)>15) {
+ const vertical=at.Target.y>at.Player.y?'KeyW':'KeyS';await page.keyboard.down(vertical);
+ await page.waitForFunction(()=>{const p=__estellaCooked.probe(['Player','Target']).at;return Math.abs(p.Player.y-p.Target.y)<15;});await page.keyboard.up(vertical);
+ }
+ const current=await page.evaluate(()=>__estellaCooked.probe(['Player','Target']).at),horizontal=current.Target.x>current.Player.x?'KeyD':'KeyA';
+ await page.keyboard.down(horizontal);await page.waitForFunction(()=>{const p=__estellaCooked.probe(['Player','Target']).at;return Math.hypot(p.Player.x-p.Target.x,p.Player.y-p.Target.y)<60;});await page.keyboard.up(horizontal);
+ for(let hit=0;hit<3;hit++){await page.keyboard.press('Space',{delay:80});await page.waitForTimeout(80);}
+ await phase('finished');await click('TrainingScore');
+ if(mode!=='load-failed') {
+ await page.waitForFunction(()=>__scores.length===1);
+ observation.score=await page.evaluate(()=>({sent:__scores[0].value,saved:Number(JSON.parse(localStorage.getItem('__youtube_mock_data')).items['esengine:mobile-controls.training-best-score'])}));
+ assert.deepEqual(observation.score,{sent:mode==='normal'?5:3,saved:mode==='normal'?5:3});
+ await page.reload();
+ if(mode==='paused-boot'){await page.waitForFunction(()=>window.__resumeListeners?.size>0);await page.evaluate(()=>__resume());}
+ await phase('menu');await page.waitForFunction(()=>!document.getElementById('es-splash'));
+ assert.match(await page.evaluate(()=>__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text),/Credits: 1/);
+ } else {
+ await page.waitForFunction(()=>__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text.includes('Score submission failed'));
+ assert.equal(await page.evaluate(()=>__scores.length),0);assert.equal(await page.evaluate(()=>localStorage.getItem('__youtube_mock_data')),null);
+ }
+ } else {
+ assert.equal(await page.evaluate(async()=>(await import('esengine')).Scores.available),false);
+ observation.storage=await page.evaluate(async()=>{try{(await import('esengine')).Storage.setString('test','bad');return'bad';}catch(error){return String(error);}});
+ assert.match(observation.storage,/unavailable/);assert.equal(await page.evaluate(()=>localStorage.getItem('esengine:test')),null);
+ }
+ const file=mode+'.png';await page.screenshot({path:path.join(out,file)});observation.screenshot={file,sha256:sha(path.join(out,file))};
+ 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('YouTube training: 5 headless SDK mock paths passed');