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(export): a project can be packaged as a quick game
esengine28ce9baca64b
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 2072e949a..a2db4c563 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -115,6 +115,7 @@ jobs:path: |desktop/public/wasmdesktop/public/wasm-wechat+ desktop/public/wasm-quickgameretention-days: 3# The native app's compiled half — the engine, Dawn, QuickJS, the linked-indiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8d2f3e822..e3760117f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A project can be packaged as a quick game — one signed `.rpk` for vivo, OPPO, Xiaomi and Honor (快游戏联盟).** Set the package name (it must end in `.minigame`) in Project Settings → Packaging → Quick game, and the export writes `manifest.json` (allianceVersion 1300), the project's icon (or Estella's mark), and `<package>.rpk` signed with your release key — or with Estella's public debug key, which a device debugger installs and a store refuses. It needs no vendor tool: the signing block is written here and matches the vendor CLI's byte for byte. The package runs on its own engine build (`build -t quickgame`) without wasm SIMD and BigInt i64, which the hosts' V8 8.3 refuses, and the runtime reads the hosts' window in physical pixels and turns WebAssembly on first. Verified end to end on vivo's engine in an Android emulator; OPPO grants WebGL2 only to a game that applied for it, and no device has run it yet.- **A project can be packaged for Bilibili (B 站).** `game.json` carries the appid (Project Settings → Packaging → Bilibili) and the project's version, and turns on all four high-performance switches — Bilibili runs WebGL2 nowhere else, and the engine renders on nothing less. Scripts are lowered below async/await, which Bilibili asks a game to polyfill, and files are staged against Bilibili's own upload whitelist. The build is judged against 4 MB for the main package, 4 MB for each subpackage and 30 MB in all; a per-subpackage limit is new, and the size panel names the heaviest subpackage's files when it is over. Ads (rewarded only), share and sign-in are forwarded to `bl` and marked unverified; purchase is not offered. wasm on iOS is contradicted in Bilibili's own docs and needs a device.- A mini-game host that asks to hear when the first screen has rendered is told, once, at the end of the first frame — Bilibili reviews a game by `bl.launchSuccess`.- **A project can be packaged for Kuaishou (快手).** The third mini-game vendor rides the same pipeline and runtime as WeChat and Douyin: a package of `game.js` + `game.json` (the appid is entered in Kuaishou's developer tool, not written into the package), judged against Kuaishou's 6 MB main package and 30 MB total. The recorder shares through Kuaishou's own `publishVideo`, whole — the host takes no ranges. Ads, share and sign-in are forwarded to `ks` and marked unverified; purchase is not offered, since `ks.requestGamePayment` needs an order signed by your server. It renders only where the host offers WebGL2, which Kuaishou still calls beta.@@ -25,6 +26,8 @@ published separately; it ships inside the editor.### Fixed+- A mini-game whose host's WebGL2 context also offers `OES_vertex_array_object` renders instead of hanging: the WebGL1 extensions WebGL2 made core are withheld from a WebGL2 context, as the spec says, so Emscripten no longer swaps in the host's broken extension path (vivo's).+- `estella export` writes a mini-game's appid and project version as the build dialog does — a headless Bilibili package came out with an empty `appId`.- A mini-game on any host but WeChat no longer throws at boot. The lifecycle plugin knew one vendor by name and sent every other one down the web path, where the `document` stub every mini-game carries has no `addEventListener`; foreground/background now come from the host's own `onShow`/`onHide` for the whole family, as they already did for the native shell.- A mini-game that fails to start says why. The generated entry now catches a boot that rejects — a host without `onUnhandledRejection` dropped it silently, leaving the loading screen up and nothing in the log — and a failed engine instantiation names the error instead of printing `[object Object]`.- `estella export --platform <id>` packages a platform the project defines in `.esengine/platforms/`, as the build dialog does, and an id that is neither built in nor defined is refused instead of silently packaged as a web game.diff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex d2e9f883d..e2c9dc760 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -17,6 +17,7 @@ export default {optimization: {web: { cmakeOpt: '-O2', wasmOpt: '-O2' },wechat: { cmakeOpt: '-O2', wasmOpt: '-O2' },+ quickgame: { cmakeOpt: '-O2', wasmOpt: '-O2' },},wasm: {@@ -41,6 +42,18 @@ export default {'sdk/esengine.wxgame.wasm': 'wasm/wechat/esengine.wxgame.wasm',},},+ // The mini-game engine for vivo's quick-game V8 (8.3), which refuses both a+ // SIMD opcode ("Invalid opcode (enable with --experimental-wasm-simd)") and+ // an i64 in a wasm↔JS signature ("wasm function signature contains illegal type").+ quickgame: {+ buildDir: 'build/cmake/qgame',+ cmakeFlags: ['-DES_BUILD_WXGAME=ON', '-DES_BUILD_TESTS=OFF', '-DES_MAIN_DISABLE_SIMD=ON', '-DES_WASM_BIGINT=OFF'],+ targets: ['esengine_wxgame'],+ outputs: {+ 'sdk/esengine.wxgame.js': 'wasm/quickgame/esengine.wxgame.js',+ 'sdk/esengine.wxgame.wasm': 'wasm/quickgame/esengine.wxgame.wasm',+ },+ },physics: {buildDir: 'build/cmake/physics',cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_BOX2D=ON', '-DES_PHYSICS_ESM=ON'],@@ -233,6 +246,7 @@ export default {// wasm-wechat first) — web-aligned filenames (physics.js, spine42.js, …)// would otherwise overwrite the web modules in desktop/public/wasm.'build/wasm/wechat': 'desktop/public/wasm-wechat',+ 'build/wasm/quickgame': 'desktop/public/wasm-quickgame',},sdk: {'build/sdk/esm': 'desktop/public/sdk/esm',diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmakeindex 80116f39a..96ca357c9 100644--- a/cmake/Emscripten.cmake+++ b/cmake/Emscripten.cmake@@ -26,6 +26,9 @@ set(ES_EMSCRIPTEN_COMPILE_FLAGS# already ships SIMD to web AND wechat, so this is on by default with a compat# fallback (`-DES_MAIN_DISABLE_SIMD=ON`) mirroring BOX2D_DISABLE_SIMD.option(ES_MAIN_DISABLE_SIMD "Disable wasm SIMD for the main module (compat fallback)" OFF)+# Hosts on V8 older than 8.5 reject an i64 in a wasm↔JS signature ("wasm function+# signature contains illegal type"); OFF legalizes i64 into i32 pairs instead.+option(ES_WASM_BIGINT "Pass i64 across the wasm↔JS boundary as BigInt" ON)if(NOT ES_MAIN_DISABLE_SIMD)list(APPEND ES_EMSCRIPTEN_COMPILE_FLAGS -msimd128 -msse2)endif()@@ -266,7 +269,11 @@ function(es_apply_wxgame_sdk_settings TARGET_NAME)if(ES_BUILD_WXGAME)target_compile_options(${TARGET_NAME} PRIVATE ${ES_EMSCRIPTEN_COMPILE_FLAGS} -flto -fno-exceptions)- string(REPLACE ";" " " LINK_FLAGS_STR "${ES_EMSCRIPTEN_WXGAME_SDK_FLAGS}")+ set(_WXGAME_LINK ${ES_EMSCRIPTEN_WXGAME_SDK_FLAGS})+ if(NOT ES_WASM_BIGINT)+ list(APPEND _WXGAME_LINK -sWASM_BIGINT=0)+ endif()+ string(REPLACE ";" " " LINK_FLAGS_STR "${_WXGAME_LINK}")set_target_properties(${TARGET_NAME} PROPERTIESSUFFIX ".js"LINK_FLAGS "${LINK_FLAGS_STR}"diff --git a/desktop b/desktopindex 957236f2b..670b2b0c2 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 957236f2b810e420372afe4d89894a68e88458f1+Subproject commit 670b2b0c2e85413fd75e0310340aaf2821433210diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex 0338f6e0e..fc52d067f 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -570,9 +570,12 @@ function projectSettings(projectDir) {* same engine — handing it the web one is a syntax error at the first `require`.*/function engineRuntimeDir(platform) {- const dirs = fmt.isMiniGamePlatform(platform)- ? [path.join(REPO, 'build', 'wasm', 'wechat'), path.join(REPO, 'desktop', 'public', 'wasm-wechat')]- : [path.join(REPO, 'build', 'wasm', 'web'), path.join(REPO, 'desktop', 'public', 'wasm')];+ const build = fmt.engineBuildFor(platform);+ const dirs = build === 'quickgame'+ ? [path.join(REPO, 'build', 'wasm', 'quickgame'), path.join(REPO, 'desktop', 'public', 'wasm-quickgame')]+ : build === 'minigame'+ ? [path.join(REPO, 'build', 'wasm', 'wechat'), path.join(REPO, 'desktop', 'public', 'wasm-wechat')]+ : [path.join(REPO, 'build', 'wasm', 'web'), path.join(REPO, 'desktop', 'public', 'wasm')];return firstExisting(dirs) ?? dirs[dirs.length - 1];}@@ -780,6 +783,8 @@ const sizeBudgetBytes = manifest.packaging?.sizeBudget?.[platform];const { mod: exporter, cleanup: cleanupExport } = await loadPipeline(path.join(PIPELINE, 'src', 'export', 'exportGame.ts'), 'exportGame.mjs');+const { mod: rpkMod, cleanup: cleanupRpk } = await loadPipeline(+ path.join(PIPELINE, 'src', 'export', 'rpk.ts'), 'rpk.mjs');// A platform the project defines in .esengine/platforms/, loaded the way the// build dialog loads it, so a headless package is the one the dialog makes.@@ -789,7 +794,7 @@ if (!fmt.BUILTIN_PLATFORMS.includes(platform)) {path.join(PIPELINE, 'src', 'export', 'platformCatalog.ts'), 'platformCatalog.mjs');try {projectPlatform = await catalog.loadProjectPlatform(opts.projectDir, platform,- { web: engineRuntimeDir('web'), minigame: engineRuntimeDir('wechat') });+ { web: engineRuntimeDir('web'), minigame: engineRuntimeDir('wechat'), quickgame: engineRuntimeDir('quickgame') });} finally {cleanupCatalog();}@@ -821,6 +826,14 @@ try {runtime: runtimeConfigOf(manifest),...cookOptionsOf(manifest),...packagingOptionsOf(manifest),+ // What the dialog passes from the same settings: the vendor's id for the game,+ // the version a host config states, and a quick game's ordinal and key.+ miniGameAppid: manifest.packaging?.platforms?.[platform]?.appid,+ appVersion: manifest.version,+ miniGameVersionCode: manifest.packaging?.platforms?.quickgame?.versionCode,+ miniGameReleaseKey: platform === 'quickgame'+ ? (await rpkMod.readReleaseKey(opts.projectDir, manifest.packaging?.platforms?.quickgame?.releaseKey)) ?? undefined+ : undefined,androidTemplate: platform === 'android' ? templateDir : null,desktopTemplates,desktopChannel: opts['steam-appid'] ? 'steam' : undefined,@@ -867,6 +880,7 @@ try {// Before the exit, not after: process.exit() in the try block would skip this// and leave the bundle dirs behind.cleanupExport();+ cleanupRpk();cleanupFmt();}process.exit(code);diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.tsindex 644c7ca14..b87cc04c4 100644--- a/pipeline/src/bundle/engineSubpaths.ts+++ b/pipeline/src/bundle/engineSubpaths.ts@@ -22,6 +22,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {'esengine/douyin': 'douyin/index.js','esengine/kuaishou': 'kuaishou/index.js','esengine/bilibili': 'bilibili/index.js',+ 'esengine/quickgame': 'quickgame/index.js','esengine/wasm': 'wasm.js',};@@ -30,7 +31,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {* loads, and a platform adapter an entry chooses rather than content asking for* it. Named here so the pickable set is derived rather than written twice.*/-export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili']);+export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili', 'esengine/quickgame']);/** The modules a project can force in or refuse, as `features.modules` keys it. */export const ENGINE_MODULES: readonly string[] =diff --git a/pipeline/src/bundle/runtimeHosts.ts b/pipeline/src/bundle/runtimeHosts.tsindex abfe0739a..efbfa3d12 100644--- a/pipeline/src/bundle/runtimeHosts.ts+++ b/pipeline/src/bundle/runtimeHosts.ts@@ -17,7 +17,7 @@ import { ESENGINE_EXTERNAL } from './esengineResolve';// editor has to ship it for the same reason it ships the hosts.export const RUNTIME_HOSTS = ['gameHost', 'playableHost', 'playableLoader', 'douyinPlatformProfile', 'kuaishouPlatformProfile',- 'bilibiliPlatformProfile',+ 'bilibiliPlatformProfile', 'quickgamePlatformProfile',] as const;export type RuntimeHost = (typeof RUNTIME_HOSTS)[number];diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 8ef9cd01a..b4b16cafd 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -36,7 +36,7 @@ import {import { engineImportMap, FULL_IMPORT_MAP, LEAN_ENTRY_FILE, FULL_ENTRY_FILE, type EngineImportMap } from '../bundle/importMap';import { engineInstalls, forcedSideModules, moduleChoices, type EngineInstallPlan } from '../bundle/engineInstalls';import { exportMiniGame } from './exportMiniGame';-import { wechatExportProfile, douyinExportProfile, kuaishouExportProfile, bilibiliExportProfile } from './miniGameExportProfile';+import { wechatExportProfile, douyinExportProfile, kuaishouExportProfile, bilibiliExportProfile, quickgameExportProfile } from './miniGameExportProfile';import type { MiniGameExportProfile } from './miniGameExportProfile';/** The mini-game vendors the editor ships, by platform id. */@@ -45,12 +45,14 @@ const BUILTIN_MINIGAME_PROFILES: Readonly<Record<string, MiniGameExportProfile>>douyin: douyinExportProfile,kuaishou: kuaishouExportProfile,bilibili: bilibiliExportProfile,+ quickgame: quickgameExportProfile,};import { exportPlayable } from './exportPlayable';import { genericPlayableProfile, type PlayableAdProfile } from './playableAdProfile';import type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL, ESENGINE_SUBPATHS } from '../bundle/esengineResolve';import { officialPackagesPlugin } from '../bundle/officialPackages';+import type { RpkSigningKey } from './rpk';import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSystems';import { resolveEmcc, runEmcc } from '../bundle/emccPath';import { findHostCC } from '../../../compiler/src/hostCC';@@ -270,6 +272,8 @@ export interface ExportGameResult {/** Playable, zip-delivery networks: the archive written beside the HTML — the file* the network takes an upload of. */zipFile?: string;+ /** A mini-game vendor's single-file package (a quick game's signed `.rpk`). */+ packageFile?: string;/** Playable: what the single file is made of. See ExportPlayableResult. */inlineParts?: { path: string; bytes: number }[];/** What the package weighs, and how it fared against the limits in force.@@ -469,6 +473,11 @@ export interface ExportGameOptions {* `wechatAppid` is how the Douyin export came to send one.*/miniGameAppid?: string;+ /** The build ordinal a mini-game host compares packages by. Absent ⇒ 1. */+ miniGameVersionCode?: number;+ /** The project's key for a mini-game vendor that takes a signed file (a quick+ * game's `.rpk`). Absent ⇒ signed with the public debug key. */+ miniGameReleaseKey?: RpkSigningKey;/** Reverse-DNS application id for a native target (format.ts resolveAppId).* Written into app.config.json, where the packagers read it. */appId?: string;@@ -596,7 +605,7 @@ async function attachSizeReport(result: ExportGameResult, opts: ExportGameOption// applies to. The playable ships its single file as index.html unless a zip// was written for a zip-delivery network.const desktopApps = result.appBundles ?? [];- const packages = [result.apkFile, result.aabFile, result.zipFile, ...desktopApps.map((a) => a.dir)]+ const packages = [result.apkFile, result.aabFile, result.zipFile, result.packageFile, ...desktopApps.map((a) => a.dir)].filter((p): p is string => !!p);// Desktop makes one package per OS; the limit is judged on the one this machine// could run, falling back to the first, because a per-OS budget would be a@@ -605,7 +614,7 @@ async function attachSizeReport(result: ExportGameResult, opts: ExportGameOption?? desktopApps[0];const deliverable = result.platform === 'playable'? result.zipFile ?? path.join(result.outDir, 'index.html')- : result.apkFile ?? result.aabFile ?? desktopApp?.dir;+ : result.packageFile ?? result.apkFile ?? result.aabFile ?? desktopApp?.dir;try {const size = await measureBuild({root: result.outDir,@@ -680,6 +689,9 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>title,appid: opts.miniGameAppid,appVersion: opts.appVersion,+ versionCode: opts.miniGameVersionCode,+ appIcon: opts.appIcon,+ releaseKey: opts.miniGameReleaseKey,features: opts.features,modulesByPlatform: opts.modulesByPlatform,orientation,@@ -716,6 +728,9 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>title,appid: opts.miniGameAppid,appVersion: opts.appVersion,+ versionCode: opts.miniGameVersionCode,+ appIcon: opts.appIcon,+ releaseKey: opts.miniGameReleaseKey,features: opts.features,modulesByPlatform: opts.modulesByPlatform,orientation,diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex 0a7f17464..0a628f934 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -49,6 +49,7 @@ import { officialPackagesPlugin } from '../bundle/officialPackages';import { explainBundleErrors, type BundleMessage } from '../bundle/bundleDiagnostics';import { scanSideModuleIds, sideModuleFiles, textureDecoderBytes } from '../bundle/sideModuleScan';import { OPEN_DATA_DIR, isEsModule } from './miniGameExportProfile';+import type { RpkSigningKey } from './rpk';import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSystems';import { resolveEmcc, runEmcc } from '../bundle/emccPath';@@ -58,6 +59,16 @@ import { engineInstalls, forcedSideModules, moduleChoices } from '../bundle/engi+/** The icon's bytes, or null. A path that no longer exists is a warning: the+ * package is still correct, it just carries the vendor profile's default. */+async function readAppIcon(root: string, rel: string | undefined, warnings: string[]): Promise<Uint8Array | null> {+ if (!rel) return null;+ const file = path.join(root, rel);+ if (existsSync(file)) return new Uint8Array(await readFile(file));+ warnings.push(`The app icon ${rel} does not exist — packaged with the default.`);+ return null;+}+export interface ExportMiniGameResult {ok: boolean;platform: MiniGameVendor;@@ -74,6 +85,8 @@ export interface ExportMiniGameResult {bundleModules?: ModuleBytes[];/** Project-relative subpackage roots — what is NOT on the main package's cap. */subPackageRoots?: string[];+ /** The single file the vendor takes, when it takes one (a quick game's `.rpk`). */+ packageFile?: string;/** Staged path → what that file weighed before this export packed it. A limit* is judged on packed bytes, so the report has no other way to know. */packedFrom?: Record<string, number>;@@ -263,6 +276,12 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {appid?: string;/** The project's version (ProjectManifest.version), for a host config that asks. */appVersion?: string;+ /** The build ordinal, for a host that compares packages by it. Absent ⇒ 1. */+ versionCode?: number;+ /** The app icon, project-relative (packaging.icon). */+ appIcon?: string;+ /** The project's signing key, for a vendor that takes a signed file. */+ releaseKey?: RpkSigningKey;/** Screen orientation (Project Settings) → game.json. */orientation?: 'portrait' | 'landscape';/** The project's runtime settings, derived once by `runtimeConfigOf`; the@@ -630,6 +649,8 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {title,appid: opts.appid ?? '',version: opts.appVersion ?? '1.0.0',+ versionCode: opts.versionCode ?? 1,+ icon: await readAppIcon(opts.root, opts.appIcon, warnings),orientation: opts.orientation ?? 'portrait',subPackages: subPackages.subPackages,includeSuffixes: packIncludeSuffixes(cookEntries, profile.nativeSuffixes),@@ -700,8 +721,17 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {warnings.push(...await stageProjectModules(projectModules, wasmOut, profile.id,async (code) => (await transform(code, { target: profile.esTarget, loader: 'js' })).code));+ // Last, over the finished directory: a signed package covers every byte in it.+ let packageFile: string | undefined;+ if (profile.pack && errors.length === 0) {+ const packed = await profile.pack({ outDir: absOut, appid: opts.appid ?? '', releaseKey: opts.releaseKey });+ packageFile = packed.file;+ warnings.push(...packed.warnings);+ }+return {ok: errors.length === 0, platform: profile.id, outDir: absOut,+ ...(packageFile ? { packageFile } : {}),included: cook.included.length, warnings, errors, inclusion: cook.inclusion,bundleModules,// The size report weighs the main package against a cap the subpackages arediff --git a/pipeline/src/export/miniGameExportProfile.ts b/pipeline/src/export/miniGameExportProfile.tsindex cb0c70f51..f57851119 100644--- a/pipeline/src/export/miniGameExportProfile.ts+++ b/pipeline/src/export/miniGameExportProfile.ts@@ -14,6 +14,11 @@import { WECHAT_MODULE_BUILD_TARGET } from '../bundle/sideModuleScan';import type { RuntimeHost } from '../bundle/runtimeHosts';import type { SizeBudget } from '../project/sizeBudget';+import { packRpk, type RpkSigningKey } from './rpk';+import { RPK_DEBUG_KEY } from './rpkDebugKey';+import { QUICKGAME_DEFAULT_ICON } from './quickgameDefaultIcon';+import { readdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';/*** A mini-game vendor's id. Open on purpose: the value is identity — the cook's@@ -22,7 +27,7 @@ import type { SizeBudget } from '../project/sizeBudget';* ship can still be exported by handing {@link exportMiniGame} a profile.* Mirrors the SDK's `MiniGameVendor` (sdk/src/platform/minigame/api.ts).*/-export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | (string & {});+export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | (string & {});/** Vendor-neutral facts the pipeline computes, handed to the config emitter. */export interface MiniGameConfigContext {@@ -30,6 +35,10 @@ export interface MiniGameConfigContext {appid: string;/** The project's version, for a host whose config asks for one. */version: string;+ /** The build ordinal a host compares to tell a newer package from an older one. */+ versionCode: number;+ /** The project's app icon (packaging.icon), or null when it has none. */+ icon: Uint8Array | null;orientation: 'portrait' | 'landscape';/** Lazy groups present in the cook, as vendor subpackage roots. */subPackages: ReadonlyArray<{ name: string; root: string }>;@@ -74,6 +83,16 @@ export function isEsModule(glue: string): boolean {return /\bexport\s+default\b/.test(glue);}+/** What a vendor that ships a single file is handed to make it. */+export interface MiniGamePackContext {+ /** The finished package directory. */+ outDir: string;+ /** The vendor's id for the game (for a quick game, its package name). */+ appid: string;+ /** The project's own signing key; absent ⇒ the build is signed for debugging. */+ releaseKey?: RpkSigningKey;+}+/** Vendor-neutral facts the pipeline computes, handed to the entry emitter. */export interface MiniGameEntryContext {/** Optional modules the shipped scenes need (physics/spine/basis/videodec). */@@ -98,16 +117,16 @@ export interface MiniGameEntryContext {* loads JS the same way — so this is the family default, and a profile only* overrides it for an unusual loader.*/-export function defaultMiniGameEntry(ctx: MiniGameEntryContext): string {+export function defaultMiniGameEntry(ctx: MiniGameEntryContext, load = 'require'): string {const requires = ctx.sideModules- .map((m) => ` ${JSON.stringify(m.id)}: asFactory(require('./${ctx.runtimeDir}/${m.file}.js')),`)+ .map((m) => ` ${JSON.stringify(m.id)}: asFactory(${load}('./${ctx.runtimeDir}/${m.file}.js')),`).join('\n');const boot = `const asFactory = (m) => (typeof m === 'function' ? m : (m && m.default) || m);-const engineFactory = asFactory(require('./${ctx.runtimeDir}/${ctx.engineGlueFile}'));+const engineFactory = asFactory(${load}('./${ctx.runtimeDir}/${ctx.engineGlueFile}'));const sideModuleFactories = {${requires}};-const bundle = require('./game-bundle.js');+const bundle = ${load}('./game-bundle.js');// A boot that fails rejects; a host without onUnhandledRejection drops that// silently, which leaves a device on the loading screen with nothing in the log.Promise.resolve(bundle.boot(engineFactory, sideModuleFactories)).catch(function (e) {@@ -255,7 +274,13 @@ export interface MiniGameExportProfile {readonly runtimeProfileHost?: RuntimeHost;/** Emit the vendor config files (game.json + project.config.json). */- emitConfigFiles(ctx: MiniGameConfigContext): Array<{ file: string; content: string }>;+ emitConfigFiles(ctx: MiniGameConfigContext): Array<{ file: string; content: string | Uint8Array }>;+ /**+ * Turn the finished directory into the one file the vendor takes, when it+ * takes a file (a quick game's signed `.rpk`). Absent ⇒ the directory is the+ * package, as a WeChat project is.+ */+ pack?(ctx: MiniGamePackContext): Promise<{ file: string; warnings: string[] }>;/** Emit the MiniGame entry the host runs (game.js). */emitEntry(ctx: MiniGameEntryContext): string;}@@ -504,3 +529,103 @@ export const bilibiliExportProfile: MiniGameExportProfile = {emitEntry: defaultMiniGameEntry,};++// =============================================================================+// Quick-game profile (快游戏联盟: vivo / OPPO / Xiaomi / Honor)+// =============================================================================++const QUICKGAME_ICON = 'icon.png';++/** The host evaluates a required file at global scope with no CommonJS wrapper+ * (a package that relied on one died on `module is not defined`), so each load+ * gets a fresh module/exports on the global and hands back module.exports. */+const COMMONJS_SHIM = 'var __load = function (p) { var m = { exports: {} }; globalThis.module = m; '+ + 'globalThis.exports = m.exports; require(p); return m.exports; };\n';++/**+ * The alliance's unified package (gamedoc.quickapp.cn, 1300): `manifest.json` ++ * `game.js` + an icon, signed into `<package>.rpk`. The name must end in+ * `.minigame` and `allianceVersion: 1300` marks it as the alliance's. It runs on+ * the `quickgame` engine build.+ */+export const quickgameExportProfile: MiniGameExportProfile = {+ id: 'quickgame',+ sdkEntryFile: 'index.minigame.js',+ runtimeInit: 'initMiniGameRuntime',+ runtimeProfileHost: 'quickgamePlatformProfile',+ engineGlueCandidates: MINIGAME_ENGINE_GLUE,+ // WeChat's floor; the host's V8 is 8.3, which takes es2017.+ esTarget: 'es2017',+ wasmBuildHint: 'quickgame',+ hostGlobal: 'qg',+ sideModuleBuildTargets: {},+ // Assumed to match the other vendors, not read from a quick-game doc; a wrong+ // guess is a staged file the runtime cannot read.+ nativeSuffixes: new Set(['.js', '.json']),+ // No upload whitelist is published for the rpk; nothing is restaged.+ packerSuffixes: null,+ // No doc names a `.wasm.br` loader for this host.+ wasmBrotli: false,+ subpackageDir: 'subpackages',+ // 「主包和分包都可以是main.js 或 game.js」.+ subpackageEntry: 'game.js',++ emitConfigFiles(ctx) {+ if (!ctx.appid.endsWith('.minigame')) {+ throw new Error(`the quick-game package name is "${ctx.appid}", and the host takes only one that ends in `+ + '".minigame" — set it in Project Settings → Packaging → Quick game');+ }+ const manifest: Record<string, unknown> = {+ package: ctx.appid,+ name: ctx.title,+ icon: `/${QUICKGAME_ICON}`,+ versionName: ctx.version,+ versionCode: ctx.versionCode,+ // 「1160(此字段是取各家兼容最低版本支持)」; vivo's 1203 engine took it.+ minPlatformVersion: 1160,+ allianceVersion: 1300,+ type: 'game',+ orientation: ctx.orientation,+ deviceOrientation: ctx.orientation,+ config: { logLevel: 'log' },+ };+ if (ctx.subPackages.length > 0) {+ manifest.subpackages = ctx.subPackages.map((s) => ({ name: s.name, root: s.root }));+ }+ return [+ { file: 'manifest.json', content: JSON.stringify(manifest, null, 2) + '\n' },+ { file: QUICKGAME_ICON, content: ctx.icon ?? QUICKGAME_DEFAULT_ICON },+ ];+ },++ emitEntry(ctx) {+ return defaultMiniGameEntry(ctx, '__load').replace("'use strict';\n", `'use strict';\n${COMMONJS_SHIM}`);+ },++ async pack(ctx) {+ const warnings: string[] = [];+ const key = ctx.releaseKey ?? RPK_DEBUG_KEY;+ if (!ctx.releaseKey) {+ warnings.push('Signed with the public debug key, which a device debugger installs and a store refuses —'+ + ' set a release key in Project Settings → Packaging → Quick game to publish.');+ }+ const file = `${ctx.appid}.rpk`;+ const entries = [];+ for (const name of await listFiles(ctx.outDir)) {+ if (name.endsWith('.rpk')) continue;+ entries.push({ name, data: await readFile(path.join(ctx.outDir, name)) });+ }+ await writeFile(path.join(ctx.outDir, file), packRpk(entries, QUICKGAME_ICON, key));+ return { file: path.join(ctx.outDir, file), warnings };+ },+};++async function listFiles(root: string, prefix = ''): Promise<string[]> {+ const out: string[] = [];+ for (const e of await readdir(path.join(root, prefix), { withFileTypes: true })) {+ const rel = prefix ? `${prefix}/${e.name}` : e.name;+ if (e.isDirectory()) out.push(...await listFiles(root, rel));+ else if (e.isFile()) out.push(rel);+ }+ return out;+}diff --git a/pipeline/src/export/platformCatalog.ts b/pipeline/src/export/platformCatalog.tsindex 45be1ef88..5571450e4 100644--- a/pipeline/src/export/platformCatalog.ts+++ b/pipeline/src/export/platformCatalog.ts@@ -48,6 +48,8 @@ export interface PlatformRuntimeDirs {* The directory is what makes a package's engine CommonJS; the filename in it* is only a name, and a project's own vendor dir may use either. */minigame: string;+ /** The mini-game engine without SIMD and BigInt i64, for the quick-game hosts. */+ quickgame: string;}/** What the renderer needs to draw one platform row. Serializable by construction. */@@ -129,6 +131,11 @@ function builtinReadiness(? { ready: true }: { ready: false, prereq: { kind: 'runtime-missing', dir: posix(dirs.minigame), looked: [...MINIGAME_ENGINE_GLUE], command: `node build-tools/cli.js build -t ${MINIGAME_ENGINE_BUILD}` } };+ case 'quickgame':+ return MINIGAME_ENGINE_GLUE.some((g) => has(dirs.quickgame, g))+ ? { ready: true }+ : { ready: false, prereq: { kind: 'runtime-missing', dir: posix(dirs.quickgame), looked: [...MINIGAME_ENGINE_GLUE], command: 'node build-tools/cli.js build -t quickgame' } };+case 'android':// The runtime template is the whole prerequisite: the APK is assembled and// signed here, on any OS, with nothing from the Android SDK.diff --git a/pipeline/src/export/quickgameDefaultIcon.ts b/pipeline/src/export/quickgameDefaultIcon.tsnew file mode 100644index 000000000..a4c05cdd8--- /dev/null+++ b/pipeline/src/export/quickgameDefaultIcon.ts@@ -0,0 +1,160 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Estella's mark at 192×192 (native/icon.png, downscaled): the icon a+ * quick-game package carries when the project sets none. The host refuses+ * a manifest without one, and asks for a square of at most 100KB.+ */+export const QUICKGAME_DEFAULT_ICON: Uint8Array = Buffer.from([+ 'iVBORw0KGgoAAAANSUhEUgAAAMAAAADACAYAAABS3GwHAAAr5UlEQVR42u19228k2X3e9ztVfW+SzdsMLzOzs7M3aaCFJT0ITiwL',+ 'iB0ZyIMNCAjiB0GRbRgJIgOGEtjwn2DJD4ngZ8OSrCiIAzhKnJdEjh0gkBUDAoxk11hpJVnamZ3rznDIHt6a3VXnl4dzquqcU1XN',+ 'vnLImXNW1JBssrtZ9X2/+4VwdocACP15bD6wsnJlO0J8k5jfJIibgLwG4BoDLYAWidACEMCfi3RiZhwC/JSAQwC3AXGbId9hordD',+ 'BO88eXLnrvM7yT2WAPisQHkWrxEAiJJvLC1dWyaKfg7EvwDCzwL4EEDLZLwbtv/Pnwt7KPlfdm/Vfd0F8AMw/gZMf8Uc/nW3e3vX',+ '+LFQC0q+qAQQ+vljALhy5Urj4Dj+JTD9KsC/SCQuJVBnTpEujfdFZ0xUf2Z/2PmcTWwQZbeZWX4A0F+C+E/bjeDbd+7cOTa0gomN',+ 'c08AS+IvL29dZZK/BtDniMRr+o9N1Jw0iOJB/uKRgw0MCCKRkOFHAH+DWHxtd/fe+/PUCLMGXZBI/KWly9ch6ItE9Hki0dGSPrHt',+ 'hAe8PwWEkFozCIDALPeY+euQ/JVu9+F7LsbOEwESBzdeXV1diLn2bwD+IpHoaGkfJSz399mfEU5iHYREAsxyD6CvBHTyb3d2dvY1',+ 'CWbiKNNMpf7K5mcI+DKReM0AfuClvT9TaIXYIMKPGPi97pP735qVNpgWmCGAaGlpaRlh898J0OeVDcce+P7MnAhEFCr1wF9HdPSv',+ 'u93uboLBsyZA6uguL29+kglfJRKvMsvYiff748+sTSMmEgGz/DExfn139/53pnGQg2ns/cXljX9JRP+JiNa01A+91PcHc0+mckRE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DP0v5H7u79z+nfVs5ikod',+ 'F8DUOz74s1qj/bIg8XHtE/hyCX+epcMbE4mKhPyT7pP7nzMc3pHsyUkkOJ0cH3xL+wQ/D3tXkD/+4OyyvCBV5hD/QffJg99K6tnG',+ 'caYmNWGC3vHBt6v11gMi+idEFGhnw+cJ/MHZRHooABBLll/o7j74klHCP1YkYRobPjzpHXyvUV/4Xwx8ikis6eI5eG3gzxylvtRh',+ 'zh8T4zPd3Qff0g6vxARhtGDKNxP2egfv1arBv2cRbgiij5GasOV9A3/mYOtTQERCgr+O+Oif7u09/uEooc555+vTGoullc3PEPBl',+ 'IvGa3pCeJM48EfyZGPgAQtXOK3/EwO91n9z/lou9acA7k1mLAIKT44N3Ws3a1yQHJwA+SiSaetJE5E0jf8a0LmIAAZEQAO8B+FJA',+ '/V/fffLB/zNwK89bxVamDZYuX4egLxLR54lER68NSuw04cngT4Eg1ZEdEgCBWe4x89ch+Svd7sP3ZiX150mA5DmTqBCWl7euMslf',+ 'A+hzROI11QAlU4fGIIMnxAtYtGZgQJBeIM4sfwTwN4jF13Z3772fBF008Pk81+zCncGYsPXKlSuNg+P4l8D0qwD/IpG4lLaAM5sS',+ 'AAWE8OR4DkYIG18LLenTW8ssPwDoL0H8p+1G8O07d+4cGxJ/boObzwJYlkZQ5tG1ZaLo50D8CyD8LIAPAbRs9owzkB8E5Q8uZOEf',+ '2UDT8m4XwA/A+Bsw/RVz+Nfd7u1d48fmIvGfBQHM10oSZZYNt7JyZTtCfJOY3ySIm4C8BuAaAy2AFonQ8nVHF+7Eagc1PyXgEMBt',+ 'QNxmyHeY6O0QwTtPnty5WxKUkWcl+f4/RT8eTU4+s5kAAAAASUVORK5CYII=',+].join(''), 'base64');diff --git a/pipeline/src/export/rpk.ts b/pipeline/src/export/rpk.tsnew file mode 100644index 000000000..25ff89c62--- /dev/null+++ b/pipeline/src/export/rpk.ts@@ -0,0 +1,210 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The quick-game package (`.rpk`): a zip with an APK-v2-style signing+ * block ("RPK Sig Block 42") inserted before its central directory.+ *+ * The format is the 快游戏联盟's (vivo / OPPO / Xiaomi / Honor share it), written+ * here from the vendor CLI's own signer (@quick-game/cli, lib/bundle.js) and the+ * hapjs runtime's verifier (SignatureVerifier / FileListSignatureVerifier), so a+ * package needs neither the CLI nor its dependencies to be built. The byte layout+ * is checked against an independent verifier in rpk.test.ts.+ */+import { createHash, createPublicKey, sign } from 'node:crypto';+import { deflateRawSync } from 'node:zlib';++export interface RpkEntry {+ /** Package-relative path, `/`-separated. ASCII only: the runtime keys the file+ * list by a CRC of the name's UTF-8 bytes and the vendor CLI by its low bytes,+ * and the two agree only for ASCII. */+ readonly name: string;+ readonly data: Uint8Array;+}++export interface RpkSigningKey {+ readonly privateKeyPem: string;+ readonly certificatePem: string;+}++/**+ * The order the vendor CLI writes entries in: the entry script first, then the+ * other scripts, then `manifest.json`, then the icon, then everything else. The+ * engine starts running script as soon as it has streamed the manifest, so what+ * it needs must already be in front of it.+ */+export function orderRpkEntries<T extends { name: string }>(entries: readonly T[], iconPath: string): T[] {+ const rank = (n: string): number => (n === 'main.js' || n === 'game.js') ? 0+ : n.endsWith('.js') ? 1 : n === 'manifest.json' ? 2 : n === iconPath ? 3 : 4;+ return [...entries].sort((a, b) => rank(a.name) - rank(b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));+}++const CRC_TABLE = (() => {+ const t = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ t[n] = c >>> 0;+ }+ return t;+})();++export function crc32(bytes: Uint8Array): number {+ let c = 0xffffffff;+ for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++/** 1980-01-01 00:00 in DOS time: a fixed stamp, so the same content packs to the same bytes. */+const DOS_TIME = 0;+const DOS_DATE = (0 << 9) | (1 << 5) | 1;++/** A plain zip: DEFLATE entries, sizes in the local headers (no data descriptor),+ * no directory entries, first local header at offset 0 — what the signer needs. */+export function writeZip(entries: readonly RpkEntry[]): Buffer {+ const locals: Buffer[] = [];+ const centrals: Buffer[] = [];+ let offset = 0;+ for (const { name, data } of entries) {+ if (!/^[\x20-\x7e]+$/.test(name)) throw new Error(`rpk entry "${name}" is not ASCII`);+ const nameBytes = Buffer.from(name, 'ascii');+ const packed = deflateRawSync(data, { level: 9 });+ const crc = crc32(data);+ const local = Buffer.alloc(30);+ local.writeUInt32LE(0x04034b50, 0);+ local.writeUInt16LE(20, 4);+ local.writeUInt16LE(0, 6);+ local.writeUInt16LE(8, 8);+ local.writeUInt16LE(DOS_TIME, 10);+ local.writeUInt16LE(DOS_DATE, 12);+ local.writeUInt32LE(crc, 14);+ local.writeUInt32LE(packed.length, 18);+ local.writeUInt32LE(data.length, 22);+ local.writeUInt16LE(nameBytes.length, 26);+ local.writeUInt16LE(0, 28);+ const central = Buffer.alloc(46);+ central.writeUInt32LE(0x02014b50, 0);+ central.writeUInt16LE(20, 4);+ central.writeUInt16LE(20, 6);+ central.writeUInt16LE(0, 8);+ central.writeUInt16LE(8, 10);+ central.writeUInt16LE(DOS_TIME, 12);+ central.writeUInt16LE(DOS_DATE, 14);+ central.writeUInt32LE(crc, 16);+ central.writeUInt32LE(packed.length, 20);+ central.writeUInt32LE(data.length, 24);+ central.writeUInt16LE(nameBytes.length, 28);+ central.writeUInt32LE(offset, 42);+ locals.push(local, nameBytes, packed);+ centrals.push(central, nameBytes);+ offset += local.length + nameBytes.length + packed.length;+ }+ const cd = Buffer.concat(centrals);+ const eocd = Buffer.alloc(22);+ eocd.writeUInt32LE(0x06054b50, 0);+ eocd.writeUInt16LE(entries.length, 8);+ eocd.writeUInt16LE(entries.length, 10);+ eocd.writeUInt32LE(cd.length, 12);+ eocd.writeUInt32LE(offset, 16);+ return Buffer.concat([...locals, cd, eocd]);+}++const RSA_PKCS1_SHA256 = 0x0103;+const BLOCK_SIGNER = 0x01000101;+const BLOCK_FILE_LIST = 0x01000201;+const MAGIC = Buffer.from('RPK Sig Block 42', 'ascii');++const u32 = (n: number): Buffer => { const b = Buffer.alloc(4); b.writeUInt32LE(n >>> 0); return b; };+const u64 = (n: number): Buffer => { const b = Buffer.alloc(8); b.writeBigUInt64LE(BigInt(n)); return b; };+const lp = (b: Buffer): Buffer => Buffer.concat([u32(b.length), b]);+const sha256 = (...parts: Buffer[]): Buffer => {+ const h = createHash('sha256');+ for (const p of parts) h.update(p);+ return h.digest();+};++function pemToDer(pem: string): Buffer {+ const m = /-----BEGIN [^-]+-----([A-Za-z0-9+/=\s]+)-----END [^-]+-----/.exec(pem);+ if (!m) throw new Error('certificate is not PEM');+ return Buffer.from(m[1].replace(/\s+/g, ''), 'base64');+}++/**+ * Insert the signing block into `zip`, whose entries are `entries` in the same+ * order. Each of the three zip sections is digested whole (no 1MB chunking — the+ * runtime's block 0x01000101 uses one chunk per section), and the end record's+ * central-directory offset is moved past the inserted block.+ */+export function signRpk(zip: Buffer, entries: readonly RpkEntry[], key: RpkSigningKey): Buffer {+ let eocd = -1;+ for (let o = zip.length - 22; o >= 0; o--) if (zip.readUInt32LE(o) === 0x06054b50) { eocd = o; break; }+ if (eocd < 0) throw new Error('not a zip: no end of central directory');+ const cd = zip.readUInt32LE(eocd + 16);+ const sections = [zip.subarray(0, cd), zip.subarray(cd, eocd), zip.subarray(eocd)];+ const chunkDigests = sections.map((s) => sha256(Buffer.from([0xa5]), u32(s.length), s));+ const contentDigest = sha256(Buffer.from([0x5a]), u32(sections.length), ...chunkDigests);++ const certDer = pemToDer(key.certificatePem);+ const spki = createPublicKey(key.certificatePem).export({ type: 'spki', format: 'der' });+ const signedData = Buffer.concat([+ lp(lp(Buffer.concat([u32(RSA_PKCS1_SHA256), lp(contentDigest)]))),+ lp(lp(certDer)),+ u32(0),+ ]);+ const signature = sign('sha256', signedData, key.privateKeyPem);+ const signer = Buffer.concat([+ lp(signedData),+ lp(lp(Buffer.concat([u32(RSA_PKCS1_SHA256), lp(signature)]))),+ lp(spki),+ ]);++ const digestList = Buffer.concat([+ u32(RSA_PKCS1_SHA256),+ ...entries.map(({ name, data }) => {+ const head = Buffer.alloc(6);+ head.writeUInt32LE(crc32(Buffer.from(name, 'utf8')));+ head.writeUInt16LE(32, 4);+ return Buffer.concat([head, sha256(Buffer.from(data))]);+ }),+ ]);+ const listSignature = sign('sha256', digestList, key.privateKeyPem);++ const pair = (id: number, value: Buffer): Buffer => Buffer.concat([u64(4 + value.length), u32(id), value]);+ const pairs = Buffer.concat([+ pair(BLOCK_SIGNER, lp(lp(signer))),+ pair(BLOCK_FILE_LIST, lp(Buffer.concat([lp(digestList), lp(Buffer.concat([u32(RSA_PKCS1_SHA256), lp(listSignature)]))]))),+ ]);+ const blockSize = pairs.length + 8 + MAGIC.length;+ const block = Buffer.concat([u64(blockSize), pairs, u64(blockSize), MAGIC]);++ const end = Buffer.from(sections[2]);+ end.writeUInt32LE(cd + block.length, 16);+ return Buffer.concat([sections[0], block, sections[1], end]);+}++/** Zip and sign a package whose files are `entries`. */+export function packRpk(entries: readonly RpkEntry[], iconPath: string, key: RpkSigningKey): Buffer {+ const ordered = orderRpkEntries(entries, iconPath);+ return signRpk(writeZip(ordered), ordered, key);+}++/**+ * A project's release key, read from the two PEM paths its packaging names.+ * Null when it names none; a named file that is missing is an error, because a+ * package silently signed with the debug key instead is one a store refuses.+ */+export async function readReleaseKey(+ root: string,+ paths: { privateKey: string; certificate: string } | undefined,+): Promise<RpkSigningKey | null> {+ if (!paths || (!paths.privateKey && !paths.certificate)) return null;+ const { readFile } = await import('node:fs/promises');+ const { join } = await import('node:path');+ try {+ return {+ privateKeyPem: await readFile(join(root, paths.privateKey), 'utf8'),+ certificatePem: await readFile(join(root, paths.certificate), 'utf8'),+ };+ } catch (e) {+ throw new Error(`the quick-game release key could not be read (${paths.privateKey}, ${paths.certificate}): ${(e as Error).message}`);+ }+}diff --git a/pipeline/src/export/rpkDebugKey.ts b/pipeline/src/export/rpkDebugKey.tsnew file mode 100644index 000000000..3360c3026--- /dev/null+++ b/pipeline/src/export/rpkDebugKey.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The key every debug quick-game package is signed with.+ *+ * Public on purpose, like the vendor CLI's own debug key: a debug package only+ * has to install on a developer's device (vivo's debugger took this one). A+ * release package is signed with the project's own key, which a vendor binds to+ * the package name for good.+ */+import type { RpkSigningKey } from './rpk';++export const RPK_DEBUG_KEY: RpkSigningKey = {+ privateKeyPem: `-----BEGIN PRIVATE KEY-----+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCqhmdBjHcu38Ly+bQZlW7ZVaco0Q9uwyXBpq+ZiEQIJC6TWpNx2p850nW34r2yVeW14cw1SJKUXgNym+ztoZaRsNX3Zv8lercLYRqI5chSPIR9uglCLEosb7wgXBqUiXd1XBFpTJ3G7OhkHk+0HSbi+UEQeeR4AohS4mre2FdloVQGH8V29NK5pV19cQazxudM+g6/bmJ8MYgrdgN+oSotCXE2WuquziTBcpMQMwdHAXhfPJ3AJz44mMSoylTMHP3GgmbG5+eUJZORIK5++3ZQ5YLOnFyzmb5Qo23egNM6AMQ12i/csvyVbX39pSxeQFeyIAgzjglWqOQ0Wbw1Z+3qbx64vBAgMBAAECggEAZSjCTHJlqZr4bRQcPTjA276cQ5EV3LRDSYy+aOKqEG+l+4+d9Ga7GnQtfV63JforAVDn8ZwRyI5VAUHxZicV+VNqSyio7s+pzN9qESYJ6DbAD+LCl0zq252VPqUk54T9JtPtSEg5OO8FlY8cJvym6c93+ZPkJoAARtsRrKUdifUTme+5wJJ2U5VaWFAz5W52gQ2YY6x21E6tpsQLJnIvAItJP9QHjRsuGz+S2d5XmK+/L/Q+kccr2na54MvJTh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BAQsFADA7MQswCQYDVQQGEwJD+TjEQMA4GA1UECgwHRXN0ZWxsYTEaMBgGA1UEAwwRRXN0ZWxsYSBSUEsgRGVidWcw+IBcNMjYwOTI0MDIwMjU4WhgPMjEyNjA4MzEwMjAyNThaMDsxCzAJBgNVBAYTAkNO+MRAwDgYDVQQKDAdFc3RlbGxhMRowGAYDVQQDDBFFc3RlbGxhIFJQSyBEZWJ1ZzCC+ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKqGZ0GMdy7fwvJtBmVbtlVp+yjRD27DJcGmr5mIRAgkLpNak3HanznSdbfivbJV5bXhzDVIkpReA3KbO2hlpGw1f+dm/yV6twthGojlyFI8hH26CUIsSixvvCBcGpSJd3VcEWlMncbs6GQeTQdJuL5QRB+55HgCiFLiat7YV2WhVAYfxXb00rmlXX1xBrPG50z6Dr9uYnwxiCt2A2hKi0JcTZa+6q7OJMFykxAzB0cBeF88ncAnPjiYxKjKVMwc/caCZsbn55Qlk5Egrn7dlDlgs6cX+LOZvlCjbd6A0zoAxDXaL9yy/JVtff2lLF5AV7IgCDOOCVao5DRZvDVnepvHri8EC+AwEAATANBgkqhkiG9w0BAQsFAAOCAQEAqALoIWQTCT3UAlXcJCP+49coatG0rAMI+ah86oU2loKcseUNiamhSSnQKO4JqQmRrUABT66HwDiMJIioMYOAriiktc4Vhy9lr+/EkRUdMdMw9Mh8mTBnBSSIONdocXRb/i4bJYqhicBXeBwwaj/52+vrT1tCeRCNct+RfHxISUfO4jJ2dLMnu22B1jhHr1FqLYTVLyDQW62nHYC2IeUe4IyCfxTN/ufnjuL+0gIPdO6B1wtzeNaAhokRtqRrnsRIilFBdgQew8tiZLOS+9JAPBDI7HfqKCUxQhhL+qfYLB+2KE/ex5e7mod4qGfuLlngaIiDdy0yLNukmgs41lV0G2R4+OA==+-----END CERTIFICATE-----`,+};diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.tsindex 89b2f1895..da0d96ffc 100644--- a/pipeline/src/project/format.ts+++ b/pipeline/src/project/format.ts@@ -208,6 +208,14 @@ export type RenderResolutionMode = 'surface' | 'design' | 'integer';* other. */export interface MiniGamePackaging { appid?: string; }export type WeChatPackaging = MiniGamePackaging;+/** A quick game ships a signed `.rpk`: `appid` is its package name (ending in+ * `.minigame`), and the release key is what a vendor binds that name to. */+export interface QuickGamePackaging extends MiniGamePackaging {+ /** The build ordinal a host compares packages by; it must grow with each upload. */+ versionCode?: number;+ /** Project-relative PEM files. Absent ⇒ signed with the public debug key. */+ releaseKey?: { privateKey: string; certificate: string };+}export interface DesktopPackaging {appId?: string;productName?: string;@@ -383,6 +391,7 @@ export interface ProjectPackaging {wechat?: MiniGamePackaging;douyin?: MiniGamePackaging;bilibili?: MiniGamePackaging;+ quickgame?: QuickGamePackaging;desktop?: DesktopPackaging;android?: AndroidPackaging;ios?: IosPackaging;@@ -818,6 +827,17 @@ export function parseManifest(raw: unknown): ProjectManifest {const v = pl[vendor] as Record<string, unknown> | undefined;if (v && typeof v === 'object' && typeof v.appid === 'string') platforms[vendor] = { appid: v.appid };}+ const qg = pl.quickgame as Record<string, unknown> | undefined;+ if (qg && typeof qg === 'object') {+ const q: QuickGamePackaging = {};+ if (typeof qg.appid === 'string') q.appid = qg.appid;+ if (typeof qg.versionCode === 'number' && Number.isInteger(qg.versionCode) && qg.versionCode > 0) q.versionCode = qg.versionCode;+ const key = qg.releaseKey as Record<string, unknown> | undefined;+ if (key && typeof key.privateKey === 'string' && typeof key.certificate === 'string') {+ q.releaseKey = { privateKey: key.privateKey, certificate: key.certificate };+ }+ if (Object.keys(q).length > 0) platforms.quickgame = q;+ }const dt = pl.desktop as Record<string, unknown> | undefined;if (dt && typeof dt === 'object') {const d: DesktopPackaging = {};diff --git a/pipeline/src/project/platforms.ts b/pipeline/src/project/platforms.tsindex b7c66a2b8..baf6ca221 100644--- a/pipeline/src/project/platforms.ts+++ b/pipeline/src/project/platforms.ts@@ -21,11 +21,11 @@* Xcode), so a single row could not tell you what to run, whether this machine* can run it, or where the package comes out.*/-export type BuiltinPlatform = 'web' | 'desktop' | 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'playable' | 'android' | 'ios';+export type BuiltinPlatform = 'web' | 'desktop' | 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | 'playable' | 'android' | 'ios';/** Built-ins, in the order they are offered. */export const BUILTIN_PLATFORMS: readonly BuiltinPlatform[] = [- 'web', 'desktop', 'wechat', 'douyin', 'kuaishou', 'bilibili', 'playable', 'android', 'ios',+ 'web', 'desktop', 'wechat', 'douyin', 'kuaishou', 'bilibili', 'quickgame', 'playable', 'android', 'ios',];/**@@ -63,9 +63,19 @@ export function isNativePlatform(platform: ExportPlatform): platform is NativePl* project's own vendor is one of these without appearing here, so that build* lives in the family's export defaults rather than behind this list.*/-export const MINIGAME_PLATFORMS = ['wechat', 'douyin', 'kuaishou', 'bilibili'] as const;+export const MINIGAME_PLATFORMS = ['wechat', 'douyin', 'kuaishou', 'bilibili', 'quickgame'] as const;export type MiniGamePlatform = (typeof MINIGAME_PLATFORMS)[number];+/**+ * Which engine build a web-runtime target packages: the browser one, the+ * CommonJS mini-game one, or that one again without wasm SIMD and BigInt i64 for+ * the quick-game hosts, whose V8 (8.3) refuses both.+ */+export function engineBuildFor(platform: ExportPlatform): 'web' | 'minigame' | 'quickgame' {+ if (platform === 'quickgame') return 'quickgame';+ return isMiniGamePlatform(platform) ? 'minigame' : 'web';+}+export function isMiniGamePlatform(platform: ExportPlatform): platform is MiniGamePlatform {return (MINIGAME_PLATFORMS as readonly string[]).includes(platform);}diff --git a/pipeline/src/project/serviceSupport.ts b/pipeline/src/project/serviceSupport.tsindex 44d46edb9..a7bb0816d 100644--- a/pipeline/src/project/serviceSupport.ts+++ b/pipeline/src/project/serviceSupport.ts@@ -203,6 +203,35 @@ const BILIBILI_SERVICES: readonly ServiceStatus[] = [{ service: 'achievements', support: 'no', note: ACHIEVEMENTS_LOCAL_ONLY },];+/** From vivo's and OPPO's docs; a game has run on vivo's engine in an emulator,+ * and nothing here has been exercised on a device. */+const QUICKGAME_SERVICES: readonly ServiceStatus[] = [+ {+ service: 'ads',+ support: 'unknown',+ note: 'qg.createRewardedVideoAd / qg.createInterstitialAd are documented by vivo and OPPO (onClose carries'+ + ' isEnded); a phone that is not the vendor\'s only gets preview ads. Unverified on a device.',+ },+ {+ service: 'share',+ support: 'no',+ note: 'The hosts share through their own qg.share rather than shareAppMessage, so the engine\'s share sheet'+ + ' reports itself unavailable here.',+ },+ {+ service: 'signIn',+ support: 'unknown',+ note: 'The engine forwards to qg.login; what it yields differs between vendors. Unverified on a device.',+ },+ {+ service: 'purchase',+ support: 'no',+ note: 'Each vendor sells through its own qg.pay with a server-signed order — a shape the engine\'s purchase'+ + ' request does not carry, so the profile leaves the slot empty.',+ },+ { service: 'achievements', support: 'no', note: ACHIEVEMENTS_LOCAL_ONLY },+];+const DESKTOP_SERVICES: readonly ServiceStatus[] = noHostServices().map((s) => (s.service === 'achievements'? {@@ -226,6 +255,7 @@ export function builtinServiceSupport(platform: ExportPlatform): readonly Servicif (platform === 'douyin') return DOUYIN_SERVICES;if (platform === 'kuaishou') return KUAISHOU_SERVICES;if (platform === 'bilibili') return BILIBILI_SERVICES;+ if (platform === 'quickgame') return QUICKGAME_SERVICES;if (platform === 'desktop') return DESKTOP_SERVICES;if (platform === 'web' || platform === 'playable' || platform === 'android' || platform === 'ios') {return noHostServices();diff --git a/pipeline/src/project/sizeBudget.ts b/pipeline/src/project/sizeBudget.tsindex fc0f0d02e..43bad50ad 100644--- a/pipeline/src/project/sizeBudget.ts+++ b/pipeline/src/project/sizeBudget.ts@@ -79,6 +79,7 @@ export function builtinSizeBudgets(platform: ExportPlatform): readonly SizeBudgeif (platform === 'douyin') return DOUYIN_BUDGETS;if (platform === 'kuaishou') return KUAISHOU_BUDGETS;if (platform === 'bilibili') return BILIBILI_BUDGETS;+ if (platform === 'quickgame') return QUICKGAME_BUDGETS;return NO_BUDGETS;}@@ -118,6 +119,16 @@ const BILIBILI_BUDGETS: readonly SizeBudget[] = [{ scope: 'total', maxBytes: 30 * MB, note: 'Bilibili caps a mini-game at 30MB across the main package and all subpackages' },];+/**+ * The tightest of the alliance's members, since one .rpk goes to all of them:+ * vivo 「主包<4MB + 所有分包<16MB」(minigame.vivo.com.cn/documents/#/lesson/base/start),+ * OPPO 「主包 ≤ 4M|所有分包之和 ≤ 26M」.+ */+const QUICKGAME_BUDGETS: readonly SizeBudget[] = [+ { scope: 'initial', maxBytes: 4 * MB, note: 'vivo and OPPO cap a quick game\'s main package at 4MB' },+ { scope: 'total', maxBytes: 20 * MB, note: 'vivo caps a quick game at 20MB — a 4MB main package and 16MB of subpackages' },+];+const NO_BUDGETS: readonly SizeBudget[] = [];/**diff --git a/pipeline/src/runtime/quickgamePlatformProfile.ts b/pipeline/src/runtime/quickgamePlatformProfile.tsnew file mode 100644index 000000000..ddeeb1fb8--- /dev/null+++ b/pipeline/src/runtime/quickgamePlatformProfile.ts@@ -0,0 +1,9 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file quickgamePlatformProfile.ts — the module a quick-game package installs its+ * platform from, as the export profile's `runtimeProfileModule`.+ */+import { quickgameProfile } from 'esengine/quickgame';++export default quickgameProfile;diff --git a/pipeline/tests/export-bilibili.test.ts b/pipeline/tests/export-bilibili.test.tsindex f6bfca319..cc44848d9 100644--- a/pipeline/tests/export-bilibili.test.ts+++ b/pipeline/tests/export-bilibili.test.ts@@ -83,11 +83,11 @@ describe('exportGame (bilibili)', () => {it('declares subpackages under the key Bilibili reads, and an open data context when there is one', () => {const [cfg] = bilibiliExportProfile.emitConfigFiles({- title: 't', appid: 'biligame1', version: '1.0.0', orientation: 'portrait',+ title: 't', appid: 'biligame1', version: '1.0.0', versionCode: 1, icon: null, orientation: 'portrait',subPackages: [{ name: 'level2', root: 'subpackages/level2/' }],includeSuffixes: [], hasOpenData: true, openDataRoot: 'open-data',});- const json = JSON.parse(cfg.content);+ const json = JSON.parse(String(cfg.content));expect(json.subpackages).toEqual([{ name: 'level2', root: 'subpackages/level2/' }]);expect(json.openDataContext).toBe('open-data');});diff --git a/pipeline/tests/export-kuaishou.test.ts b/pipeline/tests/export-kuaishou.test.tsindex 7a7b17649..374bddee7 100644--- a/pipeline/tests/export-kuaishou.test.ts+++ b/pipeline/tests/export-kuaishou.test.ts@@ -74,11 +74,11 @@ describe('exportGame (kuaishou)', () => {it('declares subpackages under the key Kuaishou reads', () => {const [cfg] = kuaishouExportProfile.emitConfigFiles({- title: 't', appid: '', version: '1.0.0', orientation: 'landscape',+ title: 't', appid: '', version: '1.0.0', versionCode: 1, icon: null, orientation: 'landscape',subPackages: [{ name: 'level2', root: 'subpackages/level2/' }],includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data',});- const json = JSON.parse(cfg.content);+ const json = JSON.parse(String(cfg.content));expect(json.subpackages).toEqual([{ name: 'level2', root: 'subpackages/level2/' }]);expect(json).not.toHaveProperty('subPackages');});diff --git a/pipeline/tests/export-project-platform.test.ts b/pipeline/tests/export-project-platform.test.tsindex 8e04b90bd..571fd52c5 100644--- a/pipeline/tests/export-project-platform.test.ts+++ b/pipeline/tests/export-project-platform.test.ts@@ -86,7 +86,7 @@ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retrdescribe('exportGame — a platform the project defines', () => {it('packages through the mini-game pipeline and joins the vendor\'s two halves', async () => {- const platform = await loadProjectPlatform(root, 'acme-play', { web: path.join(root, '_wasm'), minigame: path.join(root, '_wasm') });+ const platform = await loadProjectPlatform(root, 'acme-play', { web: path.join(root, '_wasm'), minigame: path.join(root, '_wasm'), quickgame: path.join(root, '_wasm') });expect(platform).not.toBeNull();const res = await exportGame({@@ -134,7 +134,7 @@ describe('exportGame — a platform the project defines', () => {it('omits the install when the project installs its own platform', async () => {// Same vendor, minus the runtimeProfile link: the game is then responsible// for calling installMiniGamePlatform itself, so the entry must not guess.- const bare = { ...(await loadProjectPlatform(root, 'acme-play', { web: path.join(root, '_wasm'), minigame: path.join(root, '_wasm') }))!.profile };+ const bare = { ...(await loadProjectPlatform(root, 'acme-play', { web: path.join(root, '_wasm'), minigame: path.join(root, '_wasm'), quickgame: path.join(root, '_wasm') }))!.profile };delete (bare as { runtimeProfileModule?: string }).runtimeProfileModule;const outBare = path.join(root, 'dist-bare');diff --git a/pipeline/tests/export-quickgame.test.ts b/pipeline/tests/export-quickgame.test.tsnew file mode 100644index 000000000..7e1d3b0e4--- /dev/null+++ b/pipeline/tests/export-quickgame.test.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Quick-game export — one signed `.rpk` for the 快游戏联盟. What is its+ * own: a manifest the alliance reads (package ending in `.minigame`,+ * allianceVersion 1300), an icon always present, an entry that loads files+ * without a CommonJS wrapper, the engine build without SIMD, and the rpk+ * itself, signed with the project's key or the public debug one.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { runInNewContext } from 'node:vm';+import { exportGame } from '../src/export/exportGame';+import { builtinSizeBudgets } from '../src/project/sizeBudget';+import { engineBuildFor } from '../src/project/platforms';+import { runtimeConfigOf } from '../src/project/runtimeConfig';+import { QUICKGAME_DEFAULT_ICON } from '../src/export/quickgameDefaultIcon';+import { OFFICIAL_PACKAGES } from './officialPackagesDir';++let root: string;+const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-quickgame-'));+ mkdirSync(path.join(root, 'scenes'), { recursive: true });+ writeFileSync(path.join(root, 'scenes', 'main.esscene'), JSON.stringify({ version: '1.0', name: 'Main', entities: [] }));+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'),+ JSON.stringify({ uuid: SCN, version: '2.0', type: 'scene', importer: {} }));+ writeFileSync(path.join(root, 'my-icon.png'), 'MY ICON');+ mkdirSync(path.join(root, '_sdk', 'quickgame'), { recursive: true });+ writeFileSync(path.join(root, '_sdk', 'index.minigame.js'),+ 'export function initMiniGameRuntime(){return Promise.resolve();}\nexport function installMiniGamePlatform(){}\n');+ writeFileSync(path.join(root, '_sdk', 'quickgame', 'index.js'), 'export const quickgameProfile = { id: "quickgame" };\n');+ mkdirSync(path.join(root, '_wasm'), { recursive: true });+ writeFileSync(path.join(root, '_wasm', 'esengine.wxgame.js'), 'module.exports = function engine() {};');+ writeFileSync(path.join(root, '_wasm', 'esengine.wxgame.wasm'), 'wasm');+}, 60_000);++afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));++const run = (out: string, extra: Record<string, unknown> = {}) => exportGame({+ root, entryScene: 'scenes/main.esscene',+ hostsDir: path.resolve(__dirname, '../src/runtime'), packagesDir: OFFICIAL_PACKAGES,+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),+ outDir: path.join(root, out), title: 'My Game', platform: 'quickgame', orientation: 'portrait',+ runtime: runtimeConfigOf({ designResolution: { width: 720, height: 1280 } }),+ miniGameAppid: 'com.estella.test.minigame', appVersion: '1.4.0', miniGameVersionCode: 7,+ ...extra,+});++describe('exportGame (quickgame)', () => {+ it('writes the manifest the alliance reads and the package it installs', async () => {+ const res = await run('dist');+ expect(res.ok, res.errors.join('\n')).toBe(true);+ const out = path.join(root, 'dist');+ expect(JSON.parse(readFileSync(path.join(out, 'manifest.json'), 'utf8'))).toMatchObject({+ package: 'com.estella.test.minigame', name: 'My Game', icon: '/icon.png',+ versionName: '1.4.0', versionCode: 7, allianceVersion: 1300, type: 'game',+ orientation: 'portrait', deviceOrientation: 'portrait',+ });+ expect(res.packageFile).toBe(path.join(out, 'com.estella.test.minigame.rpk'));+ expect(readFileSync(res.packageFile!).includes(Buffer.from('RPK Sig Block 42'))).toBe(true);+ expect(res.warnings.join('\n')).toContain('public debug key');+ }, 180_000);++ it('carries Estella\'s mark when the project sets no icon, and the project\'s when it does', async () => {+ expect(readFileSync(path.join(root, 'dist', 'icon.png')).equals(Buffer.from(QUICKGAME_DEFAULT_ICON))).toBe(true);+ await run('dist-icon', { appIcon: 'my-icon.png' });+ expect(readFileSync(path.join(root, 'dist-icon', 'icon.png'), 'utf8')).toBe('MY ICON');+ }, 180_000);++ it('loads its files on a host that evaluates them with no module wrapper', () => {+ // The host's require: evaluate at global scope, return nothing.+ const out = path.join(root, 'dist');+ const booted: unknown[] = [];+ const sandbox: Record<string, unknown> = {+ qg: {},+ require: (p: string) => {+ const file = path.join(out, p.replace(/^\.\//, ''));+ const src = p.endsWith('game-bundle.js')+ ? 'module.exports = { boot: function (f) { globalThis.__booted.push(typeof f); return Promise.resolve(); } };'+ : readFileSync(file, 'utf8');+ runInNewContext(src, sandbox);+ },+ __booted: booted,+ console,+ Promise,+ };+ sandbox.globalThis = sandbox;+ runInNewContext(readFileSync(path.join(out, 'game.js'), 'utf8'), sandbox);+ expect(booted).toEqual(['function']);+ });++ it('refuses a package name the host will not take', async () => {+ await expect(run('dist-bad', { miniGameAppid: 'com.estella.test' })).rejects.toThrow('ends in ".minigame"');+ });++ it('runs on the engine build without SIMD, judged against the alliance\'s tightest caps', () => {+ expect(engineBuildFor('quickgame')).toBe('quickgame');+ expect(engineBuildFor('wechat')).toBe('minigame');+ expect(builtinSizeBudgets('quickgame').map((b) => [b.scope, b.maxBytes / (1024 * 1024)]))+ .toEqual([['initial', 4], ['total', 20]]);+ expect(existsSync(path.join(root, 'dist', 'project.config.json'))).toBe(false);+ });+});diff --git a/pipeline/tests/native-template.test.ts b/pipeline/tests/native-template.test.tsindex ea13f3a0a..3acd4ab39 100644--- a/pipeline/tests/native-template.test.ts+++ b/pipeline/tests/native-template.test.ts@@ -288,7 +288,7 @@ describe('downloading a template from a release', () => {});describe('the iOS row reports what is missing', () => {- const dirs = () => ({ web: path.join(scratch, 'web'), minigame: path.join(scratch, 'wx') });+ const dirs = () => ({ web: path.join(scratch, 'web'), minigame: path.join(scratch, 'wx'), quickgame: path.join(scratch, 'qg') });const iosRow = async () => (await listPlatforms(null, dirs(), VERSION, NO_TOOLCHAINS)).find((r) => r.id === 'ios')!;it('asks for the runtime template before anything about Xcode', async () => {diff --git a/pipeline/tests/platform-catalog.test.ts b/pipeline/tests/platform-catalog.test.tsindex 9c17b5f70..aa1bfc6e6 100644--- a/pipeline/tests/platform-catalog.test.ts+++ b/pipeline/tests/platform-catalog.test.ts@@ -27,7 +27,7 @@ let wxDir: string;* against it exactly, so the tests own both ends of that comparison. */const VERSION = '9.9.9';-const dirs = () => ({ web: webDir, minigame: wxDir });+const dirs = () => ({ web: webDir, minigame: wxDir, quickgame: path.join(wxDir, '..', 'qg') });/** The catalog with the machine facts this file owns. A machine with NEITHER* compiler is deliberate: a project that marks nothing `@compiled` must be@@ -206,7 +206,7 @@ describe('createProjectPlatform — scaffolding', () => {const loaded = await loadProjectPlatform(root, 'acme-play', dirs());expect(loaded!.profile.runtimeProfileModule).toBe(path.join(root, 'src', 'platforms', 'acme-play.runtime.ts'));expect(loaded!.defaultOut).toBe('dist-acme-play');- expect(loaded!.profile.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })[0].file)+ expect(loaded!.profile.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', versionCode: 1, icon: null, orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })[0].file).toBe('game.json');});@@ -272,7 +272,7 @@ describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {expect(ttEntry).not.toContain('wx');// And the project's own emitter is what runs for config.- expect(p.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' }))+ expect(p.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', versionCode: 1, icon: null, orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })).toEqual([{ file: 'game.json', content: '{"t":"T"}' }]);});diff --git a/pipeline/tests/rpk.test.ts b/pipeline/tests/rpk.test.tsnew file mode 100644index 000000000..f399f5b6f--- /dev/null+++ b/pipeline/tests/rpk.test.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The quick-game package, held to two things this repo did not write:+ *+ * - the vendor CLI's signer. RSA PKCS#1 v1.5 is deterministic, so signing+ * the same zip with the same key must give the same bytes; GOLDEN is the+ * SHA-256 @quick-game/cli 1.9.0 (lib/bundle.js signZip) produced for the+ * fixture below.+ * - the runtime's verifier: `verify` follows hapjs SignatureVerifier /+ * FileListSignatureVerifier, the code a device runs on install.+ */+import { describe, it, expect } from 'vitest';+import { createHash, createPublicKey, verify as verifySig, X509Certificate } from 'node:crypto';+import { inflateRawSync } from 'node:zlib';+import { orderRpkEntries, packRpk, signRpk, writeZip, crc32, type RpkEntry } from '../src/export/rpk';+import { RPK_DEBUG_KEY } from '../src/export/rpkDebugKey';++const GOLDEN = 'ea286e46259f3c8e41b2cb9d30814dd63a5886eaa81ae59fdda64a93530a764d';++function fixture(): RpkEntry[] {+ const big = Buffer.alloc(2 * 1024 * 1024 + 17);+ for (let i = 0; i < big.length; i++) big[i] = (i * 31 + 7) & 0xff;+ return [+ { name: 'assets/big.bin', data: big },+ { name: 'manifest.json', data: Buffer.from('{"package":"com.estella.test.minigame","icon":"/icon.png"}') },+ { name: 'icon.png', data: Buffer.from('not really a png') },+ { name: 'game.js', data: Buffer.from('require("./game-bundle.js");') },+ { name: 'game-bundle.js', data: Buffer.from('module.exports = {};') },+ ];+}++const sha256 = (b: Uint8Array): Buffer => createHash('sha256').update(b).digest();+const u32 = (n: number): Buffer => { const b = Buffer.alloc(4); b.writeUInt32LE(n); return b; };++/** The install-time check, after hapjs: magic and sizes, the signer's signature+ * over SignedData, the key matching the certificate, the content digest over+ * the three zip sections, and the per-file digest list. */+function verify(rpk: Buffer, entries: readonly RpkEntry[]): void {+ let eocd = -1;+ for (let o = rpk.length - 22; o >= 0; o--) if (rpk.readUInt32LE(o) === 0x06054b50) { eocd = o; break; }+ const cd = rpk.readUInt32LE(eocd + 16);+ if (rpk.subarray(cd - 16, cd).toString('ascii') !== 'RPK Sig Block 42') throw new Error('magic');+ const size = Number(rpk.readBigUInt64LE(cd - 24));+ const blockOff = cd - (size + 8);+ if (Number(rpk.readBigUInt64LE(blockOff)) !== size) throw new Error('block size');+ const pairs = new Map<number, Buffer>();+ for (let p = blockOff + 8; p < cd - 24;) {+ const len = Number(rpk.readBigUInt64LE(p));+ pairs.set(rpk.readUInt32LE(p + 8), rpk.subarray(p + 12, p + 8 + len));+ p += 8 + len;+ }+ const rd = (b: Buffer, o: number): [Buffer, number] => { const n = b.readUInt32LE(o); return [b.subarray(o + 4, o + 4 + n), o + 4 + n]; };+ const [signers] = rd(pairs.get(0x01000101)!, 0);+ const [signer] = rd(signers, 0);+ const [signedData, o1] = rd(signer, 0);+ const [sigs, o2] = rd(signer, o1);+ const [pub] = rd(signer, o2);+ const [sigRec] = rd(sigs, 0);+ const [sigBytes] = rd(sigRec, 4);+ const key = createPublicKey({ key: pub, format: 'der', type: 'spki' });+ if (sigRec.readUInt32LE(0) !== 0x0103 || !verifySig('sha256', signedData, key, sigBytes)) throw new Error('signer signature');+ const [digests, o3] = rd(signedData, 0);+ const [digestRec] = rd(digests, 0);+ const [expected] = rd(digestRec, 4);+ const [certs] = rd(signedData, o3);+ const [certDer] = rd(certs, 0);+ const certKey = new X509Certificate(certDer).publicKey.export({ type: 'spki', format: 'der' });+ if (!certKey.equals(pub)) throw new Error('key does not match certificate');+ const end = Buffer.from(rpk.subarray(eocd));+ end.writeUInt32LE(blockOff, 16);+ const sections = [rpk.subarray(0, blockOff), rpk.subarray(cd, eocd), end];+ const actual = sha256(Buffer.concat([Buffer.from([0x5a]), u32(3),+ ...sections.map((s) => sha256(Buffer.concat([Buffer.from([0xa5]), u32(s.length), s])))]));+ if (!actual.equals(expected)) throw new Error('content digest');+ const [outer] = rd(pairs.get(0x01000201)!, 0);+ const [list, o4] = rd(outer, 0);+ const [listSig] = rd(outer, o4);+ const [listSigBytes] = rd(listSig, 4);+ if (!verifySig('sha256', list, key, listSigBytes)) throw new Error('file list signature');+ const byCrc = new Map<number, Buffer>();+ for (let q = 4; q < list.length;) {+ byCrc.set(list.readUInt32LE(q), list.subarray(q + 6, q + 6 + list.readUInt16LE(q + 4)));+ q += 6 + list.readUInt16LE(q + 4);+ }+ for (const e of entries) {+ if (!byCrc.get(crc32(Buffer.from(e.name, 'utf8')))?.equals(sha256(e.data))) throw new Error(`file digest ${e.name}`);+ }+}++/** Every entry, read back through the local headers the way an unzip does. */+function unzip(rpk: Buffer): Map<string, Buffer> {+ const out = new Map<string, Buffer>();+ for (let o = 0; rpk.readUInt32LE(o) === 0x04034b50;) {+ const size = rpk.readUInt32LE(o + 18);+ const nameLen = rpk.readUInt16LE(o + 26);+ const name = rpk.toString('ascii', o + 30, o + 30 + nameLen);+ const start = o + 30 + nameLen + rpk.readUInt16LE(o + 28);+ out.set(name, inflateRawSync(rpk.subarray(start, start + size)));+ o = start + size;+ }+ return out;+}++describe('the quick-game package', () => {+ it('signs byte for byte as the vendor CLI does', () => {+ const entries = orderRpkEntries(fixture(), 'icon.png');+ const rpk = signRpk(writeZip(entries), entries, RPK_DEBUG_KEY);+ expect(createHash('sha256').update(rpk).digest('hex')).toBe(GOLDEN);+ });++ it('passes the check a device runs on install, and fails it once a byte changes', () => {+ const entries = fixture();+ const rpk = packRpk(entries, 'icon.png', RPK_DEBUG_KEY);+ expect(() => verify(rpk, entries)).not.toThrow();+ const tampered = Buffer.from(rpk);+ tampered[100] ^= 0xff;+ expect(() => verify(tampered, entries)).toThrow('content digest');+ });++ it('is an ordinary zip underneath, every file intact', () => {+ const entries = fixture();+ const files = unzip(packRpk(entries, 'icon.png', RPK_DEBUG_KEY));+ for (const e of entries) expect(files.get(e.name)?.equals(Buffer.from(e.data))).toBe(true);+ });++ it('puts the entry script first and the manifest before the assets, as the engine streams it', () => {+ const names = [...unzip(packRpk(fixture(), 'icon.png', RPK_DEBUG_KEY)).keys()];+ expect(names).toEqual(['game.js', 'game-bundle.js', 'manifest.json', 'icon.png', 'assets/big.bin']);+ });++ it('refuses a name the runtime and the vendor tools would key differently', () => {+ expect(() => writeZip([{ name: 'assets/精灵.png', data: new Uint8Array(1) }])).toThrow('not ASCII');+ });+});diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 57cf644c2..720168a3d 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -5140,6 +5140,7 @@ id: MiniGameVendorinstantiateWasm: ((pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>) | undefinedpay: { can(): boolean; request(request: PlatformPaymentRequest): Promise<void>; } | undefinedrecordingLimits: { readonly minSeconds: number; readonly maxSeconds: number; } | undefined+windowInPhysicalPixels: boolean | undefined```## MiniGameRequestOptions — interface @experimental@@ -5231,7 +5232,7 @@ changedTouches: MiniGameTouch[]## MiniGameVendor — type @experimental```-'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | (string & {})+'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | (string & {})```## MissingAssetCallback — type @experimentaldiff --git a/sdk/package.json b/sdk/package.jsonindex 18331e7ca..b66fa5b69 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -25,6 +25,7 @@"./dist/douyin/index.js","./dist/kuaishou/index.js","./dist/bilibili/index.js",+ "./dist/quickgame/index.js","./dist/index.wechat.cjs.js"],"main": "./dist/index.js",@@ -100,6 +101,10 @@"./bilibili": {"import": "./dist/bilibili/index.js","types": "./dist/bilibili/index.d.ts"+ },+ "./quickgame": {+ "import": "./dist/quickgame/index.js",+ "types": "./dist/quickgame/index.d.ts"}},"files": [diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex 9e400ba14..e98b6c939 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -104,6 +104,7 @@ export default defineConfig(['douyin/index': 'src/platform/douyin/index.ts','kuaishou/index': 'src/platform/kuaishou/index.ts','bilibili/index': 'src/platform/bilibili/index.ts',+ 'quickgame/index': 'src/platform/quickgame/index.ts','wasm': 'src/wasm.ts',},// Only the node entry reaches these; a browser entry that did would faildiff --git a/sdk/rollup.config.js b/sdk/rollup.config.jsindex d25b7c8a7..433eeea80 100644--- a/sdk/rollup.config.js+++ b/sdk/rollup.config.js@@ -19,6 +19,7 @@ export default ['douyin/index': 'src/platform/douyin/index.ts','kuaishou/index': 'src/platform/kuaishou/index.ts','bilibili/index': 'src/platform/bilibili/index.ts',+ 'quickgame/index': 'src/platform/quickgame/index.ts','spine/index': 'src/spine/index.ts','tilemap/index': 'src/tilemap/index.ts','logic/index': 'src/logic/index.ts',diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex 5434fd98b..412cad96c 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -417,7 +417,7 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {canvas: MiniGameCanvas,size: { windowWidth?: number; windowHeight?: number },): void {- const dpr = this.g_.getSystemInfoSync().pixelRatio ?? 1;+ const dpr = this.profile_.windowInPhysicalPixels ? 1 : (this.g_.getSystemInfoSync().pixelRatio ?? 1);if (size.windowWidth) canvas.width = size.windowWidth * dpr;if (size.windowHeight) canvas.height = size.windowHeight * dpr;}diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.tsindex 4b5e69380..226a9d031 100644--- a/sdk/src/platform/minigame/api.ts+++ b/sdk/src/platform/minigame/api.ts@@ -387,7 +387,7 @@ export interface MiniGameGlobal {* never heard of and get the whole family for it. Nothing in the SDK branches on* this value — it is identity (adapter name, diagnostics, logs), not behavior.*/-export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | (string & {});+export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | (string & {});/*** A vendor described as DATA — three facts and, at most, one method.@@ -433,6 +433,11 @@ export interface MiniGameProfile {request(request: PlatformPaymentRequest): Promise<void>;};+ /** The host reports `windowWidth`/`windowHeight` in physical pixels rather+ * than WeChat's logical ones (vivo: 2340 wide beside a pixelRatio of 2.75), so+ * multiplying by pixelRatio again would size the screen past the GPU's limit. */+ windowInPhysicalPixels?: boolean;+/** The recording length this vendor accepts, when its recorder's shape is* another vendor's but its limits are not. */recordingLimits?: { readonly minSeconds: number; readonly maxSeconds: number };diff --git a/sdk/src/platform/quickgame/index.ts b/sdk/src/platform/quickgame/index.tsnew file mode 100644index 000000000..c9b28b549--- /dev/null+++ b/sdk/src/platform/quickgame/index.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.ts+ * @brief 快游戏联盟 MiniGame platform (a profile of the mini-game family).+ *+ * Adapter, polyfills and install are the family's; the quick-game hosts add nothing, which is+ * the point of the family existing.+ */+import { MiniGamePlatformAdapter, installMiniGamePlatform } from '../minigame';+import { quickgameProfile } from './profile';++export const quickgameAdapter = new MiniGamePlatformAdapter(quickgameProfile);++let initialized = false;++/** Initialize the quick-game platform. */+export function initQuickGamePlatform(): void {+ if (initialized) return;+ initialized = true;+ installMiniGamePlatform(quickgameProfile, quickgameAdapter);+}++export { quickgameProfile };diff --git a/sdk/src/platform/quickgame/profile.ts b/sdk/src/platform/quickgame/profile.tsnew file mode 100644index 000000000..587518a15--- /dev/null+++ b/sdk/src/platform/quickgame/profile.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file profile.ts+ * @brief The 快游戏联盟 hosts (vivo, OPPO, Xiaomi, Honor) as a profile of the+ * mini-game family.+ *+ * `qg` is WeChat-shaped for what the family reads. What differs, each measured on+ * vivo's engine (1203) in an emulator:+ *+ * - `windowWidth`/`windowHeight` are physical pixels (2340 beside a pixelRatio of+ * 2.75), so the screen is sized without multiplying again.+ * - `WebAssembly` is exposed by `qg.setWasmTaskCompile(true)` (OPPO documents+ * it: 「开启 wasm 开关,会全局暴露`WebAssembly`变量」); it is called before the+ * engine instantiates.+ *+ * The engine binary itself differs too (no SIMD, no BigInt i64 — V8 8.3); that is+ * the export's `quickgame` build, not something a profile can choose.+ *+ * UNVERIFIED: OPPO, Xiaomi and Honor on a device. OPPO grants WebGL2 only to a+ * game that applied for it.+ */+import type { MiniGameGlobal, MiniGameProfile } from '../minigame';+import type { WasmInstantiateResult } from '../types';++declare const qg: unknown;++interface QuickGameGlobal {+ setWasmTaskCompile?(on: boolean): void;+ getFileSystemManager(): { readFileSync(path: string): ArrayBuffer };+}++export const quickgameProfile: MiniGameProfile = {+ id: 'quickgame',+ hostLabel: '快游戏',++ get global(): MiniGameGlobal {+ return qg as MiniGameGlobal;+ },++ windowInPhysicalPixels: true,++ async instantiateWasm(pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports): Promise<WasmInstantiateResult> {+ const host = qg as QuickGameGlobal;+ host.setWasmTaskCompile?.(true);+ const bytes = typeof pathOrBuffer === 'string'+ ? host.getFileSystemManager().readFileSync(pathOrBuffer)+ : pathOrBuffer;+ return WebAssembly.instantiate(bytes, imports) as Promise<WasmInstantiateResult>;+ },+};diff --git a/sdk/tests/quickgame-profile.test.ts b/sdk/tests/quickgame-profile.test.tsnew file mode 100644index 000000000..91754c9b2--- /dev/null+++ b/sdk/tests/quickgame-profile.test.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What the quick-game hosts needed that no other vendor did, each found+ * by running a package on vivo's engine: a window measured in physical+ * pixels, WebAssembly behind a switch, and a WebGL2 context that offers+ * an extension WebGL2 does not have.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';+import type { MiniGameGlobal, MiniGameProfile } from '../src/platform/minigame/api';+import { quickgameProfile } from '../src/platform/quickgame/profile';+import { hideCoreExtensions } from '../src/runtime/miniGameRuntime';++const EMPTY_WASM = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]).buffer;++afterEach(() => { delete (globalThis as { qg?: unknown }).qg; });++describe('the quick-game hosts', () => {+ it('size the screen from a window already in physical pixels', () => {+ const host = (): MiniGameGlobal => ({+ createCanvas: () => ({ width: 0, height: 0 }),+ getSystemInfoSync: () => ({ windowWidth: 2340, windowHeight: 1080, pixelRatio: 2.75 }),+ } as unknown as MiniGameGlobal);+ const screen = (over: Partial<MiniGameProfile>) =>+ new MiniGamePlatformAdapter({ id: 'x', hostLabel: 'x', global: host(), ...over } as MiniGameProfile).createScreenCanvas();+ expect(screen({ windowInPhysicalPixels: true })).toMatchObject({ width: 2340, height: 1080 });+ expect(screen({})).toMatchObject({ width: 6435, height: 2970 });+ });++ it('turn WebAssembly on before the engine is instantiated', async () => {+ const order: string[] = [];+ (globalThis as { qg?: unknown }).qg = {+ setWasmTaskCompile: (on: boolean) => order.push(`switch ${on}`),+ getFileSystemManager: () => ({ readFileSync: (p: string) => { order.push(`read ${p}`); return EMPTY_WASM; } }),+ };+ const res = await quickgameProfile.instantiateWasm!('wasm/esengine.wxgame.wasm', {});+ expect(order).toEqual(['switch true', 'read wasm/esengine.wxgame.wasm']);+ expect(res.instance).toBeInstanceOf(WebAssembly.Instance);+ });++ it('withhold from a WebGL2 context the WebGL1 extensions it made core', () => {+ const vao = { createVertexArrayOES: vi.fn() };+ const other = {};+ const gl = { getExtension: (name: string) => (name === 'OES_vertex_array_object' ? vao : other) };+ hideCoreExtensions(gl as unknown as WebGLRenderingContext);+ expect(gl.getExtension('OES_vertex_array_object')).toBeNull();+ expect(gl.getExtension('ANGLE_instanced_arrays')).toBeNull();+ expect(gl.getExtension('EXT_color_buffer_float')).toBe(other);+ });+});diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex 3429c7769..d1b0d7c58 100644--- a/tools/goldenProjects.mjs+++ b/tools/goldenProjects.mjs@@ -26,7 +26,7 @@ const EXAMPLES = path.join(ROOT, 'examples');export const TIERS = ['pr', 'nightly', 'release'];/** Export targets a golden project can be asked to package + launch for. */-export const TARGETS = ['web', 'playable', 'desktop', 'wechat', 'douyin', 'kuaishou', 'bilibili', 'android', 'ios'];+export const TARGETS = ['web', 'playable', 'desktop', 'wechat', 'douyin', 'kuaishou', 'bilibili', 'quickgame', 'android', 'ios'];/*** How far a packaged frame may sit from the editor's frame of the same game.diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.jsindex d88add468..4d63110b6 100644--- a/tools/nativeScriptModules.js+++ b/tools/nativeScriptModules.js@@ -102,6 +102,10 @@ export const MODULES = {disposition: 'forbidden-native-script',why: "Bilibili's platform profile — it names a host global (`bl`) that a native build does not have",},+ 'esengine/quickgame': {+ disposition: 'forbidden-native-script',+ why: "the quick-game platform profile — it names a host global (`qg`) that a native build does not have",+ },};/** The `exports` subpath ("." / "./physics3d") a specifier corresponds to. */diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 69400ef31..489f298d5 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -996,6 +996,12 @@ export const NOTED = {{ note: 'A mini-game that fails to start says why.' },'fix(cli): a project platform exports headless, and an unknown id is refused':{ note: '`estella export --platform <id>` packages a platform the project defines' },+ 'feat(export): a project can be packaged as a quick game':+ { note: 'A project can be packaged as a quick game' },+ 'feat(editor): the quick game is a build target, with its package name, version code and release key':+ { note: 'A project can be packaged as a quick game' },+ 'fix(runtime): a WebGL2 context does not offer the WebGL1 extensions it made core':+ { note: 'A mini-game whose host\'s WebGL2 context also offers `OES_vertex_array_object` renders instead of hanging' },'fix(agent): the history toggle presses grey again, not the accent':{ note: "The agent drawer's History button shows it is open with a grey press again, not the accent colour 0.71 gave it." },};