A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(youtube): validate export bundle constraints
yhh28c325b56f1b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c104e4fea..d941dee65 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Added+- **YouTube exports check stored bundle constraints.** Exports reject total packages at or above 250 MiB, individual files at or above 30 MiB, more than 8000 files and unsupported filenames. Cloud envelopes at exactly 3 MiB are rejected before staging. Recommendations and static initial-content estimates appear as warnings in both CLI and editor export results. Headless observations record local ready time and startup heap samples without claiming official transfer, peak heap or device certification.+- **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-15diff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdxindex 874747a29..7d57285f1 100644--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx@@ -355,6 +355,12 @@ submission; these observations do not certify devices or production ad fill.## YouTube Playables Web exports+Export checks stored total size below 250 MiB, each file below 30 MiB, at most+8000 files and supported filenames. Both CLI and editor show recommendation+warnings. Static initial content is an estimate; actual compressed transfer+through gameReady must remain below 30 MiB. Verify loading and peak heap on+target devices and in the official Test Suite.+Select **YouTube Playables** in Web packaging or set`packaging.platforms.web.channel` to `"youtube"`. The Mobile Controls exampleprovides a named `youtube` profile. The official SDK loads before game code;@@ -366,7 +372,7 @@ player pause. Game-owned asynchronous work must cooperate with executionnotifications. Visibility events do not override SDK pause. Reward creditsrequire 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+or `SaveManager.saveAsync()` to observe SDK save acknowledgment. Saves at or above3 MiB are rejected; pause-time saves above 64 KiB remain pending. The examplesends the highest score only after saving that value successfully.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.mdxindex 636a5a547..f8bc93427 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@@ -315,6 +315,11 @@ Inspector 会提供测试上下文。训练示例的真实 SDK 初始化、加## YouTube Playables Web 导出+导出检查总包低于 250 MiB、单文件低于 30 MiB、最多 8000 个文件,以及+文件名只使用允许的字符。CLI 与编辑器都会显示建议限额警告。+静态首包只是估算;截至 gameReady 的实际压缩传输须低于 30 MiB,+加载速度与峰值堆内存仍须在目标设备和官方 Test Suite 中测量。+在 Web 打包设置选择 **YouTube Playables**,或将`packaging.platforms.web.channel` 设置为 `"youtube"`。Mobile Controls提供同名导出档。官方 SDK 在游戏代码前加载:加载画面绘制后通知diff --git a/examples/mobile-controls/README.md b/examples/mobile-controls/README.mdindex bdd8d07f1..3a2f162dd 100644--- a/examples/mobile-controls/README.md+++ b/examples/mobile-controls/README.md@@ -132,6 +132,13 @@ and [client score submission](https://docs.crazygames.com/sdk/leaderboards-clien## YouTube Playables Web training profile+The export checks stored total size (below 250 MiB), each file (below 30 MiB),+file count (at most 8000) and allowed filename characters. It also warns about+files at or above 512 KiB and static initial content at or above 15 MiB.+Actual compressed transfer through gameReady must be below 30 MiB and needs+runtime measurement. The headless report records local ready time and a startup+heap sample, which do not certify device loading or peak gameplay heap.+Export with `node pipeline/bin/estella.mjs export examples/mobile-controls--profile youtube --out output/youtube-training-web`. The editor also exposesYouTube Playables under Web channel settings. The official SDK loads beforediff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 55c2cf7e7..4df894ce9 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -79,6 +79,7 @@ import { BUILTIN_PLATFORMS, compileTargetFor, isNativePlatform, desktopTemplateFimport type { DesktopPackaging, ProjectFeatures, ProjectPackaging, SteamPackaging } from '../project/format';import type { SizeBudget } from '../project/sizeBudget';import { measureBuild, type BuildSizeReport } from './sizeReport';+import { checkYouTubeBundle } from './youtubeBundle';import { sizeSettingsOf } from './sizeHistory';import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';import { subsystemGapWarnings, targetGaps } from '../project/targetSupport';@@ -632,7 +633,16 @@ export interface ExportGameOptions {* defines for itself would have none. See sizeReport.ts for what is counted.*/export async function exportGame(opts: ExportGameOptions): Promise<ExportGameResult> {- const result = await attachSizeReport(await produceExport(opts), opts);+ let result = await attachSizeReport(await produceExport(opts), opts);+ if (result.ok && result.platform === 'web' && opts.webChannel === 'youtube') {+ try {+ const checked = await checkYouTubeBundle(result.outDir, result.size?.initialBytes ?? 0);+ result = { ...result, ok: checked.errors.length === 0,+ errors: [...result.errors, ...checked.errors], warnings: [...result.warnings, ...checked.warnings] };+ } catch (error) {+ result = { ...result, ok: false, errors: [...result.errors, `YouTube bundle validation failed: ${String(error)}`] };+ }+ }const exposed = committableSecrets(opts.root, opts.secretFiles ?? []);return exposed.length > 0 ? { ...result, warnings: [...result.warnings, ...exposed] } : result;}diff --git a/pipeline/src/export/youtubeBundle.ts b/pipeline/src/export/youtubeBundle.tsnew file mode 100644index 000000000..58ceb7eaa--- /dev/null+++ b/pipeline/src/export/youtubeBundle.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { readdir, stat } from 'node:fs/promises';+import path from 'node:path';++const MiB = 1024 * 1024;+/** Stored package checks; initial transfer/load time still require runtime measurement.+ * https://developers.google.com/youtube/gaming/playables/certification/requirements_stability */+export function checkYouTubeFiles(files: readonly { path: string; bytes: number }[], initialBytes: number) {+ const errors: string[] = [], warnings: string[] = [];+ const total = files.reduce((sum, file) => sum + file.bytes, 0);+ if (total >= 250 * MiB) errors.push('YouTube: total bundle must be less than 250 MiB.');+ if (files.length > 8000) errors.push(`YouTube: bundle has ${files.length} files; at most 8000 are allowed.`);+ for (const file of files) {+ if (file.bytes >= 30 * MiB) errors.push(`YouTube: ${file.path} must be less than 30 MiB.`);+ if (!file.path.split('/').every(part => /^[A-Za-z0-9_.-]+$/.test(part))) {+ errors.push(`YouTube: ${file.path} contains unsupported filename characters; use letters, digits, _, - or .`);+ }+ }+ const large = files.filter(file => file.bytes >= 512 * 1024);+ if (large.length) warnings.push(`YouTube: ${large.length} file(s) exceed the recommended size below 512 KiB: ${large.slice(0, 5).map(file => file.path).join(', ')}.`);+ if (initialBytes >= 15 * MiB) warnings.push(`YouTube: static initial-content estimate is ${(initialBytes / MiB).toFixed(2)} MiB, above the recommendation below 15 MiB. Measure actual compressed transfer through gameReady; it must be below 30 MiB.`);+ warnings.push('YouTube: static bundle checks do not measure actual initial transfer, loading time or peak heap. Verify transfer through gameReady, interactivity under 5 seconds and peak JavaScript heap at most 512 MB in the official Test Suite and target devices.');+ return { errors, warnings };+}++export async function checkYouTubeBundle(root: string, initialBytes: number) {+ const files: { path: string; bytes: number }[] = [];+ async function walk(relative: string): Promise<void> {+ for (const entry of await readdir(path.join(root, relative), { withFileTypes: true })) {+ const name = relative ? `${relative}/${entry.name}` : entry.name;+ if (entry.isDirectory()) await walk(name);+ else if (entry.isFile()) files.push({ path: name, bytes: (await stat(path.join(root, name))).size });+ else throw new Error(`YouTube bundle contains an unsupported filesystem entry: ${name}`);+ }+ }+ await walk('');+ return checkYouTubeFiles(files, initialBytes);+}diff --git a/pipeline/src/runtime/youtubeProfile.ts b/pipeline/src/runtime/youtubeProfile.tsindex 8a5b3c15b..90ee6d3cc 100644--- a/pipeline/src/runtime/youtubeProfile.ts+++ b/pipeline/src/runtime/youtubeProfile.ts@@ -45,7 +45,7 @@ export function initializeYouTube(sdk: YouTubeSdk | undefined, warn: (message: sif (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) });+ }, { maxBytes: 3 * 1024 * 1024 - 1, 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); }diff --git a/pipeline/tests/export-splash.test.ts b/pipeline/tests/export-splash.test.tsindex cfd922d76..a85cccdd8 100644--- a/pipeline/tests/export-splash.test.ts+++ b/pipeline/tests/export-splash.test.ts@@ -131,13 +131,14 @@ 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 { html, config, warnings } = 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');+ expect(warnings.some(warning => warning.includes('static bundle checks do not measure'))).toBe(true);});it('packages the client leaderboard key only for CrazyGames', async () => {const key = Buffer.alloc(32, 7).toString('base64');diff --git a/pipeline/tests/youtube-bundle.test.ts b/pipeline/tests/youtube-bundle.test.tsnew file mode 100644index 000000000..e4b7f3f56--- /dev/null+++ b/pipeline/tests/youtube-bundle.test.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { it, expect } from 'vitest';+import { mkdtemp, mkdir, writeFile, rm, symlink } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { checkYouTubeFiles, checkYouTubeBundle } from '../src/export/youtubeBundle';+const MiB=1024*1024;+it('applies strict total and per-file boundaries independently of initial estimate',()=>{+ expect(checkYouTubeFiles([{path:'game.wasm',bytes:30*MiB-1}],0).errors).toEqual([]);+ expect(checkYouTubeFiles([{path:'game.wasm',bytes:30*MiB}],0).errors).toContain('YouTube: game.wasm must be less than 30 MiB.');+ const files=Array.from({length:10},(_,i)=>({path:`chunk-${i}.bin`,bytes:25*MiB}));+ expect(checkYouTubeFiles(files,0).errors).toEqual(['YouTube: total bundle must be less than 250 MiB.']);+ files[0].bytes--;expect(checkYouTubeFiles(files,0).errors).toEqual([]);+});+it('checks every filename and the inclusive file-count ceiling',()=>{+ const files=Array.from({length:8000},(_,i)=>({path:`assets/${i}.bin`,bytes:0}));+ expect(checkYouTubeFiles(files,0).errors).toEqual([]);+ files.push({path:'assets/bad name.bin',bytes:0});+ const result=checkYouTubeFiles(files,0);expect(result.errors).toHaveLength(2);+ expect(result.errors[0]).toContain('8001');expect(result.errors[1]).toContain('bad name.bin');+});+it('does not mistake stored initial estimates or startup samples for certification',()=>{+ const result=checkYouTubeFiles([{path:'game.js',bytes:512*1024}],30*MiB);+ expect(result.errors).toEqual([]);expect(result.warnings).toHaveLength(3);+ expect(result.warnings[1]).toContain('compressed transfer through gameReady');+ expect(result.warnings[2]).toContain('peak');+});+it('walks nested output files and rejects links rather than silently excluding them',async()=>{+ const root=await mkdtemp(path.join(tmpdir(),'youtube-bundle-'));+ try {+ await mkdir(path.join(root,'assets'));await writeFile(path.join(root,'assets','bad name.bin'),'test');+ expect((await checkYouTubeBundle(root,0)).errors[0]).toContain('assets/bad name.bin');+ await symlink(path.join(root,'assets'),path.join(root,'linked'),'junction');+ await expect(checkYouTubeBundle(root,0)).rejects.toThrow('unsupported filesystem entry');+ } finally {await rm(root,{recursive:true,force:true,maxRetries:10,retryDelay:50});}+});diff --git a/pipeline/tests/youtube-profile.test.ts b/pipeline/tests/youtube-profile.test.tsindex 4beeb0784..960a0ca19 100644--- a/pipeline/tests/youtube-profile.test.ts+++ b/pipeline/tests/youtube-profile.test.ts@@ -71,3 +71,9 @@ it('does not activate a cloud load after its timeout or start an abandoned pausef.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();});+it('rejects an envelope exactly at 3 MiB without staging or sending the value',async()=>{+ const f=fixture(),session=initializeYouTube(f.sdk,vi.fn());await session.load();+ const overhead=new TextEncoder().encode(JSON.stringify({version:1,items:{key:''}})).byteLength;+ expect(()=>session.storage.setStorageItem('key','x'.repeat(3*1024*1024-overhead))).toThrow('byte limit');+ expect(session.storage.getStorageItem('key')).toBeNull();expect(f.sdk.game.saveData).not.toHaveBeenCalled();session.dispose();+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 88feefed0..512ab42cb 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(youtube): validate export bundle constraints':+ { note: 'YouTube exports check stored bundle constraints.' },'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':diff --git a/tools/tests/youtube-training.e2e.mjs b/tools/tests/youtube-training.e2e.mjsindex 6189927f6..425d5c00d 100644--- a/tools/tests/youtube-training.e2e.mjs+++ b/tools/tests/youtube-training.e2e.mjs@@ -28,7 +28,10 @@ try {${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')},+ gameReady(){record('ready');window.__readyLoading=!!document.getElementById('es-splash');+ window.__readyPerformance={gameReadyMs:performance.now(),jsHeapAtReadyBytes:performance.memory?.usedJSHeapSize??null,+ localEncodedResourceBytes:performance.getEntriesByType('resource').filter(e=>e.name.startsWith(location.origin+'/')).reduce((sum,e)=>sum+e.encodedBodySize,0),+ scope:'Local resource timing through mocked gameReady; excludes page and mock SDK transport. Heap is a startup sample, not a gameplay peak.'}},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)},@@ -48,7 +51,8 @@ try {}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);}+ if(mode!=='sdk-missing') {await page.waitForFunction(()=>__events.includes('ready'));assert(await page.evaluate(()=>__firstLoading));assert.equal(await page.evaluate(()=>__readyLoading),false);+ observation.performance=await page.evaluate(()=>__readyPerformance);assert(observation.performance.gameReadyMs>0);}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';