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 for Bilibili
esengine21bdc95f5931
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 94568309f..3ea0dfd5b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Added+- **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.- **The `record-share` example.** Record a run, mark a highlight every few seconds, stop, and share the clip; the share button hides where the host cannot share, which is what a real game wants too.- **`tsc` and an outside editor type-check the official packages too.** Opening a project mirrors the packages the editor ships into `.esengine/packages/`, beside the SDK's types, and a tsconfig maps them with `"estella-plugin-*": ["./.esengine/packages/*"]` — the `wechat-minigame` template and the examples that use one already do.diff --git a/desktop b/desktopindex 2632e8d6f..957236f2b 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 2632e8d6f44db9b340896a2a1ee5f034412b6ed7+Subproject commit 957236f2b810e420372afe4d89894a68e88458f1diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.tsindex d5512bdd7..644c7ca14 100644--- a/pipeline/src/bundle/engineSubpaths.ts+++ b/pipeline/src/bundle/engineSubpaths.ts@@ -21,6 +21,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {'esengine/physics3d': 'physics3d/index.js','esengine/douyin': 'douyin/index.js','esengine/kuaishou': 'kuaishou/index.js',+ 'esengine/bilibili': 'bilibili/index.js','esengine/wasm': 'wasm.js',};@@ -29,7 +30,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']);+export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili']);/** 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 375eaf658..abfe0739a 100644--- a/pipeline/src/bundle/runtimeHosts.ts+++ b/pipeline/src/bundle/runtimeHosts.ts@@ -17,6 +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',] as const;export type RuntimeHost = (typeof RUNTIME_HOSTS)[number];diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex b7e86d220..08597c272 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 } from './miniGameExportProfile';+import { wechatExportProfile, douyinExportProfile, kuaishouExportProfile, bilibiliExportProfile } from './miniGameExportProfile';import type { MiniGameExportProfile } from './miniGameExportProfile';/** The mini-game vendors the editor ships, by platform id. */@@ -44,6 +44,7 @@ const BUILTIN_MINIGAME_PROFILES: Readonly<Record<string, MiniGameExportProfile>>wechat: wechatExportProfile,douyin: douyinExportProfile,kuaishou: kuaishouExportProfile,+ bilibili: bilibiliExportProfile,};import { exportPlayable } from './exportPlayable';import { genericPlayableProfile, type PlayableAdProfile } from './playableAdProfile';@@ -678,6 +679,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>packagesDir: opts.packagesDir,title,appid: opts.miniGameAppid,+ appVersion: opts.appVersion,features: opts.features,modulesByPlatform: opts.modulesByPlatform,orientation,@@ -713,6 +715,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>packagesDir: opts.packagesDir,title,appid: opts.miniGameAppid,+ appVersion: opts.appVersion,features: opts.features,modulesByPlatform: opts.modulesByPlatform,orientation,diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex b06b52e60..0a7f17464 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -261,6 +261,8 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {title?: string;/** MiniGame appid (Project Settings) → project config. */appid?: string;+ /** The project's version (ProjectManifest.version), for a host config that asks. */+ appVersion?: string;/** Screen orientation (Project Settings) → game.json. */orientation?: 'portrait' | 'landscape';/** The project's runtime settings, derived once by `runtimeConfigOf`; the@@ -627,6 +629,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {const configFiles = profile.emitConfigFiles({title,appid: opts.appid ?? '',+ version: opts.appVersion ?? '1.0.0',orientation: opts.orientation ?? 'portrait',subPackages: subPackages.subPackages,includeSuffixes: packIncludeSuffixes(cookEntries, profile.nativeSuffixes),diff --git a/pipeline/src/export/miniGameExportProfile.ts b/pipeline/src/export/miniGameExportProfile.tsindex 0ef8d6718..e685b18cf 100644--- a/pipeline/src/export/miniGameExportProfile.ts+++ b/pipeline/src/export/miniGameExportProfile.ts@@ -22,12 +22,14 @@ 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' | (string & {});+export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | (string & {});/** Vendor-neutral facts the pipeline computes, handed to the config emitter. */export interface MiniGameConfigContext {title: string;appid: string;+ /** The project's version, for a host whose config asks for one. */+ version: string;orientation: 'portrait' | 'landscape';/** Lazy groups present in the cook, as vendor subpackage roots. */subPackages: ReadonlyArray<{ name: string; root: string }>;@@ -174,7 +176,7 @@ export interface MiniGameExportProfile {/** Engine glue filenames to look for in wasmDir, in preference order. */readonly engineGlueCandidates: readonly string[];/** esbuild target for the game bundle + glue down-level (real-device syntax floor). */- readonly esTarget: 'es2017' | 'es2019' | 'es2020';+ readonly esTarget: 'es2016' | 'es2017' | 'es2019' | 'es2020';/** Build-target name woven into "runtime not found" errors (`build -t <hint>`). */readonly wasmBuildHint: string;/** side-module id → the `build -t <target>` that produces it for THIS vendor.@@ -438,3 +440,63 @@ export const kuaishouExportProfile: MiniGameExportProfile = {emitEntry: defaultMiniGameEntry,};++// =============================================================================+// Bilibili profile+// =============================================================================++/** The upload whitelist, from the page's own `whiteList` array+ * (miniapp.bilibili.com/small-game-doc/framework/structure). */+const BILIBILI_PACKER_SUFFIXES: ReadonlySet<string> = new Set(`png jpg jpeg gif svg js json cer obj dae fbx mtl stl 3ds mp3 pvr wav plist ttf fnt gz ccz m4a+ mp4 bmp atlas swf ani part proto bin sk mipmaps txt zip ogg silk dbbin dbmv etc lmat lm ls lh+ lani lav lsani ltc csv scene prefab lml lmani ktx dds xml wasm exml xtt fui webp`.split(/\s+/).filter(Boolean));++/**+ * Bilibili (B 站), from miniapp.bilibili.com/small-game-doc: `game.json` carries the+ * appid and version and spells `subpackages` lower-case. WebGL2 exists only in+ * high-performance mode (「仅在高性能模式下,支持运行 WebGL2.0 小游戏」), so all+ * four switches are always on — the engine renders on nothing less.+ */+export const bilibiliExportProfile: MiniGameExportProfile = {+ id: 'bilibili',+ sdkEntryFile: 'index.minigame.js',+ runtimeInit: 'initMiniGameRuntime',+ runtimeProfileHost: 'bilibiliPlatformProfile',+ engineGlueCandidates: MINIGAME_ENGINE_GLUE,+ // 「如果开发使用了 ES7 语法,特别是 async/await 的写法,必须在 game.js 开头引入+ // [regenerator]」: async/await is lowered to generators rather than trusted.+ esTarget: 'es2016',+ wasmBuildHint: MINIGAME_ENGINE_BUILD,+ hostGlobal: 'bl',+ sideModuleBuildTargets: {},+ // 「*.json、game.json 会经过编译」 — and `require` takes no .json at all.+ nativeSuffixes: new Set(['.js', '.json']),+ // miniapp.bilibili.com/small-game-doc/framework/structure, 「只有后缀名在白名单内的文件可以被上传」.+ packerSuffixes: BILIBILI_PACKER_SUFFIXES,+ // 「平台暂不支持Wasm Brotli压缩」 (the Cocos build note).+ wasmBrotli: false,+ subpackageDir: 'subpackages',+ // WeChat's rule, assumed here: the docs name loadSubpackage but not what a+ // root must hold, and a root without game.js is refused on WeChat.+ subpackageEntry: 'game.js',++ emitConfigFiles(ctx) {+ const gameCfg: Record<string, unknown> = {+ version: ctx.version,+ appId: ctx.appid,+ deviceOrientation: ctx.orientation,+ showStatusBar: false,+ iOSHighPerformance: true,+ 'iOSHighPerformance+': true,+ androidHighPerformance: true,+ 'androidHighPerformance+': true,+ };+ if (ctx.hasOpenData) gameCfg.openDataContext = ctx.openDataRoot;+ if (ctx.subPackages.length > 0) {+ gameCfg.subpackages = ctx.subPackages.map((s) => ({ name: s.name, root: s.root }));+ }+ return [{ file: 'game.json', content: JSON.stringify(gameCfg, null, 2) + '\n' }];+ },++ emitEntry: defaultMiniGameEntry,+};diff --git a/pipeline/src/export/platformCatalog.ts b/pipeline/src/export/platformCatalog.tsindex 6e927e079..45be1ef88 100644--- a/pipeline/src/export/platformCatalog.ts+++ b/pipeline/src/export/platformCatalog.ts@@ -121,6 +121,7 @@ function builtinReadiness(case 'wechat':case 'douyin':case 'kuaishou':+ case 'bilibili':// One probe for the family: they run the same engine build, so a machine// ready for one is ready for the other — and answering otherwise offers a// build command that produces a file the target already has.diff --git a/pipeline/src/export/sizeReport.ts b/pipeline/src/export/sizeReport.tsindex 164df2dad..745afaa83 100644--- a/pipeline/src/export/sizeReport.ts+++ b/pipeline/src/export/sizeReport.ts@@ -96,6 +96,8 @@ export interface BuildSizeReport {deliverableBytes?: number;/** That file's name, so the UI can say what was weighed. */deliverableName?: string;+ /** The heaviest subpackage (`subpackages/<name>`), when the build has any. */+ largestSubpackage?: { root: string; bytes: number };/** Largest first, capped at {@link LARGEST_FILES}. */largest: BuildSizeEntry[];/** Package composition (initial + lazy), largest kind first. Excludes remote:@@ -316,6 +318,12 @@ export function summarizeEntries(}const packageBytes = initialBytes + lazyBytes;+ const bySubpackage = new Map<string, number>();+ for (const file of entries) {+ if (file.bucket !== 'lazy') continue;+ const root = file.path.split('/').slice(0, 2).join('/');+ bySubpackage.set(root, (bySubpackage.get(root) ?? 0) + file.bytes);+ }const report: BuildSizeReport = {initialBytes, lazyBytes, remoteBytes, packageBytes, totalBytes,fileCount: entries.length,@@ -323,6 +331,9 @@ export function summarizeEntries(byKind: [...kinds.values()].sort((a, b) => b.bytes - a.bytes),verdicts: [],};+ for (const [root, bytes] of bySubpackage) {+ if (!report.largestSubpackage || bytes > report.largestSubpackage.bytes) report.largestSubpackage = { root, bytes };+ }if (opts.deliverableBytes != null) {report.deliverableBytes = opts.deliverableBytes;if (opts.deliverableName) report.deliverableName = opts.deliverableName;@@ -354,7 +365,8 @@ function judge(report: BuildSizeReport, budgets: readonly SizeBudget[]): SizeVerfor (const budget of budgets) {const measured = budget.scope === 'initial' ? report.initialBytes: budget.scope === 'total' ? report.packageBytes- : report.deliverableBytes;+ : budget.scope === 'eachSubpackage' ? report.largestSubpackage?.bytes+ : report.deliverableBytes;if (measured == null) continue;verdicts.push(evaluateSizeBudget(measured, budget));}diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.tsindex ce695686a..89b2f1895 100644--- a/pipeline/src/project/format.ts+++ b/pipeline/src/project/format.ts@@ -382,6 +382,7 @@ export interface ProjectPackaging {platforms?: {wechat?: MiniGamePackaging;douyin?: MiniGamePackaging;+ bilibili?: MiniGamePackaging;desktop?: DesktopPackaging;android?: AndroidPackaging;ios?: IosPackaging;@@ -813,9 +814,9 @@ export function parseManifest(raw: unknown): ProjectManifest {if (!orientation && (wx.orientation === 'portrait' || wx.orientation === 'landscape')) orientation = wx.orientation;if (Object.keys(w).length > 0) platforms.wechat = w;}- const tt = pl.douyin as Record<string, unknown> | undefined;- if (tt && typeof tt === 'object' && typeof tt.appid === 'string') {- platforms.douyin = { appid: tt.appid };+ for (const vendor of ['douyin', 'bilibili'] as const) {+ const v = pl[vendor] as Record<string, unknown> | undefined;+ if (v && typeof v === 'object' && typeof v.appid === 'string') platforms[vendor] = { appid: v.appid };}const dt = pl.desktop as Record<string, unknown> | undefined;if (dt && typeof dt === 'object') {diff --git a/pipeline/src/project/platforms.ts b/pipeline/src/project/platforms.tsindex 37118cb20..b7c66a2b8 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' | 'playable' | 'android' | 'ios';+export type BuiltinPlatform = 'web' | 'desktop' | 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'playable' | 'android' | 'ios';/** Built-ins, in the order they are offered. */export const BUILTIN_PLATFORMS: readonly BuiltinPlatform[] = [- 'web', 'desktop', 'wechat', 'douyin', 'kuaishou', 'playable', 'android', 'ios',+ 'web', 'desktop', 'wechat', 'douyin', 'kuaishou', 'bilibili', 'playable', 'android', 'ios',];/**@@ -63,7 +63,7 @@ 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'] as const;+export const MINIGAME_PLATFORMS = ['wechat', 'douyin', 'kuaishou', 'bilibili'] as const;export type MiniGamePlatform = (typeof MINIGAME_PLATFORMS)[number];export function isMiniGamePlatform(platform: ExportPlatform): platform is MiniGamePlatform {diff --git a/pipeline/src/project/serviceSupport.ts b/pipeline/src/project/serviceSupport.tsindex f11c24d54..44d46edb9 100644--- a/pipeline/src/project/serviceSupport.ts+++ b/pipeline/src/project/serviceSupport.ts@@ -175,6 +175,34 @@ const KUAISHOU_SERVICES: readonly ServiceStatus[] = [{ service: 'achievements', support: 'no', note: ACHIEVEMENTS_LOCAL_ONLY },];+/** From miniapp.bilibili.com/small-game-doc; nothing here has run on a device yet. */+const BILIBILI_SERVICES: readonly ServiceStatus[] = [+ {+ service: 'ads',+ support: 'unknown',+ note: 'bl.createRewardedVideoAd is documented (onClose carries isEnded); no interstitial is —'+ + ' 「当前支持激励视频广告」 — so showInterstitial has no unit to show. Unverified on a device.',+ },+ {+ service: 'share',+ support: 'unknown',+ note: 'bl.shareAppMessage and the passive bl.onShareAppMessage are documented; imageUrl must be on'+ + ' Bilibili\'s own image server (「暂不支持非 bilibili 图片服务器资源地址」). Unverified on a device.',+ },+ {+ service: 'signIn',+ support: 'unknown',+ note: 'bl.login yields a code your server exchanges at Bilibili\'s jscode2session; unverified on a device.',+ },+ {+ service: 'purchase',+ support: 'no',+ note: 'Bilibili sells through bl.requestRecharge, which takes an order your server creates —'+ + ' 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'? {@@ -197,6 +225,7 @@ export function builtinServiceSupport(platform: ExportPlatform): readonly Servicif (platform === 'wechat') return WECHAT_SERVICES;if (platform === 'douyin') return DOUYIN_SERVICES;if (platform === 'kuaishou') return KUAISHOU_SERVICES;+ if (platform === 'bilibili') return BILIBILI_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 b32ab81ef..fc0f0d02e 100644--- a/pipeline/src/project/sizeBudget.ts+++ b/pipeline/src/project/sizeBudget.ts@@ -45,7 +45,9 @@ export type BudgetScope =| 'total'/** The single file that gets uploaded: an ad network's index.html or archive,* a store's .apk. */- | 'deliverable';+ | 'deliverable'+ /** The largest one subpackage, for a host that caps each on its own. */+ | 'eachSubpackage';/** One limit a target imposes. */export interface SizeBudget {@@ -76,6 +78,7 @@ export function builtinSizeBudgets(platform: ExportPlatform): readonly SizeBudgeif (platform === 'wechat') return WECHAT_BUDGETS;if (platform === 'douyin') return DOUYIN_BUDGETS;if (platform === 'kuaishou') return KUAISHOU_BUDGETS;+ if (platform === 'bilibili') return BILIBILI_BUDGETS;return NO_BUDGETS;}@@ -105,6 +108,16 @@ const KUAISHOU_BUDGETS: readonly SizeBudget[] = [{ scope: 'total', maxBytes: 30 * MB, note: 'Kuaishou caps a mini-game at 30MB across the main package and all subpackages' },];+/**+ * 「单个分包/主包大小不能超过 4M」「整个小游戏所有分包大小不超过 30M」+ * https://miniapp.bilibili.com/small-game-doc/ability/subpackage+ */+const BILIBILI_BUDGETS: readonly SizeBudget[] = [+ { scope: 'initial', maxBytes: 4 * MB, note: "Bilibili caps a mini-game's main package at 4MB (单个分包/主包大小不能超过 4M)" },+ { scope: 'eachSubpackage', maxBytes: 4 * MB, note: 'Bilibili caps every subpackage at 4MB as well (单个分包/主包大小不能超过 4M)' },+ { scope: 'total', maxBytes: 30 * MB, note: 'Bilibili caps a mini-game at 30MB across the main package and all subpackages' },+];+const NO_BUDGETS: readonly SizeBudget[] = [];/**diff --git a/pipeline/src/runtime/bilibiliPlatformProfile.ts b/pipeline/src/runtime/bilibiliPlatformProfile.tsnew file mode 100644index 000000000..c070a3f11--- /dev/null+++ b/pipeline/src/runtime/bilibiliPlatformProfile.ts@@ -0,0 +1,9 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file bilibiliPlatformProfile.ts — the module a Bilibili package installs its+ * platform from, as the export profile's `runtimeProfileModule`.+ */+import { bilibiliProfile } from 'esengine/bilibili';++export default bilibiliProfile;diff --git a/pipeline/tests/export-bilibili.test.ts b/pipeline/tests/export-bilibili.test.tsnew file mode 100644index 000000000..f6bfca319--- /dev/null+++ b/pipeline/tests/export-bilibili.test.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Bilibili MiniGame export. What is Bilibili's own: `game.json` carries the+ * appid and version, spells `subpackages` lower-case and turns on all four+ * high-performance switches (WebGL2 exists nowhere else there); async is+ * lowered; and every subpackage is capped at 4MB on its own.+ */+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 { exportGame } from '../src/export/exportGame';+import { bilibiliExportProfile } from '../src/export/miniGameExportProfile';+import { builtinSizeBudgets } from '../src/project/sizeBudget';+import { runtimeConfigOf } from '../src/project/runtimeConfig';+import { OFFICIAL_PACKAGES } from './officialPackagesDir';++let root: string;+let out: string;+const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-bilibili-'));+ 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: {} }));+ mkdirSync(path.join(root, 'src'), { recursive: true });+ writeFileSync(path.join(root, 'src', 'main.ts'), 'async function later(): Promise<number> { await null; return 1; }\nlater().then((n) => console.log(n));\n');+ mkdirSync(path.join(root, '_sdk', 'bilibili'), { recursive: true });+ writeFileSync(path.join(root, '_sdk', 'index.minigame.js'),+ 'export function initMiniGameRuntime(){return Promise.resolve();}\n'+ + 'export function installMiniGamePlatform(){}\n');+ writeFileSync(path.join(root, '_sdk', 'bilibili', 'index.js'), 'export const bilibiliProfile = { id: "bilibili" };\n');+ mkdirSync(path.join(root, '_wasm'), { recursive: true });+ writeFileSync(path.join(root, '_wasm', 'esengine.wxgame.js'), 'module.exports = () => Promise.resolve({});');+ writeFileSync(path.join(root, '_wasm', 'esengine.wxgame.wasm'), 'wasmbytes');+ out = path.join(root, 'dist-bilibili');+}, 60_000);++afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));++describe('exportGame (bilibili)', () => {+ it('writes the appid, the version and the high-performance switches into game.json', async () => {+ const res = await exportGame({+ root,+ entryScene: 'scenes/main.esscene',+ scriptsEntry: 'src/main.ts',+ hostsDir: path.resolve(__dirname, '../src/runtime'), packagesDir: OFFICIAL_PACKAGES,+ sdkDistDir: path.join(root, '_sdk'),+ wasmDir: path.join(root, '_wasm'),+ outDir: out,+ title: 'My Game',+ platform: 'bilibili',+ orientation: 'landscape',+ runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),+ miniGameAppid: 'biligame0123456789',+ appVersion: '1.2.3',+ });+ expect(res.ok, res.errors.join('\n')).toBe(true);+ expect(JSON.parse(readFileSync(path.join(out, 'game.json'), 'utf8'))).toEqual({+ version: '1.2.3',+ appId: 'biligame0123456789',+ deviceOrientation: 'landscape',+ showStatusBar: false,+ iOSHighPerformance: true,+ 'iOSHighPerformance+': true,+ androidHighPerformance: true,+ 'androidHighPerformance+': true,+ });+ expect(existsSync(path.join(out, 'project.config.json'))).toBe(false);+ }, 180_000);++ it('lowers async/await, which Bilibili does not take as written', () => {+ const bundle = readFileSync(path.join(out, 'game-bundle.js'), 'utf8');+ // The project's own async function is in the bundle, as a generator.+ expect(bundle).toContain('later');+ expect(bundle).toContain('function*');+ expect(bundle).not.toMatch(/\basync function\b/);+ expect(bundle).toContain('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',+ subPackages: [{ name: 'level2', root: 'subpackages/level2/' }],+ includeSuffixes: [], hasOpenData: true, openDataRoot: 'open-data',+ });+ const json = JSON.parse(cfg.content);+ expect(json.subpackages).toEqual([{ name: 'level2', root: 'subpackages/level2/' }]);+ expect(json.openDataContext).toBe('open-data');+ });++ it('is judged per subpackage as well as on the main package and the total', () => {+ expect(builtinSizeBudgets('bilibili').map((b) => [b.scope, b.maxBytes / (1024 * 1024)]))+ .toEqual([['initial', 4], ['eachSubpackage', 4], ['total', 30]]);+ });+});diff --git a/pipeline/tests/export-kuaishou.test.ts b/pipeline/tests/export-kuaishou.test.tsindex 2586fb1f6..7a7b17649 100644--- a/pipeline/tests/export-kuaishou.test.ts+++ b/pipeline/tests/export-kuaishou.test.ts@@ -74,7 +74,7 @@ describe('exportGame (kuaishou)', () => {it('declares subpackages under the key Kuaishou reads', () => {const [cfg] = kuaishouExportProfile.emitConfigFiles({- title: 't', appid: '', orientation: 'landscape',+ title: 't', appid: '', version: '1.0.0', orientation: 'landscape',subPackages: [{ name: 'level2', root: 'subpackages/level2/' }],includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data',});diff --git a/pipeline/tests/platform-catalog.test.ts b/pipeline/tests/platform-catalog.test.tsindex 8c367f7c2..9c17b5f70 100644--- a/pipeline/tests/platform-catalog.test.ts+++ b/pipeline/tests/platform-catalog.test.ts@@ -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: '', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })[0].file)+ expect(loaded!.profile.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', 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: '', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' }))+ expect(p.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })).toEqual([{ file: 'game.json', content: '{"t":"T"}' }]);});diff --git a/pipeline/tests/size-report.test.ts b/pipeline/tests/size-report.test.tsindex 554847a26..676293afa 100644--- a/pipeline/tests/size-report.test.ts+++ b/pipeline/tests/size-report.test.ts@@ -467,3 +467,28 @@ describe('what the export packed', () => {.toBeUndefined();});});++describe('a cap on each subpackage', () => {+ const entry = (path: string, bytes: number, bucket: 'initial' | 'lazy') => ({ path, bytes, bucket, kind: 'other' as const });++ it('is judged on the heaviest one, not their sum', () => {+ const budget = { scope: 'eachSubpackage' as const, maxBytes: 4 * MB, note: 'each subpackage' };+ const report = summarizeEntries([+ entry('game-bundle.js', 1 * MB, 'initial'),+ entry('subpackages/a/one.bin', 3 * MB, 'lazy'),+ entry('subpackages/a/two.bin', 2 * MB, 'lazy'),+ entry('subpackages/b/three.bin', 3 * MB, 'lazy'),+ ], { budgets: [budget] });+ expect(report.largestSubpackage).toEqual({ root: 'subpackages/a', bytes: 5 * MB });+ expect(report.verdicts).toHaveLength(1);+ expect(report.verdicts[0]).toMatchObject({ measuredBytes: 5 * MB, status: 'over' });+ });++ it('says nothing about a build with no subpackages', () => {+ const report = summarizeEntries([entry('game-bundle.js', 9 * MB, 'initial')], {+ budgets: [{ scope: 'eachSubpackage', maxBytes: 4 * MB, note: 'each subpackage' }],+ });+ expect(report.largestSubpackage).toBeUndefined();+ expect(report.verdicts).toEqual([]);+ });+});diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 272214032..de0c35380 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -5227,7 +5227,7 @@ changedTouches: MiniGameTouch[]## MiniGameVendor — type @experimental```-'wechat' | 'douyin' | 'kuaishou' | (string & {})+'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | (string & {})```## MissingAssetCallback — type @experimentaldiff --git a/sdk/package.json b/sdk/package.jsonindex a3229699b..18331e7ca 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -24,6 +24,7 @@"./dist/physics3d/index.js","./dist/douyin/index.js","./dist/kuaishou/index.js",+ "./dist/bilibili/index.js","./dist/index.wechat.cjs.js"],"main": "./dist/index.js",@@ -95,6 +96,10 @@"./kuaishou": {"import": "./dist/kuaishou/index.js","types": "./dist/kuaishou/index.d.ts"+ },+ "./bilibili": {+ "import": "./dist/bilibili/index.js",+ "types": "./dist/bilibili/index.d.ts"}},"files": [diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex eaf8379e9..9e400ba14 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -103,6 +103,7 @@ export default defineConfig(['dragonbones/index': 'src/dragonbones/index.ts','douyin/index': 'src/platform/douyin/index.ts','kuaishou/index': 'src/platform/kuaishou/index.ts',+ 'bilibili/index': 'src/platform/bilibili/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 ece2637b8..d25b7c8a7 100644--- a/sdk/rollup.config.js+++ b/sdk/rollup.config.js@@ -18,6 +18,7 @@ export default ['physics3d/index': 'src/physics3d/index.ts','douyin/index': 'src/platform/douyin/index.ts','kuaishou/index': 'src/platform/kuaishou/index.ts',+ 'bilibili/index': 'src/platform/bilibili/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/bilibili/index.ts b/sdk/src/platform/bilibili/index.tsnew file mode 100644index 000000000..a90fd78ed--- /dev/null+++ b/sdk/src/platform/bilibili/index.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.ts+ * @brief Bilibili MiniGame platform (a profile of the mini-game family).+ *+ * Adapter, polyfills and install are the family's; Bilibili adds nothing, which is+ * the point of the family existing.+ */+import { MiniGamePlatformAdapter, installMiniGamePlatform } from '../minigame';+import { bilibiliProfile } from './profile';++export const bilibiliAdapter = new MiniGamePlatformAdapter(bilibiliProfile);++let initialized = false;++/** Initialize the Bilibili platform. */+export function initBilibiliPlatform(): void {+ if (initialized) return;+ initialized = true;+ installMiniGamePlatform(bilibiliProfile, bilibiliAdapter);+}++export { bilibiliProfile };diff --git a/sdk/src/platform/bilibili/profile.ts b/sdk/src/platform/bilibili/profile.tsnew file mode 100644index 000000000..6ef7f1acc--- /dev/null+++ b/sdk/src/platform/bilibili/profile.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file profile.ts+ * @brief Bilibili as a profile of the mini-game platform family.+ *+ * `bl` is WeChat-shaped (miniapp.bilibili.com/small-game-doc: 「bilibili 小游戏+ * runtime 与小游戏兼容」) and needs no override. Its recorder shares only through+ * a native button, which the engine does not draw, so `canShare` answers false.+ *+ * UNVERIFIED on a device: wasm on iOS (the upload list says 「wasm 仅支持+ * Android」, the config table recommends iOS high-performance mode for it), and+ * the standard `WebAssembly` loader — no page names one.+ *+ * NOT CLAIMED: `pay`. `bl.requestRecharge` takes an order your server creates.+ */+import type { MiniGameGlobal, MiniGameProfile } from '../minigame';++declare const bl: unknown;++export const bilibiliProfile: MiniGameProfile = {+ id: 'bilibili',+ hostLabel: '哔哩哔哩',++ get global(): MiniGameGlobal {+ return bl as MiniGameGlobal;+ },+};diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.tsindex 110a49ef6..70a067c27 100644--- a/sdk/src/platform/minigame/api.ts+++ b/sdk/src/platform/minigame/api.ts@@ -385,7 +385,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' | (string & {});+export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | (string & {});/*** A vendor described as DATA — three facts and, at most, one method.diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex af22b7593..3429c7769 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', 'android', 'ios'];+export const TARGETS = ['web', 'playable', 'desktop', 'wechat', 'douyin', 'kuaishou', 'bilibili', '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 2f48316ef..d88add468 100644--- a/tools/nativeScriptModules.js+++ b/tools/nativeScriptModules.js@@ -98,6 +98,10 @@ export const MODULES = {disposition: 'forbidden-native-script',why: "Kuaishou's platform profile — it names a host global (`ks`) that a native build does not have",},+ 'esengine/bilibili': {+ disposition: 'forbidden-native-script',+ why: "Bilibili's platform profile — it names a host global (`bl`) 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 91aa004c4..b0e2ef6bd 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -984,6 +984,12 @@ export const NOTED = {{ note: 'A project can be packaged for Kuaishou (快手).' },'fix(runtime): a mini-game host with only WebGL1 is told the game cannot start':{ note: 'A mini-game host that offers only WebGL1 is told the game cannot start there' },+ 'feat(export): a project can be packaged for Bilibili':+ { note: 'A project can be packaged for Bilibili (B 站).' },+ 'feat(editor): Bilibili is a build target, and a cap can be per subpackage':+ { note: 'A project can be packaged for Bilibili (B 站).' },+ 'feat(runtime): a mini-game host that asks to hear the first frame is told':+ { note: 'A mini-game host that asks to hear when the first screen has rendered is told' },'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." },};