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): one decision for which Spine runtimes a package carries, with Include and Exclude per runtime
yhhba9ffef66566
diff --git a/desktop b/desktopindex 4b215f26e..32deb3b22 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 4b215f26eb806e79bf17dd2ad43561c352facaad+Subproject commit 32deb3b22e57a870d6866bc8d08f071939b5ab7ediff --git a/docs/astro/src/content/docs/publishing/android-ios.mdx b/docs/astro/src/content/docs/publishing/android-ios.mdxindex 55135524b..e6f4d976d 100644--- a/docs/astro/src/content/docs/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/publishing/android-ios.mdx@@ -232,6 +232,22 @@ library (0.2 to 1 MB per ABI). The export reads the version of every skeletonit packages and includes only the libraries those skeletons need. On iOS andthe desktop all versions are linked into the app, which adds about 1 MB.+Which runtimes a package carries is decided once for every target: the web,+playables, mini-games and Android. Project Settings → Spine has a row per+runtime, and each row says what the build will do with it:++- **Auto** (the default) carries the runtime when a packaged skeleton was+ exported from it.+- **Include** carries it even when no packaged skeleton uses it. Use it for+ skeletons that only code loads, such as a path built at run time or content+ fetched later.+- **Exclude** leaves it out. If a packaged skeleton needs that runtime, the+ export fails and names the skeleton, so it never ships a skeleton that cannot+ play.++The export result lists every runtime with the reason it was carried or left+out.+A runtime template from an older release carries a single Spine version. Ifyou package with one, the export lists every skeleton the template cannotplay. Install this editor version's template from Package Project to fix it.diff --git a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdxindex d6ecbba19..c82ec5648 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx@@ -191,6 +191,15 @@ Android 的下限是 29,因为引擎的字体路径调用 `AFontMatcher_create`,Android 上每个版本是一个单独的库(每个 ABI 0.2 到 1 MB)。导出时会读取每个要打包的骨架的版本,只放入这些骨架需要的库。iOS 和桌面端把所有版本都链接进应用,大约增加 1 MB。+一个包带哪些运行时,由同一处逻辑统一决定,网页、试玩广告、小游戏和 Android 都一样。+项目设置 → Spine 里每个运行时一行,每行都会显示构建会怎么处理它:++- **自动**(默认):包里有骨架是用这个版本导出的就带上。+- **包含**:即使包里没有骨架用到也带上。用于只有代码才会加载的骨架,比如运行时拼出来的路径、之后才下载的内容。+- **排除**:不带。如果包里有骨架需要这个运行时,导出会失败并点名该骨架,不会打出一个骨架播不了的包。++导出结果里会列出每个运行时带或不带,以及原因。+旧版本的运行时模板只编入一个 Spine 版本。如果用旧模板打包,导出会列出模板播放不了的每个骨架。在“打包项目”里安装当前编辑器版本的模板即可解决。diff --git a/pipeline/src/bundle/sideModuleScan.ts b/pipeline/src/bundle/sideModuleScan.tsindex 6e3e62aeb..e113a2cf4 100644--- a/pipeline/src/bundle/sideModuleScan.ts+++ b/pipeline/src/bundle/sideModuleScan.ts@@ -8,8 +8,9 @@import { readFile } from 'node:fs/promises';import path from 'node:path';import { statSync } from 'node:fs';+import { spineChoiceKey, type ModuleChoice } from '../project/format';import {- SIDE_MODULES, spineModuleId, physics3dModuleId, getEditorType,+ SIDE_MODULES, SPINE_VERSIONS, spineModuleId, physics3dModuleId, getEditorType,sceneUsesPhysics, sceneUses3DPhysics,type SideModuleId, type SpineVersion, type Physics3DBackend,} from 'esengine';@@ -56,6 +57,77 @@ export interface SideModuleScanInput {forced?: readonly string[];/** The project's 3D backend: which module answers for the 3D world. Absent ⇒ Jolt. */physics3dBackend?: Physics3DBackend;+ /** What the project said per module, from `moduleChoices` — read here for the+ * Spine runtimes (`esengine/spine@<version>`, see resolveSpineRuntimes). */+ choices?: Readonly<Record<string, ModuleChoice>>;+}++/** Why one Spine runtime is in a package or not, for the export to report. */+export interface SpineRuntimeDecision {+ version: SpineVersion;+ ships: boolean;+ /** `detected`: a shipped skeleton was exported from it. `included`/`excluded`:+ * the project said so. `unused`: nothing needs it and nothing asked. */+ why: 'detected' | 'included' | 'excluded' | 'unused';+ /** The shipped skeletons exported from it (authored paths). */+ skeletons: readonly string[];+}++/** The Spine runtimes a package carries, decided once for every target. */+export interface SpineRuntimePlan {+ versions: readonly SpineVersion[];+ decisions: readonly SpineRuntimeDecision[];+ /** Runtimes the project excluded that shipped skeletons need: the export fails,+ * since the alternative is a package whose skeletons silently do not play. */+ refused: ReadonlyArray<{ version: SpineVersion; skeletons: readonly string[] }>;+}++/**+ * Which Spine runtimes a package carries: the ones its skeletons were exported+ * from, plus what the project included, minus what it excluded. Every target+ * asks this one function — web and playable side modules, a mini-game's+ * per-version wasm, Android's per-release libraries — so a runtime cannot ship on+ * one and be missing on another. Detection reads the skeleton files themselves;+ * `include` is for skeletons only code loads (a path built at run time, content+ * fetched later), `exclude` for one detection collected that never plays.+ */+export function resolveSpineRuntimes(+ skeletons: ReadonlyMap<string, readonly string[]>,+ choices: Readonly<Record<string, ModuleChoice>> = {},+): SpineRuntimePlan {+ const moduleExcluded = choices['esengine/spine'] === 'exclude';+ const decisions: SpineRuntimeDecision[] = [];+ const refused: Array<{ version: SpineVersion; skeletons: readonly string[] }> = [];+ for (const version of SPINE_VERSIONS) {+ const used = skeletons.get(version) ?? [];+ const choice = moduleExcluded ? 'exclude' : (choices[spineChoiceKey(version)] ?? 'auto');+ if (choice === 'exclude') {+ decisions.push({ version, ships: false, why: 'excluded', skeletons: used });+ // The whole-module refusal is engineInstalls'; this names the runtime.+ if (used.length && !moduleExcluded) refused.push({ version, skeletons: used });+ } else if (choice === 'include') {+ decisions.push({ version, ships: true, why: used.length ? 'detected' : 'included', skeletons: used });+ } else {+ decisions.push({ version, ships: used.length > 0, why: used.length ? 'detected' : 'unused', skeletons: used });+ }+ }+ return { versions: decisions.filter((d) => d.ships).map((d) => d.version), decisions, refused };+}++/** A refused runtime, said the way the other module refusals are. */+export function spineRefusalMessage(r: { version: string; skeletons: readonly string[] }): string {+ const named = r.skeletons.slice(0, 3).join(', ') + (r.skeletons.length > 3 ? `, and ${r.skeletons.length - 3} more` : '');+ return `${spineChoiceKey(r.version)} is excluded in Project Settings, and this build ships `+ + `${r.skeletons.length} skeleton${r.skeletons.length === 1 ? '' : 's'} exported from Spine ${r.version} `+ + `(${named}). Set it to Auto or Include, or export those skeletons from a runtime the package carries.`;+}++/** What a package carries, with the Spine part spelled out. */+export interface SideModulePlan {+ ids: Set<SideModuleId>;+ spine: SpineRuntimePlan;+ /** Every shipped skeleton by the runtime it was exported from. */+ skeletons: ReadonlyMap<SpineVersion, readonly string[]>;}const VERSION_PREFIXES: ReadonlyArray<readonly [string, SpineVersion]> = [@@ -136,6 +208,12 @@ async function readDocuments(root: string, includedPaths: readonly string[]): Pr* entry scene.*/export async function scanSideModuleIds(input: SideModuleScanInput): Promise<Set<SideModuleId>> {+ return (await planSideModules(input)).ids;+}++/** {@link scanSideModuleIds}, with the Spine decision and its evidence: what an+ * export reports, and refuses on. */+export async function planSideModules(input: SideModuleScanInput): Promise<SideModulePlan> {const ids = new Set<SideModuleId>();const docs = await readDocuments(input.root, input.includedPaths);@@ -159,8 +237,26 @@ export async function scanSideModuleIds(input: SideModuleScanInput): Promise<Setconst editorType = getEditorType(e.sourcePath ?? e.path);if (editorType === 'dragonbones-skeleton' || editorType === 'dragonbones-atlas') ids.add('dragonbones');}- for (const v of (await scanSpineSkeletons(input.cookEntries, input.stagedDir)).keys()) ids.add(spineModuleId(v));- return ids;+ const skeletons = await scanSpineSkeletons(input.cookEntries, input.stagedDir);+ const spine = resolveSpineRuntimes(skeletons, input.choices);+ for (const v of spine.versions) ids.add(spineModuleId(v));+ return { ids, spine, skeletons };+}++/**+ * The Spine runtime one skeleton file was exported from, read from its bytes —+ * null for an atlas, an unreadable file, or a version no runtime reads. `named`+ * is the path whose extension says which format it is (a cooked copy may carry+ * a `.bin` suffix). Shared with the settings page, so it attributes skeletons+ * to runtimes exactly as the export does.+ */+export async function spineSkeletonVersion(file: string, named: string = file): Promise<SpineVersion | null> {+ const ext = path.extname(named).toLowerCase();+ try {+ if (ext === '.skel') return detectSpineVersion(new Uint8Array(await readFile(file)));+ if (ext === '.json') return detectSpineVersionJson(await readFile(file, 'utf8'));+ } catch { /* unreadable — cookAssets already warned */ }+ return null;}/**@@ -175,19 +271,11 @@ export async function scanSpineSkeletons(const byVersion = new Map<SpineVersion, string[]>();for (const e of cookEntries) {if (e.type !== 'spine') continue;- const ext = path.extname(e.sourcePath ?? e.path).toLowerCase();- try {- let v: SpineVersion | null = null;- if (ext === '.skel') {- v = detectSpineVersion(new Uint8Array(await readFile(path.join(stagedDir, e.path))));- } else if (ext === '.json') {- v = detectSpineVersionJson(await readFile(path.join(stagedDir, e.path), 'utf8'));- }- if (!v) continue;- const list = byVersion.get(v) ?? [];- list.push(e.sourcePath ?? e.path);- byVersion.set(v, list);- } catch { /* unreadable cook entry — cookAssets already warned */ }+ const v = await spineSkeletonVersion(path.join(stagedDir, e.path), e.sourcePath ?? e.path);+ if (!v) continue;+ const list = byVersion.get(v) ?? [];+ list.push(e.sourcePath ?? e.path);+ byVersion.set(v, list);}return byVersion;}diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 75c84ff50..4b2deb25d 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -87,7 +87,7 @@ import { sizeSettingsOf } from './sizeHistory';import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';import { subsystemGapWarnings, targetGaps } from '../project/targetSupport';import { contentSubsystems } from './contentSubsystems';-import { scanSideModuleIds, scanSpineSkeletons, sideModuleFiles, shipsSideModule, textureDecoderBytes } from '../bundle/sideModuleScan';+import { planSideModules, spineRefusalMessage, type SpineRuntimeDecision, sideModuleFiles, shipsSideModule, textureDecoderBytes } from '../bundle/sideModuleScan';import { nativeSpineMismatch } from './nativeTemplates';import { MODULES, NATIVE_MODULE_REGISTRY } from '../../../tools/nativeScriptModules.js';@@ -287,6 +287,9 @@ export interface ExportGameResult {packedFrom?: Record<string, number>;warnings: string[];errors: string[];+ /** Each Spine runtime, whether this package carries it, and why — detected from+ * a skeleton, included or excluded in Project Settings, or unused. */+ spineRuntimes?: readonly SpineRuntimeDecision[];/** A native target's bundle id, as the installed app is known to the OS. */appId?: string;/** Android: the generated Gradle project, for the editor to reveal. Absent@@ -946,6 +949,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>let appId: string | undefined;let androidProject: string | undefined;let apkFile: string | undefined;+ let spineRuntimes: readonly SpineRuntimeDecision[] | undefined;let aabFile: string | undefined;/** Desktop: one assembled app per desktop OS a template is installed for. */let appBundles: { os: DesktopOs; dir: string }[] = [];@@ -1043,24 +1047,27 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>// asset model in the package — the mini-game export has always done this.await rm(path.join(payloadDir, 'assets.manifest.json'), { force: true });- // A native host links one Spine runtime, so a skeleton of another version- // does not play on it (#115). Read from the files: the project setting is a- // preference, and editor Play loads every version.- const nativeSpine = nativeContent- ? await scanSpineSkeletons(cookEntries, payloadDir) : new Map<string, string[]>();-- // What wasm this project's content pulls in — evidence for the plan below, and- // the filter the runtime tree is copied through further down.- const sideModuleIds = !nativeContent && existsSync(opts.wasmDir)- ? await scanSideModuleIds({- root: opts.root, includedPaths: cook.includedPaths, cookEntries,- stagedDir: payloadDir,- // One path for old and new: moduleChoices reads `physics.enabled` as an- // include, so the legacy flag arrives here as the choice it always meant.- forced: forcedSideModules(moduleChoices(opts.features, opts.modulesByPlatform?.[platform])),- physics3dBackend: opts.features?.physics?.backend3d,- })- : [];+ // What this package's content pulls in, decided once for every target: the+ // web's side modules and, on Android, which Spine release libraries ship. The+ // project's per-module choices (Spine per runtime) are applied here, so a+ // runtime only code reaches can be included and one detection over-collected+ // excluded — and an exclusion the content contradicts fails the export.+ const choices = moduleChoices(opts.features, opts.modulesByPlatform?.[platform]);+ const sidePlan = await planSideModules({+ root: opts.root, includedPaths: cook.includedPaths, cookEntries,+ stagedDir: payloadDir,+ // One path for old and new: moduleChoices reads `physics.enabled` as an+ // include, so the legacy flag arrives here as the choice it always meant.+ forced: forcedSideModules(choices),+ physics3dBackend: opts.features?.physics?.backend3d,+ choices,+ });+ for (const r of sidePlan.spine.refused) errors.push(spineRefusalMessage(r));+ spineRuntimes = sidePlan.spine.decisions;+ /** The Spine runtimes a native package carries, with the skeletons each reads:+ * Android packs one library per entry; the other targets carry every release. */+ const nativeSpine = new Map(sidePlan.spine.versions.map((v) => [v, sidePlan.skeletons.get(v) ?? []]));+ const sideModuleIds = !nativeContent && existsSync(opts.wasmDir) ? sidePlan.ids : [];/** The subpaths this package installs, and whether a lean entry can carry it.* Set on the browser path once the project's own imports are known. */let plan: EngineInstallPlan = { lean: false, subpaths: [], refused: [] };@@ -1452,5 +1459,6 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>...(appBundles.length > 0 ? { appBundles } : {}),...(steamChecklist ? { steamChecklist } : {}),...(splashBytes !== undefined ? { splashBytes } : {}),+ ...(spineRuntimes ? { spineRuntimes } : {}),};}diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex 4805125e2..6004e26ef 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -33,7 +33,7 @@ import { packagedDebugChannel } from './debugChannel';import { packagedHotUpdate } from './hotUpdateConfig';import { loadEsbuild } from '../bundle/esbuildRuntime';import { liteEngineAnswer, scriptsMentionOmitted } from './liteEngine';-import type { ProjectFeatures, ProjectPackaging } from '../project/format';+import type { ModuleChoice, ProjectFeatures, ProjectPackaging } from '../project/format';import {DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, withAudioLoadTypes, type RuntimeProjectConfig,} from '../project/runtimeConfig';@@ -51,7 +51,7 @@ import { breakdownOf, type ModuleBytes } from './bundleBreakdown';import { esengineAlias } from '../bundle/esengineResolve';import { officialPackagesPlugin } from '../bundle/officialPackages';import { explainBundleErrors, type BundleMessage } from '../bundle/bundleDiagnostics';-import { scanSideModuleIds, sideModuleFiles, textureDecoderBytes } from '../bundle/sideModuleScan';+import { planSideModules, spineRefusalMessage, sideModuleFiles, textureDecoderBytes, type SpineRuntimePlan } from '../bundle/sideModuleScan';import { exportedAssetFiles, pruneExportedAssets } from './assetCleanup';import { OPEN_DATA_DIR, isEsModule } from './miniGameExportProfile';import type { RpkSigningKey } from './rpk';@@ -82,6 +82,8 @@ export interface ExportMiniGameResult {included: number;warnings: string[];errors: string[];+ /** Each Spine runtime, whether this package carries it, and why. */+ spineRuntimes?: SpineRuntimePlan['decisions'];/** @internal Why each asset is in the build; the size report consumes and drops it. */inclusion?: Record<string, Inclusion>;/** What each subsystem costs inside `game-bundle.js`, largest first. The bundle@@ -222,11 +224,18 @@ async function scanSideModules(wasmDir: string,errors: string[],forced: readonly string[],- physics3dBackend?: Physics3DBackend,+ physics3dBackend: Physics3DBackend | undefined,+ choices: Readonly<Record<string, ModuleChoice>>,+ onSpine: (plan: SpineRuntimePlan) => void,): Promise<Array<{ id: string; file: string }>> {- const ids = await scanSideModuleIds({- root, includedPaths, cookEntries, stagedDir: absOut, forced, physics3dBackend,+ // One decision for every target (resolveSpineRuntimes): a mini-game pays for+ // each Spine runtime it carries, and fails to boot a skeleton whose runtime it+ // dropped, so the project's per-runtime choice is applied here too.+ const { ids, spine } = await planSideModules({+ root, includedPaths, cookEntries, stagedDir: absOut, forced, physics3dBackend, choices,});+ for (const r of spine.refused) errors.push(spineRefusalMessage(r));+ onSpine(spine);const { files, unknown } = sideModuleFiles(ids);for (const id of unknown) errors.push(`internal: no artifact mapping for side module "${id}"`);@@ -443,10 +452,14 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// 1b. Scan the shipped content for the optional modules it needs (physics/spine),// so the generated entry requires exactly those — the export-time half of// the runtime's self-gating.+ const moduleChoiceMap = moduleChoices(opts.features, opts.modulesByPlatform?.[profile.id]);+ let spineRuntimes: SpineRuntimePlan['decisions'] | undefined;const engineSideModules = await scanSideModules(profile, opts.root, cook.includedPaths, cookEntries, absOut, opts.wasmDir, errors,- forcedSideModules(moduleChoices(opts.features, opts.modulesByPlatform?.[profile.id])),+ forcedSideModules(moduleChoiceMap),opts.features?.physics?.backend3d,+ moduleChoiceMap,+ (spine) => { spineRuntimes = spine.decisions; },);// …plus the ones the PROJECT supplies. They are not scanned for: a project put// them in `.esengine/modules/` in order to use them, and unlike physics or@@ -775,5 +788,6 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// export that made them names them.subPackageRoots: subPackages.subPackages.map((sp) => sp.root),...(Object.keys(packedFrom).length > 0 ? { packedFrom } : {}),+ ...(spineRuntimes ? { spineRuntimes } : {}),};}diff --git a/pipeline/src/export/exportPlayable.ts b/pipeline/src/export/exportPlayable.tsindex 0103d9aac..c28846c04 100644--- a/pipeline/src/export/exportPlayable.ts+++ b/pipeline/src/export/exportPlayable.ts@@ -39,10 +39,10 @@ import type { ScreenOrientation } from './orientationHtml';import { genericPlayableProfile, playableAdInjection, isPlayableZipFileName, type PlayableAdProfile } from './playableAdProfile';import { checkPlayable, type PlayableCheckReport } from './playableCheck';import { makeZip } from '../../../build-tools/utils/zip.js';-import { scanSideModuleIds, sideModuleFiles } from '../bundle/sideModuleScan';+import { planSideModules, spineRefusalMessage, sideModuleFiles } from '../bundle/sideModuleScan';import type { Physics3DBackend } from 'esengine';import { forcedSideModules, moduleChoices } from '../bundle/engineInstalls';-import type { ProjectFeatures, ProjectPackaging } from '../project/format';+import type { ModuleChoice, ProjectFeatures, ProjectPackaging } from '../project/format';export interface ExportPlayableResult {ok: boolean;@@ -160,11 +160,15 @@ async function collectSideModules(wasmDir: string,errors: string[],forced: readonly string[],- physics3dBackend?: Physics3DBackend,+ physics3dBackend: Physics3DBackend | undefined,+ choices: Readonly<Record<string, ModuleChoice>>,): Promise<Record<string, { glue: PackedBytes; wasm: PackedBytes }>> {- const ids = await scanSideModuleIds({- root, includedPaths, cookEntries: manifestEntries, stagedDir: cookDir, forced, physics3dBackend,+ // A playable inlines every runtime it carries into one file under a hard size+ // cap, so it takes the same per-runtime Spine decision as every other target.+ const { ids, spine } = await planSideModules({+ root, includedPaths, cookEntries: manifestEntries, stagedDir: cookDir, forced, physics3dBackend, choices,});+ for (const r of spine.refused) errors.push(spineRefusalMessage(r));const { files, unknown } = sideModuleFiles(ids);for (const id of unknown) errors.push(`internal: no artifact mapping for side module "${id}"`);@@ -371,10 +375,12 @@ export async function exportPlayable(opts: {// A needed module missing from wasmDir is a HARD error — better a failed// export than a playable that silently ships without physics.progress({ phase: 'Embedding modules' });+ const playableChoices = moduleChoices(opts.features, opts.modulesByPlatform?.playable);const sideModules = await collectSideModules(opts.root, cook.includedPaths, manifestEntries, cookDir, opts.wasmDir, errors,- forcedSideModules(moduleChoices(opts.features, opts.modulesByPlatform?.playable)),+ forcedSideModules(playableChoices),opts.features?.physics?.backend3d,+ playableChoices,);// 6. Assemble once for each measured candidate, with fixed engine/script spans.diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.tsindex ba3b0ba43..213635006 100644--- a/pipeline/src/project/format.ts+++ b/pipeline/src/project/format.ts@@ -134,6 +134,18 @@ export interface ProjectScripts {*/export type ModuleChoice = 'auto' | 'include' | 'exclude';+/**+ * The `features.modules` key for one Spine runtime: `esengine/[email protected]`. Spine+ * is the one module with several runtimes, and which ones a package carries is+ * the question that sizes it — a mini-game or an Android package pays for each.+ * `auto` carries a runtime when a shipped skeleton was exported from it;+ * `include` carries it for skeletons only code loads; `exclude` drops it, and an+ * export whose content needs it fails (see resolveSpineRuntimes).+ */+export function spineChoiceKey(version: string): string {+ return `esengine/spine@${version}`;+}+export interface ProjectFeatures {/*** Per-module override, keyed by the `esengine/` subpath that installs it — thediff --git a/pipeline/tests/spine-runtimes.test.ts b/pipeline/tests/spine-runtimes.test.tsnew file mode 100644index 000000000..9892ed5db--- /dev/null+++ b/pipeline/tests/spine-runtimes.test.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Which Spine runtimes a package carries. A mini-game, a playable or an+ * Android package pays for every runtime it carries, and a skeleton whose+ * runtime was left out does not play: too many and the package is over+ * its cap, too few and it does not run. One decision serves every target+ * (resolveSpineRuntimes); these hold it to the skeleton files themselves+ * and to the project's per-runtime choice.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, copyFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ planSideModules, resolveSpineRuntimes, spineRefusalMessage,+} from '../src/bundle/sideModuleScan';+import { spineChoiceKey } from '../src/project/format';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const TP = path.join(HERE, '..', '..', 'third_party');++/** Real exports from the vendored runtimes' own examples: the version is read+ * from the bytes, so a fixture that only claimed one would prove nothing. */+const SKELETONS: Record<string, string> = {+ '3.8': path.join(TP, 'spine-runtimes-3.8', 'examples', 'spineboy', 'export', 'spineboy-pro.skel'),+ '4.2': path.join(TP, 'spine-runtimes-4.2', 'examples', 'spineboy', 'export', 'spineboy-pro.skel'),+};++let staged: string;+beforeAll(() => {+ staged = mkdtempSync(path.join(tmpdir(), 'estella-spine-rt-'));+ for (const [v, file] of Object.entries(SKELETONS)) copyFileSync(file, path.join(staged, `hero${v}.skel`));+});+afterAll(() => rmSync(staged, { recursive: true, force: true }));++const entries = (...versions: string[]) =>+ versions.map((v) => ({ path: `hero${v}.skel`, sourcePath: `assets/hero${v}.skel`, type: 'spine' }));++function plan(versions: string[], choices: Record<string, 'auto' | 'include' | 'exclude'> = {}) {+ return planSideModules({ root: staged, includedPaths: [], cookEntries: entries(...versions), stagedDir: staged, choices });+}++describe('the Spine runtimes a package carries', () => {+ it('carries exactly the runtimes its skeletons were exported from', async () => {+ const p = await plan(['3.8', '4.2']);+ expect([...p.ids].filter((id) => id.startsWith('spine:')).sort()).toEqual(['spine:3.8', 'spine:4.2']);+ expect(p.spine.versions).toEqual(['3.8', '4.2']);+ expect(p.spine.decisions.find((d) => d.version === '3.8')).toMatchObject({+ ships: true, why: 'detected', skeletons: ['assets/hero3.8.skel'],+ });+ expect(p.spine.decisions.find((d) => d.version === '4.1')).toMatchObject({ ships: false, why: 'unused' });+ });++ it('carries no runtime for a package with no skeletons', async () => {+ const p = await plan([]);+ expect([...p.ids].some((id) => id.startsWith('spine:'))).toBe(false);+ });++ // A skeleton a script loads by a path it builds at run time leaves nothing for+ // the cook to see: the project says so, and the runtime ships.+ it('carries a runtime the project includes for skeletons only code loads', async () => {+ const p = await plan(['4.2'], { [spineChoiceKey('3.8')]: 'include' });+ expect(p.spine.versions).toEqual(['3.8', '4.2']);+ expect(p.spine.decisions.find((d) => d.version === '3.8')).toMatchObject({ ships: true, why: 'included' });+ });++ it('leaves out an unused runtime the project excludes, and says why', async () => {+ const p = await plan(['4.2'], { [spineChoiceKey('3.8')]: 'exclude' });+ expect(p.spine.versions).toEqual(['4.2']);+ expect(p.spine.refused).toEqual([]);+ expect(p.spine.decisions.find((d) => d.version === '3.8')).toMatchObject({ ships: false, why: 'excluded' });+ });++ // Too few is the failure that only a device shows: refuse the export instead,+ // naming the skeletons that would not play.+ it('refuses an excluded runtime that a shipped skeleton needs', async () => {+ const p = await plan(['3.8', '4.2'], { [spineChoiceKey('3.8')]: 'exclude' });+ expect(p.spine.versions).toEqual(['4.2']);+ expect(p.spine.refused).toEqual([{ version: '3.8', skeletons: ['assets/hero3.8.skel'] }]);+ const message = spineRefusalMessage(p.spine.refused[0]);+ expect(message).toContain('esengine/[email protected] is excluded');+ expect(message).toContain('assets/hero3.8.skel');+ });++ it('carries nothing when the whole Spine module is excluded, leaving the refusal to the module', () => {+ const r = resolveSpineRuntimes(new Map([['4.2', ['a.skel']]]), { 'esengine/spine': 'exclude' });+ expect(r.versions).toEqual([]);+ expect(r.refused).toEqual([]);+ });+});