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(playable): an ad network is a profile, so a project can add the one we lack
esenginedaaa4ee2aa05
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex fac1011c7..f733b8b2c 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -33,6 +33,7 @@ import { exportWeChat } from './exportWeChat';import { exportMiniGame } from './exportMiniGame';import type { MiniGameExportProfile } from './miniGameExportProfile';import { exportPlayable } from './exportPlayable';+import type { PlayableAdProfile } from './playableAdProfile';import type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL } from './esengineResolve';import { orientationCss, orientationOverlayHtml, orientationLockScript, orientationLockCspHash, type ScreenOrientation } from './orientationHtml';@@ -366,6 +367,9 @@ export async function exportGame(opts: {platform?: ExportPlatform;/** Playable host source (src/playableHost.ts). */playableHostEntry?: string;+ /** The ad network a playable targets (`packaging.platforms.playable.network`),+ * resolved by the caller since a project can define its own. Absent ⇒ generic. */+ playableAdProfile?: PlayableAdProfile;/** Desktop installer id (Project Settings → Packaging → Desktop); default com.estella.<slug>. */desktopAppId?: string;/** Desktop product/display name (Project Settings); default the project title. */@@ -497,6 +501,7 @@ export async function exportGame(opts: {screenFit: opts.screenFit,uiTheme: opts.uiTheme,uiThemeColors: opts.uiThemeColors,+ adProfile: opts.playableAdProfile,onProgress: opts.onProgress,});}diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex 57fd3d6ae..9098440b3 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -22,6 +22,7 @@ import { cookAssets } from './cookAssets';import type { OnExportProgress } from './exportProgress';import { esengineAlias } from './esengineResolve';import { orientationCss, orientationOverlayHtml, orientationLockScript, type ScreenOrientation } from './orientationHtml';+import { genericPlayableProfile, playableAdInjection, type PlayableAdProfile } from './playableAdProfile';import {sceneUsesPhysics, detectSpineVersion, detectSpineVersionJson,spineModuleId, SIDE_MODULE_FILE, type SpineVersion,@@ -54,13 +55,22 @@ const mimeOf = (p: string): string => MIME[path.extname(p).slice(1).toLowerCase(/** Escape `</script` so inlined content can't close the host <script> early. */const inlineSafe = (s: string): string => s.replace(/<\/script/gi, '<\\/script');-function indexHtml(title: string, globals: string, bundle: string, orientation: ScreenOrientation): string {+/** `network` is what the chosen ad-network profile contributes: markup for `<head>`+ * and the bridge script that gives `playableCta()` somewhere to go. The bridge runs+ * BEFORE the game bundle, so a CTA fired during boot still resolves. */+function indexHtml(+ title: string,+ globals: string,+ bundle: string,+ orientation: ScreenOrientation,+ network: { head: string; bridge: string },+): string {return `<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />- <title>${title}</title>+ <title>${title}</title>${network.head ? `\n ${network.head}` : ''}<style>* { margin: 0; padding: 0; box-sizing: border-box; }html, body { width: 100%; height: 100%; overflow: hidden; background: #0e121b; }@@ -71,7 +81,7 @@ function indexHtml(title: string, globals: string, bundle: string, orientation:<body><canvas id="canvas"></canvas>${orientationOverlayHtml(orientation)}- ${orientationLockScript(orientation)}+ ${orientationLockScript(orientation)}${network.bridge ? `\n <script>${inlineSafe(network.bridge)}</script>` : ''}<script>${inlineSafe(globals)}</script><script>${inlineSafe(bundle)}</script></body>@@ -162,6 +172,9 @@ export async function exportPlayable(opts: {uiTheme?: 'light';/** Project theme color overrides (role → #rrggbbaa hex) — the host parses them. */uiThemeColors?: Record<string, string>;+ /** The ad network this package targets (Project Settings → Packaging → Playable):+ * its size cap, its `<head>` markup and its click-through API. Absent ⇒ generic. */+ adProfile?: PlayableAdProfile;onProgress?: OnExportProgress;}): Promise<ExportPlayableResult> {const title = opts.title ?? 'Game';@@ -285,15 +298,20 @@ export async function exportPlayable(opts: {(opts.screenFit && opts.screenFit.scaleMode >= 0 ? `window.__GAME_SCREENFIT__=${JSON.stringify(opts.screenFit)};` : '') +(opts.uiTheme === 'light' ? `window.__GAME_UITHEME__='light';` : '') +(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? `window.__GAME_UITHEMECOLORS__=${JSON.stringify(opts.uiThemeColors)};` : '');+ const adProfile = opts.adProfile ?? genericPlayableProfile;+ const network = playableAdInjection(adProfile, { title, orientation });const outFile = path.join(absOut, 'index.html');- await writeFile(outFile, indexHtml(title, globals, bundle, orientation));+ await writeFile(outFile, indexHtml(title, globals, bundle, orientation, network));await rm(cookDir, { recursive: true, force: true });const bytes = (await stat(outFile)).size;- // Ad networks cap playable size (Facebook ~2MB, Google ~5MB). A full WASM engine- // + assets typically exceeds this — surface it rather than silently ship a reject.- if (bytes > 2 * 1024 * 1024) {- warnings.push(`playable is ~${(bytes / 1024 / 1024).toFixed(1)}MB — likely over ad-network limits (Facebook ~2MB, Google ~5MB).`);+ // A full WASM engine + assets routinely exceeds what a network accepts, and each+ // network caps differently — say which cap and where it comes from, so this reads+ // as a fact to check rather than a number to trust.+ if (bytes > adProfile.maxBytes) {+ warnings.push(`playable is ~${(bytes / 1024 / 1024).toFixed(1)}MB, over the `+ + `${(adProfile.maxBytes / 1024 / 1024).toFixed(1)}MB limit for ${adProfile.label} `+ + `(${adProfile.limitNote}).`);}return { ok: errors.length === 0, platform: 'playable', outDir: absOut, included: cook.included.length, bytes, warnings, errors };diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 1c9d4d9b3..96e300b6b 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -40,7 +40,11 @@ import { ensureProjectShaderTwins } from './shaderTwins';import { installCrashCapture, logsDir } from './resilience';import { mcpMode, startMcpEndpoint } from './mcpEndpoint';import { checkForUpdate } from './updateCheck';-import { listPlatforms, loadProjectPlatform, createProjectPlatform, type PlatformRuntimeDirs } from './platformCatalog';+import {+ listPlatforms, loadProjectPlatform, createProjectPlatform,+ listPlayableNetworks, loadPlayableProfile,+ type PlatformRuntimeDirs, type ProjectPlatformKind,+} from './platformCatalog';import { resolveLayout, resolveScripts, resolveOrientation, resolveScreenFit, resolveAppId, type ExportPlatform } from '../src/project/format';import type { WorkspaceState } from '../src/project/format';@@ -788,15 +792,19 @@ ipcMain.handle('project:cookAssets', async (_e, outDir?: string) => {// runs, and can list the platforms the project defines for itself.ipcMain.handle('project:listPlatforms', async () => listPlatforms(projectRoot, platformRuntimeDirs()));+// The ad networks a playable can target — built-ins plus the project's own, so the+// Packaging page offers a network the editor never heard of on equal terms.+ipcMain.handle('project:listPlayableNetworks', async () => listPlayableNetworks(projectRoot));+// Scaffold a project platform — both halves, already joined. The editor writes// them because the SHAPE of a vendor (two files linked by runtimeProfile) is the// part that is hard to know before you have seen one.-ipcMain.handle('project:createPlatform', async (_e, id: string, label: string) => {+ipcMain.handle('project:createPlatform', async (_e, id: string, label: string, kind?: ProjectPlatformKind) => {const root = requireRoot();const manifest = await readManifest(root);// The runtime half is game code, so it belongs beside the project's scripts.const scriptsDir = path.dirname(resolveScripts(manifest).main ?? 'src/main.ts');- return createProjectPlatform(root, id, label, scriptsDir);+ return createProjectPlatform(root, id, label, scriptsDir, kind);});// Export a runnable web build (play == ship): cook + game host + wasm + index.html.@@ -819,6 +827,17 @@ ipcMain.handle(? await loadProjectPlatform(root, opts.platform, dirs): null;const plat = manifest.packaging?.platforms;+ // The playable's ad network: a built-in profile or one the project defined. An id+ // that resolves to nothing does not fail the export — it ships generic and says so,+ // because a package with no click-through still previews and still installs.+ const playableAdProfile = opts?.platform === 'playable'+ ? await loadPlayableProfile(root, plat?.playable?.network)+ : null;+ if (opts?.platform === 'playable' && !playableAdProfile) {+ e.sender.send('project:exportProgress', {+ phase: `ad network "${plat?.playable?.network}" not found — packaging generic`,+ });+ }const ySortLayers =(manifest.features?.rendering?.ySortLayers ?? []).reduce((m, i) => m | (1 << i), 0) >>> 0;const colorSpace = manifest.features?.rendering?.colorSpace === 'linear' ? 'linear' as const : undefined;@@ -847,6 +866,7 @@ ipcMain.handle(title: manifest.name,platform: opts?.platform,miniGameProfile: projectPlatform?.profile,+ playableAdProfile: playableAdProfile ?? undefined,desktopAppId: plat?.desktop?.appId,desktopProductName: plat?.desktop?.productName,wechatAppid: plat?.wechat?.appid,diff --git a/desktop/electron/platformCatalog.ts b/desktop/electron/platformCatalog.tsindex 5a5f6458e..209105906 100644--- a/desktop/electron/platformCatalog.ts+++ b/desktop/electron/platformCatalog.ts@@ -26,6 +26,10 @@ import { readdir, mkdir, writeFile } from 'node:fs/promises';import path from 'node:path';import { pathToFileURL } from 'node:url';import { defaultMiniGameEntry } from './miniGameExportProfile';+import {+ BUILTIN_PLAYABLE_PROFILES, builtinPlayableProfile, genericPlayableProfile,+ type PlayableAdProfile,+} from './playableAdProfile';import { BUILTIN_PLATFORMS, type PlatformPrereq } from '../src/project/platforms';import type { MiniGameExportProfile, MiniGameConfigContext } from './miniGameExportProfile';@@ -159,11 +163,21 @@ export const MINIGAME_PROFILE_DEFAULTS = {emitEntry: defaultMiniGameEntry,};+/**+ * What a project profile declares itself to be. A mini-game vendor is a whole+ * PLATFORM (its own host, packaging and runtime); a playable ad network is a+ * variant of the built-in `playable` target (same browser host, same single-file+ * pipeline — only the network's cap, head markup and click-through API differ).+ * Absent ⇒ mini-game, which is what every profile written before this meant.+ */+export type ProjectPlatformKind = 'minigame' | 'playable';+/** The shape a `.esengine/platforms/<id>.mjs` default-exports. */-export interface ProjectPlatformModule extends Partial<MiniGameExportProfile> {+export interface ProjectPlatformModule extends Partial<MiniGameExportProfile>, Partial<PlayableAdProfile> {id: string;/** Shown in the platform list (the project names its own platforms). */label: string;+ kind?: ProjectPlatformKind;blurb?: string;defaultOut?: string;/** Engine runtime dir for this platform, relative to the project root.@@ -179,7 +193,8 @@ export interface ProjectPlatformModule extends Partial<MiniGameExportProfile> {* half. Naming it here is what joins them.*/runtimeProfile?: string;- emitConfigFiles(ctx: MiniGameConfigContext): Array<{ file: string; content: string }>;+ /** Mini-game kind only — a playable network has no vendor config files. */+ emitConfigFiles?(ctx: MiniGameConfigContext): Array<{ file: string; content: string }>;}/** A loaded project platform: the export profile plus where its runtime lives. */@@ -248,6 +263,40 @@ export default {`;}+/**+ * A playable ad network. One file: the pipeline and the host are unchanged (a+ * playable always runs in a browser), so all a network can differ in is the size+ * it accepts, what it wants in `<head>`, and the API its click-through calls.+ */+function playableTemplate(id: string, label: string): string {+ return `// Ad-network profile for "${label}" — how Estella packages a playable for it.+//+// Selected in Project Settings → Packaging → Playable. The editor's own networks+// are written against this same contract, so anything they can do, this can.+export default {+ id: '${id}',+ kind: 'playable',+ label: '${label}',++ // The size this network accepts for the delivered index.html, and where that+ // number comes from — the export quotes the note in its size warning, so keep it+ // pointing at the network's docs rather than at a guess.+ maxBytes: 5 * 1024 * 1024,+ limitNote: 'TODO: cite this network\\'s published limit',++ // Optional. Markup for <head> — an orientation meta tag, this network's SDK+ // script. Note that some networks forbid ANY external request in a playable.+ // emitHead: (ctx) => \`<meta name="ad.orientation" content="\${ctx.orientation}">\`,++ // Optional. Installs the bridge the SDK's playableCta() dispatches through, so+ // game code never names this network. Runs before the game bundle.+ emitBridge: () => \`window.__ESTELLA_PLAYABLE__={cta:function(){+ // TODO: call this network's click-through API.+ }};\`,+};+`;+}+/** The runtime half — the host global, plus anything this vendor replaces. */function runtimeTemplate(id: string, label: string): string {return `// Runtime profile for "${label}" — what the host is, at run time.@@ -315,11 +364,26 @@ export async function createProjectPlatform(id: string,label: string,scriptsDir: string,+ kind: ProjectPlatformKind = 'minigame',): Promise<CreatePlatformResult> {- const bad = idProblem(id);+ const bad = kind === 'playable' ? playableIdProblem(id) : idProblem(id);if (bad) return { ok: false, error: bad };if (!label.trim()) return { ok: false, error: 'platform needs a label' };+ // A playable network has no runtime half: the host is the browser, unchanged.+ if (kind === 'playable') {+ const rel = path.join(PROJECT_PLATFORM_DIR, `${id}.mjs`);+ const abs = path.join(root, rel);+ if (existsSync(abs)) return { ok: false, error: `${rel} already exists` };+ try {+ await mkdir(path.dirname(abs), { recursive: true });+ await writeFile(abs, playableTemplate(id, label), 'utf8');+ return { ok: true, packagingFile: posix(rel) };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+ }+const packagingRel = path.join(PROJECT_PLATFORM_DIR, `${id}.mjs`);const runtimeRel = runtimeHalfPath(scriptsDir, id);const packagingAbs = path.join(root, packagingRel);@@ -347,6 +411,15 @@ function idProblem(id: unknown): string | null {return null;}+/** A playable network's id: same spelling rules, but it competes with the networks+ * the editor ships rather than with the platform list. */+function playableIdProblem(id: unknown): string | null {+ if (typeof id !== 'string' || id.length === 0) return 'profile has no string `id`';+ if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) return `id "${id}" must be lowercase letters, digits and dashes`;+ if (builtinPlayableProfile(id)) return `id "${id}" is a built-in ad network`;+ return null;+}+/*** Import one project platform module. Returns its raw export, or an error string* — never throws: a project that ships a broken profile must still be able to@@ -361,9 +434,20 @@ async function importPlatformModule(file: string): Promise<{ mod?: ProjectPlatfoconst mod = ns.default;if (!mod || typeof mod !== 'object') return { error: 'module has no default export object' };const candidate = mod as ProjectPlatformModule;- const bad = idProblem(candidate.id);+ // A playable network shares the `playable` target's id space (it is a variant of+ // it, not a rival platform), so only a mini-game platform must avoid built-in ids.+ const bad = candidate.kind === 'playable' ? playableIdProblem(candidate.id) : idProblem(candidate.id);if (bad) return { error: bad };if (typeof candidate.label !== 'string' || !candidate.label) return { error: 'profile has no `label`' };+ if (candidate.kind === 'playable') {+ if (typeof candidate.maxBytes !== 'number' || !(candidate.maxBytes > 0)) {+ return { error: 'playable profile needs a positive `maxBytes` (the size this network accepts)' };+ }+ if (typeof candidate.limitNote !== 'string' || !candidate.limitNote) {+ return { error: 'playable profile needs a `limitNote` saying where `maxBytes` comes from' };+ }+ return { mod: candidate };+ }if (typeof candidate.emitConfigFiles !== 'function') return { error: 'profile has no `emitConfigFiles(ctx)`' };return { mod: candidate };} catch (err) {@@ -390,7 +474,7 @@ async function projectPlatformFiles(root: string): Promise<string[]> {export async function loadProjectPlatform(root: string, id: string, dirs: PlatformRuntimeDirs): Promise<ProjectPlatform | null> {for (const file of await projectPlatformFiles(root)) {const { mod } = await importPlatformModule(file);- if (!mod || mod.id !== id) continue;+ if (!mod || mod.id !== id || mod.kind === 'playable') continue;// The runtime half is resolved to an absolute path here: the generated entry// is bundled with `resolveDir` at the project root, but an absolute specifier// is unambiguous whatever the profile wrote.@@ -406,6 +490,70 @@ export async function loadProjectPlatform(root: string, id: string, dirs: Platforeturn null;}+// =============================================================================+// Playable ad networks+// =============================================================================++/** One row of the network picker. Serializable by construction (it crosses IPC). */+export interface PlayableNetworkOption {+ id: string;+ label: string;+ source: 'builtin' | 'project';+ /** Present when a project profile failed to load, and why — the row still appears. */+ error?: string;+}++/**+ * Every ad network this project can package a playable for: the ones the editor+ * ships, then the project's own. One list, one contract — a network the editor+ * never heard of appears here on equal terms, which is the whole point of the+ * `kind: 'playable'` profile.+ */+export async function listPlayableNetworks(root: string | null): Promise<PlayableNetworkOption[]> {+ const out: PlayableNetworkOption[] = BUILTIN_PLAYABLE_PROFILES+ .map((p) => ({ id: p.id, label: p.label, source: 'builtin' as const }));+ if (!root) return out;+ for (const file of await projectPlatformFiles(root)) {+ const { mod, error } = await importPlatformModule(file);+ // A broken profile is NAMED rather than dropped — a project that wrote a file+ // and sees nothing cannot tell the difference between "not loaded" and "typo".+ if (error) {+ const id = path.basename(file, '.mjs');+ if (!out.some((p) => p.id === id)) out.push({ id, label: path.basename(file), source: 'project', error });+ continue;+ }+ if (!mod || mod.kind !== 'playable') continue;+ out.push({ id: mod.id, label: mod.label, source: 'project' });+ }+ return out;+}++/**+ * Resolve a network id to the profile the playable export runs with. Built-ins+ * first, then the project's; an id that resolves to nothing falls back to generic+ * rather than failing the export — a package that ships without a click-through is+ * still a package, and the missing network is reported as a warning by the caller.+ */+export async function loadPlayableProfile(root: string | null, id: string | undefined): Promise<PlayableAdProfile | null> {+ if (!id) return genericPlayableProfile;+ const builtin = builtinPlayableProfile(id);+ if (builtin) return builtin;+ if (!root) return null;+ for (const file of await projectPlatformFiles(root)) {+ const { mod } = await importPlatformModule(file);+ if (!mod || mod.kind !== 'playable' || mod.id !== id) continue;+ return {+ id: mod.id,+ label: mod.label,+ maxBytes: mod.maxBytes as number,+ limitNote: mod.limitNote as string,+ emitHead: mod.emitHead,+ emitBridge: mod.emitBridge,+ };+ }+ return null;+}+// =============================================================================// The catalog// =============================================================================@@ -435,6 +583,9 @@ export async function listPlatforms(root: string | null, dirs: PlatformRuntimeDi});continue;}+ // A playable network is not a platform row — it is chosen inside the built-in+ // `playable` target (Project Settings → Packaging → Playable).+ if (mod.kind === 'playable') continue;const wasmDir = mod.wasmDir? (path.isAbsolute(mod.wasmDir) ? mod.wasmDir : path.join(root, mod.wasmDir)): dirs.web;diff --git a/desktop/electron/playableAdProfile.ts b/desktop/electron/playableAdProfile.tsnew file mode 100644index 000000000..d3500a527--- /dev/null+++ b/desktop/electron/playableAdProfile.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Per-network playable-ad profile.+ *+ * The export pipeline (exportPlayable.ts) is shared by every ad network: cook →+ * inline assets/scenes/engine → bundle the host → one self-contained index.html.+ * What differs per network is small and it is all DATA plus two emit hooks: the+ * size the network accepts, what goes in `<head>`, and which API the player's+ * click-through calls.+ *+ * Adding a network = one profile, not a branch in the pipeline. The built-ins+ * below are written against the same contract a project's own profile uses+ * (`.esengine/platforms/<id>.mjs` with `kind: 'playable'`), so "the editor+ * supports this network" is never a privileged path.+ */+import type { ScreenOrientation } from './orientationHtml';++/** Neutral facts the pipeline computed, handed to a profile's emitters. */+export interface PlayableAdContext {+ title: string;+ orientation: ScreenOrientation;+}++export interface PlayableAdProfile {+ /** Network identity — persisted in `packaging.platforms.playable.network`. */+ readonly id: string;+ /** Shown wherever the network is chosen. */+ readonly label: string;+ /**+ * Bytes the network accepts for the delivered file. Playables are size-capped+ * and every network caps differently, so the export's size warning reads this+ * rather than a constant.+ */+ readonly maxBytes: number;+ /** Where {@link maxBytes} comes from, quoted in the warning so a developer can+ * check it against the network's current docs rather than trusting us. */+ readonly limitNote: string;+ /** Markup for `<head>`: an orientation meta tag, the network's own SDK script. */+ emitHead?(ctx: PlayableAdContext): string;+ /**+ * An inline script installing `globalThis.__ESTELLA_PLAYABLE__`, whose `cta()`+ * calls this network's click-through API. The game side of that seam is the+ * SDK's `playableCta()`, which every network shares.+ */+ emitBridge?(ctx: PlayableAdContext): string;+}++/**+ * No network named. The page stays exactly what a plain single-file HTML5 build+ * is — no injected markup, no bridge (so `playableCta()` is a no-op) — and the+ * size warning uses the strictest cap we know of, because an unnamed target could+ * be any of them.+ */+export const genericPlayableProfile: PlayableAdProfile = {+ id: 'generic',+ label: 'Generic (single-file HTML5)',+ maxBytes: 2 * 1024 * 1024,+ limitNote: "no network selected — using Meta's 2MB index.html cap, the strictest we know of",+};++/**+ * Meta (Facebook / Instagram) playable ads, single-file format. Meta caps the+ * index.html itself at 2MB (its 5MB figure is the total for a ZIP bundle, which a+ * single-file playable has no way to spend), forbids any HTTP request — hence+ * nothing in `<head>` — and requires the click-through to call its own function.+ * @see https://www.facebook.com/business/help/412951382532338+ */+export const metaPlayableProfile: PlayableAdProfile = {+ id: 'meta',+ label: 'Meta (Facebook / Instagram)',+ maxBytes: 2 * 1024 * 1024,+ limitNote: "Meta caps a playable's index.html at 2MB",+ emitBridge: () => 'window.__ESTELLA_PLAYABLE__={cta:function(){'+ + 'if(typeof FbPlayableAd!=="undefined"&&FbPlayableAd.onCTAClick)FbPlayableAd.onCTAClick();'+ + '}};',+};++/** The networks the editor ships, by id. */+export const BUILTIN_PLAYABLE_PROFILES: readonly PlayableAdProfile[] = [+ genericPlayableProfile,+ metaPlayableProfile,+];++export function builtinPlayableProfile(id: string | undefined): PlayableAdProfile | null {+ return BUILTIN_PLAYABLE_PROFILES.find((p) => p.id === id) ?? null;+}++/** What a profile contributes to the page, resolved once so the assembler stays flat. */+export function playableAdInjection(+ profile: PlayableAdProfile,+ ctx: PlayableAdContext,+): { head: string; bridge: string } {+ return {+ head: profile.emitHead?.(ctx) ?? '',+ bridge: profile.emitBridge?.(ctx) ?? '',+ };+}diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 26d746946..6e2d49c8e 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -7,7 +7,9 @@ import type { ExtractSchemasResult } from './extractSchemas';import type { ScanAssetsResult, AssetIndex, IncrementalScanResult } from './assetDb';import type { CookResult } from './cookAssets';import type { ExportGameResult } from './exportGame';-import type { PlatformStatus, CreatePlatformResult } from './platformCatalog';+import type {+ PlatformStatus, CreatePlatformResult, PlayableNetworkOption, ProjectPlatformKind,+} from './platformCatalog';import type { PlayRealmResult } from './buildPlayRealm';import type { LatestRelease } from './updateCheck';@@ -97,10 +99,15 @@ const api = {/** The platforms this project can package for — built-ins plus any the project* defines in `.esengine/platforms/` — each with its engine runtime probed. */listPlatforms: (): Promise<PlatformStatus[]> => ipcRenderer.invoke('project:listPlatforms'),+ /** The ad networks a playable can target — the editor's plus any the project+ * defines with `kind: 'playable'`. A profile that failed to load is listed with+ * its `error` rather than dropped. */+ listPlayableNetworks: (): Promise<PlayableNetworkOption[]> =>+ ipcRenderer.invoke('project:listPlayableNetworks'),/** Scaffold a project platform: the packaging profile + the runtime profile it* points at, both written and already joined. */- createPlatform: (id: string, label: string): Promise<CreatePlatformResult> =>- ipcRenderer.invoke('project:createPlatform', id, label),+ createPlatform: (id: string, label: string, kind?: ProjectPlatformKind): Promise<CreatePlatformResult> =>+ ipcRenderer.invoke('project:createPlatform', id, label, kind),/** Export a runnable web build (play==ship) → self-contained `outDir` (default dist-game/). */exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: ExportPlatform; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }): Promise<ExportGameResult> =>ipcRenderer.invoke('project:exportGame', opts),diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex 6d53952fb..240956173 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -131,6 +131,13 @@ export interface AndroidPackaging { appId?: string; versionCode?: number; }/** iOS's slice: the bundle identifier Xcode signs against. */export interface IosPackaging { appId?: string; }+/** Playable's slice: which ad network the single-file package targets. The id names+ * a profile — one the editor ships, or one the project defines in+ * `.esengine/platforms/<id>.mjs` with `kind: 'playable'` — which decides the size+ * cap, the `<head>` markup, and the API `playableCta()` calls. Absent ⇒ generic+ * (no network API, strictest cap). */+export interface PlayablePackaging { network?: string; }+/** A packaging target — defined in `./platforms`, where the built-in vocabulary* lives, and re-exported here because the manifest is what persists it. */export type { ExportPlatform } from './platforms';@@ -188,6 +195,7 @@ export interface ProjectPackaging {desktop?: DesktopPackaging;android?: AndroidPackaging;ios?: IosPackaging;+ playable?: PlayablePackaging;};}@@ -452,11 +460,16 @@ export function parseManifest(raw: unknown): ProjectManifest {if (typeof io.appId === 'string') i.appId = io.appId;if (Object.keys(i).length > 0) platforms.ios = i;}- // Legacy playable.orientation (its only field) also migrates; the platform- // block itself is gone (playable has no per-platform config anymore).const pa = pl.playable as Record<string, unknown> | undefined;- if (!orientation && pa && typeof pa === 'object' && (pa.orientation === 'portrait' || pa.orientation === 'landscape')) {- orientation = pa.orientation;+ if (pa && typeof pa === 'object') {+ // A legacy playable.orientation migrates to the project-wide field; `network`+ // is what the block carries today.+ if (!orientation && (pa.orientation === 'portrait' || pa.orientation === 'landscape')) {+ orientation = pa.orientation;+ }+ const p: PlayablePackaging = {};+ if (typeof pa.network === 'string' && pa.network !== '') p.network = pa.network;+ if (Object.keys(p).length > 0) platforms.playable = p;}if (Object.keys(platforms).length > 0) pkg.platforms = platforms;}diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.tsindex 65c29e02a..0f3318270 100644--- a/desktop/tests/export-playable.test.ts+++ b/desktop/tests/export-playable.test.ts@@ -99,6 +99,50 @@ describe('exportGame (playable)', () => {expect(html).toMatch(/screen\.orientation[\s\S]*lock\("landscape"\)/);}, 60_000);+ // The ad network is a PROFILE, not a branch: what it contributes is head markup, a+ // CTA bridge, and the size it accepts. A project profile and a built-in one reach+ // the pipeline the same way, so this exercises the contract with a bespoke one.+ it('injects the ad network profile head + CTA bridge, and warns against ITS limit', async () => {+ const o = path.join(root, 'dist-playable-network');+ const res = await exportGame({+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),+ outDir: o, platform: 'playable',+ playableAdProfile: {+ id: 'acme', label: 'Acme Ads',+ // Tiny cap so this fixture's few KB trip the warning.+ maxBytes: 16, limitNote: 'Acme caps playables at 16 bytes',+ emitHead: (ctx) => `<meta name="acme.orientation" content="${ctx.orientation}">`,+ emitBridge: () => 'window.__ESTELLA_PLAYABLE__={cta:function(){AcmeSDK.openStore();}};',+ },+ });+ expect(res.ok).toBe(true);++ const html = readFileSync(path.join(o, 'index.html'), 'utf8');+ expect(html).toContain('<meta name="acme.orientation" content="landscape">');+ expect(html).toContain('AcmeSDK.openStore()');+ // The bridge must precede the game bundle, or a CTA fired during boot finds nothing.+ expect(html.indexOf('__ESTELLA_PLAYABLE__')).toBeLessThan(html.indexOf('__ENGINE_GLUE__'));+ // The warning cites this network's cap and where it came from — not a constant.+ expect(res.warnings.join('\n')).toMatch(/over the 0\.0MB limit for Acme Ads \(Acme caps playables at 16 bytes\)/);+ }, 60_000);++ it('injects nothing and keeps the default cap with no network selected', async () => {+ const o = path.join(root, 'dist-playable-generic');+ const res = await exportGame({+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),+ outDir: o, platform: 'playable',+ });+ expect(res.ok).toBe(true);+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');+ expect(html).not.toContain('__ESTELLA_PLAYABLE__');+ // A fixture this small is under every cap, so nothing to report.+ expect(res.warnings).toEqual([]);+ }, 60_000);+it('inlines the project camera fit as __GAME_SCREENFIT__ (only when opted in)', async () => {const o = path.join(root, 'dist-playable-fit');const res = await exportGame({diff --git a/desktop/tests/platform-catalog.test.ts b/desktop/tests/platform-catalog.test.tsindex 721f03ba0..9720a6d07 100644--- a/desktop/tests/platform-catalog.test.ts+++ b/desktop/tests/platform-catalog.test.ts@@ -13,7 +13,10 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';-import { listPlatforms, loadProjectPlatform, createProjectPlatform, PROJECT_PLATFORM_DIR } from '../electron/platformCatalog';+import {+ listPlatforms, loadProjectPlatform, createProjectPlatform, PROJECT_PLATFORM_DIR,+ listPlayableNetworks, loadPlayableProfile,+} from '../electron/platformCatalog';import { BUILTIN_PLATFORMS } from '../src/project/platforms';let root: string;@@ -290,3 +293,73 @@ describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {expect(await loadProjectPlatform(root, 'nope', dirs())).toBeNull();});});++// A playable ad network is a variant of the built-in `playable` target, not a rival+// platform: it is chosen inside that target, and a project-defined one must reach the+// export through exactly the path a built-in does.+describe('playable ad networks', () => {+ it('lists the built-ins, then the project\'s own', async () => {+ writePlatform('acme-ads.mjs', `export default {+ id: 'acme-ads', kind: 'playable', label: 'Acme Ads',+ maxBytes: 3145728, limitNote: 'Acme docs say 3MB',+ };`);+ const rows = await listPlayableNetworks(root);+ expect(rows.filter((r) => r.source === 'builtin').map((r) => r.id)).toEqual(['generic', 'meta']);+ expect(rows.find((r) => r.id === 'acme-ads')).toMatchObject({ label: 'Acme Ads', source: 'project' });+ });++ it('resolves a project network to a profile the export can run with', async () => {+ writePlatform('acme-ads.mjs', `export default {+ id: 'acme-ads', kind: 'playable', label: 'Acme Ads',+ maxBytes: 3145728, limitNote: 'Acme docs say 3MB',+ emitHead: (ctx) => '<meta name="acme" content="' + ctx.orientation + '">',+ emitBridge: () => 'window.__ESTELLA_PLAYABLE__={cta:function(){}};',+ };`);+ const profile = await loadPlayableProfile(root, 'acme-ads');+ expect(profile).toMatchObject({ id: 'acme-ads', maxBytes: 3145728 });+ expect(profile!.emitHead!({ title: 'T', orientation: 'portrait' })).toBe('<meta name="acme" content="portrait">');+ expect(profile!.emitBridge!({ title: 'T', orientation: 'portrait' })).toContain('__ESTELLA_PLAYABLE__');+ });++ it('resolves the built-ins, and nothing for an unknown id', async () => {+ expect((await loadPlayableProfile(root, 'meta'))!.emitBridge!({ title: 'T', orientation: 'landscape' }))+ .toContain('FbPlayableAd.onCTAClick');+ // No selection ⇒ generic, so a project that never chose still exports.+ expect((await loadPlayableProfile(root, undefined))!.id).toBe('generic');+ // An id naming nothing is NOT silently generic — the caller reports it.+ expect(await loadPlayableProfile(root, 'nope')).toBeNull();+ });++ it('rejects a playable profile missing the facts the warning needs', async () => {+ writePlatform('bad.mjs', "export default { id: 'bad', kind: 'playable', label: 'Bad' };");+ const row = (await listPlayableNetworks(root)).find((r) => r.id === 'bad');+ expect(row!.error).toMatch(/maxBytes/);+ });++ it('keeps networks out of the platform list, and platforms out of the network list', async () => {+ writePlatform('acme-ads.mjs', `export default {+ id: 'acme-ads', kind: 'playable', label: 'Acme Ads', maxBytes: 100, limitNote: 'x',+ };`);+ writePlatform('acme-mini.mjs', `export default {+ id: 'acme-mini', label: 'Acme MiniGame', emitConfigFiles: () => [],+ };`);+ expect((await listPlatforms(root, dirs())).map((r) => r.id)).not.toContain('acme-ads');+ expect((await listPlayableNetworks(root)).map((r) => r.id)).not.toContain('acme-mini');+ // And a network id must not shadow a network the editor ships.+ writePlatform('meta.mjs', "export default { id: 'meta', kind: 'playable', label: 'Mine', maxBytes: 1, limitNote: 'x' };");+ expect((await listPlayableNetworks(root)).find((r) => r.label === 'Mine')).toBeUndefined();+ });++ it('scaffolds a playable network as one file (the host is still the browser)', async () => {+ const res = await createProjectPlatform(root, 'acme-ads', 'Acme Ads', 'src', 'playable');+ expect(res.ok).toBe(true);+ expect(res.runtimeFile).toBeUndefined();+ const written = readFileSync(path.join(root, res.packagingFile!), 'utf8');+ expect(written).toContain("kind: 'playable'");+ expect(written).toContain('__ESTELLA_PLAYABLE__');+ // The scaffold must satisfy its own contract, or the first export after+ // scaffolding reports an error the developer did not write.+ const row = (await listPlayableNetworks(root)).find((r) => r.id === 'acme-ads');+ expect(row?.error).toBeUndefined();+ });+});diff --git a/desktop/tests/project-packaging.test.ts b/desktop/tests/project-packaging.test.tsindex 82d9f713e..df699ed2c 100644--- a/desktop/tests/project-packaging.test.ts+++ b/desktop/tests/project-packaging.test.ts@@ -80,6 +80,14 @@ describe('parseManifest — orientation (unified, project-wide)', () => {expect(parseManifest({ name: 'X', packaging: { orientation: 'portrait' } }).packaging?.orientation).toBe('portrait');});+ it('parses the playable ad network, and drops an empty one', () => {+ expect(parseManifest({ name: 'X', packaging: { platforms: { playable: { network: 'meta' } } } })+ .packaging?.platforms?.playable?.network).toBe('meta');+ // An empty string is not a selection — it must fall through to generic.+ expect(parseManifest({ name: 'X', packaging: { platforms: { playable: { network: '' } } } })+ .packaging?.platforms).toBeUndefined();+ });+it('drops an invalid top-level orientation', () => {expect(parseManifest({ name: 'X', packaging: { orientation: 'diagonal' } }).packaging).toBeUndefined();});