Skip to content

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.

fix(assets): a Spine skeleton exported as JSON is an asset, not an unknown file

yhhcce400d227e6
diff --git a/desktop/electron/assetMeta.ts b/desktop/electron/assetMeta.ts
index 51936de1d..b5f2cd66d 100644
--- a/desktop/electron/assetMeta.ts
+++ b/desktop/electron/assetMeta.ts
@@ -6,26 +6,57 @@
* orphan-adoption pass — mints through here, so the uuid/version/type/
* importer shape can never diverge between doors.
*
- * The ext→type vocabulary is single-sourced in `tools/assetMetaTable.js`,
+ * The file→type vocabulary is single-sourced in `tools/assetMetaTable.js`,
* shared verbatim with the CLI `tools/asset-meta.js`, so the two mint
* doors can never disagree on a file's `.meta` type.
*/
-import { writeFile } from 'node:fs/promises';
+import { writeFile, open } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import { META_EXT } from './contentPolicy';
import { importerDefaults } from '../src/project/assetImporter';
-import { EXT_TO_TYPE, metaTypeForExt } from '../../tools/assetMetaTable.js';
+import {
+ EXT_TO_TYPE, metaTypeForExt, metaTypeForContent, needsContentType, CONTENT_SNIFF_BYTES,
+} from '../../tools/assetMetaTable.js';
export const META_VERSION = '2.0';
export { EXT_TO_TYPE };
-/** The meta `type` for a file name/path, or null for unknown extensions. */
+/** The meta `type` a file's NAME declares, or null when the name cannot say. */
export function metaTypeFor(file: string): string | null {
return metaTypeForExt(file);
}
+/** The first @p bytes of a file as text, or '' if it can't be read. */
+async function readHead(absFile: string, bytes: number): Promise<string> {
+ let handle: Awaited<ReturnType<typeof open>> | undefined;
+ try {
+ handle = await open(absFile, 'r');
+ const buf = Buffer.alloc(bytes);
+ const { bytesRead } = await handle.read(buf, 0, bytes, 0);
+ return buf.subarray(0, bytesRead).toString('utf8');
+ } catch {
+ return '';
+ } finally {
+ await handle?.close();
+ }
+}
+
+/**
+ * The meta `type` for a file ON DISK — the door every minter should use. The
+ * name answers for almost everything; for the extensions it cannot type
+ * ({@link needsContentType}) the file's own header does. Spine's JSON skeleton
+ * is the case: it is a plain `.json`, so a name-only door left it unregistered
+ * and its component slot had nothing to offer — which is the whole of "my Spine
+ * 2.1 skeleton cannot be assigned".
+ */
+export async function metaTypeForFile(absFile: string): Promise<string | null> {
+ const byName = metaTypeForExt(absFile);
+ if (byName || !needsContentType(absFile)) return byName;
+ return metaTypeForContent(absFile, await readHead(absFile, CONTENT_SNIFF_BYTES));
+}
+
/** A fresh `.meta` document for an asset of `type`. */
export function mintMeta(type: string): Record<string, unknown> {
return { uuid: randomUUID(), version: META_VERSION, type, importer: importerDefaults(type) };
@@ -38,13 +69,13 @@ export async function writeMeta(absFile: string, type: string): Promise<void> {
}
/**
- * Adopt an orphan: mint `<absFile>.meta` iff the file has none and its
- * extension names a known asset type. Returns what happened, so callers can
- * count adoptions / skip unknowns without re-deriving the checks.
+ * Adopt an orphan: mint `<absFile>.meta` iff the file has none and it resolves
+ * to a known asset type. Returns what happened, so callers can count adoptions /
+ * skip unknowns without re-deriving the checks.
*/
export async function adoptOrphan(absFile: string): Promise<'adopted' | 'has-meta' | 'unknown-type'> {
if (existsSync(absFile + META_EXT)) return 'has-meta';
- const type = metaTypeFor(absFile);
+ const type = await metaTypeForFile(absFile);
if (!type) return 'unknown-type';
await writeMeta(absFile, type);
return 'adopted';
diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.ts
index 441398cc6..a4ebce634 100644
--- a/desktop/electron/importAssets.ts
+++ b/desktop/electron/importAssets.ts
@@ -11,10 +11,16 @@ import { copyFile, mkdir, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { resolveInRoot, META_EXT } from './projectFs';
-import { EXT_TO_TYPE, metaTypeFor, mintMeta, writeMeta, adoptOrphan } from './assetMeta';
+import { EXT_TO_TYPE, metaTypeFor, metaTypeForFile, mintMeta, writeMeta, adoptOrphan } from './assetMeta';
+import { CONTENT_TYPED_EXTENSIONS } from '../../tools/assetMetaTable.js';
-/** The supported import extensions (no leading dot) — used by the file dialog filter. */
-export const IMPORT_EXTENSIONS = Object.keys(EXT_TO_TYPE).map((e) => e.slice(1));
+/** The supported import extensions (no leading dot) — used by the file dialog filter.
+ * The content-typed ones are offered too: a Spine JSON skeleton is a `.json`, and a
+ * dialog that hides it leaves the user no way to bring one in. Whether such a file
+ * really is an asset is settled by reading it (metaTypeForFile), not by the filter. */
+export const IMPORT_EXTENSIONS = [
+ ...new Set([...Object.keys(EXT_TO_TYPE), ...CONTENT_TYPED_EXTENSIONS]),
+].map((e) => e.slice(1));
/** A unique destination name in `absDir`: "hero.png" → "hero 2.png" if taken. */
function uniqueName(absDir: string, name: string): string {
@@ -103,7 +109,7 @@ export async function importAssets(root: string, destDir: string, sources: strin
const imported: string[] = [];
const skipped: string[] = [];
for (const src of sources) {
- const type = metaTypeFor(src);
+ const type = await metaTypeForFile(src);
if (!type) {
skipped.push(path.basename(src));
continue;
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index e26aadb0d..c4fa449e1 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -64,7 +64,6 @@ import { LogStore } from './store/LogStore';
import { initFsWatch } from './project/fsWatch';
import { initPlugins } from './plugins/init';
import { openAssetOfType } from './project/assetOpen';
-import { assetTypeOf } from './project/assetTypes';
import { initBackgroundThrottle } from './engine/backgroundThrottle';
// Register the built-in settings (side effect) and replay persisted ones.
import './settings';
@@ -251,7 +250,7 @@ if (new URLSearchParams(location.search).has('automation')) {
/** Double-click-open an asset by project path (FSM/BT/tileset/clip editors…). */
openAsset: (path: string) => {
const name = path.split('/').pop() ?? path;
- openAssetOfType(assetTypeOf(name), path, name);
+ openAssetOfType(ProjectStore.assetTypeAt(path), path, name);
},
reveal: (id: string) => dockApi.revealAndExpand(id),
/** Open a registered panel by id, docking it where its def says (reveal only
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index d0b76ee27..233bbb0dd 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -13,7 +13,7 @@ import { Segmented } from '@/components/Segmented';
import { ProjectStore } from '@/project/ProjectStore';
import { Toasts } from '@/store/Toasts';
import { useSelection } from '@/store/selectionStore';
-import { IMAGE_RE, assetTypeOf as assetType, baseName, TYPE_CODE } from '@/project/assetMeta';
+import { IMAGE_RE, baseName, TYPE_CODE } from '@/project/assetMeta';
import { openAssetOfType } from '@/project/assetOpen';
import { assetTypeRegistry } from '@/project/assetTypes';
import { contributedContextRows } from '@/plugins/contextMenus';
@@ -43,6 +43,12 @@ const TILE_KEY = 'estella.content.tileSize';
const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e));
+/** What kind of thing a project file is — the ONE resolver the tiles, badges, type
+ * chips, sort and double-click open all read, so they cannot disagree. Asked by
+ * PATH, not name: a file's type is not always readable from its name (a Spine JSON
+ * skeleton is a plain `.json`), and the registry knows what its `.meta` recorded. */
+const typeAt = (path: string): AssetType => ProjectStore.assetTypeAt(path);
+
// Per-delivery-mode presentation (menu label + corner badge; `local` has none).
// Keyed by AssetGroupMode so adding a mode to the SDK's ASSET_GROUP_MODES forces
// a matching entry here — the vocabulary is single-sourced in the SDK, only its
@@ -151,7 +157,7 @@ function AssetTipCard({ path, entry }: { path: string; entry: DirEntry }) {
const [stat, setStat] = useState<{ size: number; mtimeMs: number } | null>(null);
const [dims, setDims] = useState<string | null>(null);
- const type: AssetType = entry.isDir ? 'folder' : assetType(entry.name);
+ const type: AssetType = entry.isDir ? 'folder' : typeAt(path);
const isImg = !entry.isDir && IMAGE_RE.test(entry.name);
const assetReference = entry.isDir ? null : ProjectStore.assetRef(path);
@@ -445,7 +451,7 @@ export function ContentBrowser() {
[searching, scan.files, entries, cwd],
);
const items = useMemo(
- () => filterAndSortAssets(rows, parsed, filters as ReadonlySet<string>, sort, assetType),
+ () => filterAndSortAssets(rows, parsed, filters as ReadonlySet<string>, sort, typeAt),
[rows, parsed, filters, sort],
);
const listLoading = searching ? scan.loading : dirLoading;
@@ -466,7 +472,7 @@ export function ContentBrowser() {
go(path);
return;
}
- openAssetOfType(assetType(name), path, name);
+ openAssetOfType(typeAt(path), path, name);
};
// After any fs mutation: re-read open directories + re-scan the asset registry
@@ -506,8 +512,8 @@ export function ContentBrowser() {
return;
}
// Preserve a FILE's extension if the user dropped it (e.g. Ctrl+A + retype):
- // assetType() drives the icon AND double-click open and is extension-based, so
- // an extensionless file would go inert. Folders have no extension to keep.
+ // the type drives the icon AND double-click open and is mostly extension-based,
+ // so an extensionless file would go inert. Folders have no extension to keep.
const isDir = entries.find((e) => e.name === cur)?.isDir ?? false;
const dot = cur.lastIndexOf('.');
const ext = !isDir && dot > 0 ? cur.slice(dot) : '';
@@ -1002,11 +1008,12 @@ export function ContentBrowser() {
];
}
const { path, entry } = ctx.target;
- const isScene = !entry.isDir && assetType(entry.name) === 'scene';
- const isTexture = !entry.isDir && (assetType(entry.name) === 'texture' || assetType(entry.name) === 'sprite');
- const isTileset = !entry.isDir && assetType(entry.name) === 'tileset';
- const isAnimClip = !entry.isDir && assetType(entry.name) === 'animclip';
- const isMaterial = !entry.isDir && assetType(entry.name) === 'material';
+ const targetType = entry.isDir ? 'folder' : typeAt(path);
+ const isScene = targetType === 'scene';
+ const isTexture = targetType === 'texture' || targetType === 'sprite';
+ const isTileset = targetType === 'tileset';
+ const isAnimClip = targetType === 'animclip';
+ const isMaterial = targetType === 'material';
const ref = entry.isDir ? null : ProjectStore.assetRef(path);
return [
// Offered for everything, because opening now always resolves to something —
@@ -1245,7 +1252,7 @@ export function ContentBrowser() {
))}
{!listLoading && items.map((it) => {
const path = it.path;
- const type: AssetType = it.isDir ? 'folder' : assetType(it.name);
+ const type: AssetType = it.isDir ? 'folder' : typeAt(path);
const isImg = !it.isDir && IMAGE_RE.test(it.name);
const deliv = it.isDir ? ProjectStore.folderDeliveryMode(path) : 'local';
return (
@@ -1322,7 +1329,7 @@ export function ContentBrowser() {
))}
{!listLoading && items.map((it) => {
const path = it.path;
- const type: AssetType = it.isDir ? 'folder' : assetType(it.name);
+ const type: AssetType = it.isDir ? 'folder' : typeAt(path);
return (
<div
key={path}
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 8609976f5..1860c2d28 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -56,7 +56,7 @@ import { AudioWavePreview } from '@/components/AudioWavePreview';
import { NineSliceEditor } from '@/components/NineSliceEditor';
import { fsRefresh } from '@/project/fsWatch';
import { Toasts } from '@/store/Toasts';
-import { baseName, assetTypeOf, IMAGE_RE } from '@/project/assetMeta';
+import { baseName, IMAGE_RE } from '@/project/assetMeta';
import { BUILTIN_PLATFORMS, type BuiltinPlatform } from '@/project/platforms';
import { revealAsset } from '@/project/assetReveal';
import { useSelection } from '@/store/selectionStore';
@@ -3184,7 +3184,7 @@ function LocaleSection({ title, badge, action, children }: {
// rows); other assets show their fs metadata + the image/type glyph preview.
function AssetInspector({ path }: { path: string }) {
- const type = assetTypeOf(baseName(path));
+ const type = ProjectStore.assetTypeAt(path);
if (isMaterialAsset(path)) {
return <MaterialAssetInspector path={path} />;
}
@@ -3350,7 +3350,7 @@ function TexturePlatformOverrides({ importer, write }: { importer: Record<string
// (written to the `.meta` sidecar) through the shared ComponentSection engine.
function GenericAssetInspector({ path }: { path: string }) {
const name = baseName(path);
- const type = assetTypeOf(name);
+ const type = ProjectStore.assetTypeAt(path);
const isImage = IMAGE_RE.test(name);
const [importer, setImporter] = useState<Record<string, unknown> | null>(null);
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 023735443..723a866ea 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -34,6 +34,7 @@ import { confirm } from '@/components/confirm';
import { previewApply } from './applyPreview';
import { t } from '@/i18n';
import { assetTypeOf } from '@/project/assetMeta';
+import { ASSET_TYPES, assetTypeDef } from '@/project/assetTypes';
import { ASSET_SLOTS, metaTypeToSlot } from '@/project/assetSlots';
import type { AssetType } from '@/types';
import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenPreset, type ScreenOrientation, type CameraScaleMode, type ExportPlatform } from './format';
@@ -59,10 +60,18 @@ function assetMatchesSlot(type: AssetType, path: string, fieldType?: string): bo
if (!fieldType) return true;
// A 'texture' slot accepts any image (texture or sprite); others match by name.
if (fieldType === 'texture') return type === 'texture' || type === 'sprite';
- // Spine slots discriminate the shared 'spine' Content-Browser type by
- // extension, through the SDK's own classification (.skel vs .atlas) — the
- // same vocabulary the cook's dep scan uses.
- if (fieldType === 'spine-skeleton' || fieldType === 'spine-atlas') return getEditorType(path) === fieldType;
+ // Spine slots split the shared 'spine' Content-Browser type into its two
+ // halves, through the SDK's own classification (.skel vs .atlas) — the same
+ // vocabulary the cook's dep scan uses.
+ if (fieldType === 'spine-skeleton' || fieldType === 'spine-atlas') {
+ const named = getEditorType(path);
+ if (named === 'spine-skeleton' || named === 'spine-atlas') return named === fieldType;
+ // A JSON skeleton has no extension of its own — Spine 2.1 exports nothing
+ // else — so what says it is one is its registered `spine` type, minted from
+ // the marker inside the file. Only the skeleton half can arrive unnamed:
+ // the atlas is always `.atlas`.
+ return fieldType === 'spine-skeleton' && type === 'spine';
+ }
if (type === fieldType) return true;
// Slots named in the SDK's editorType vocabulary rather than the
// Content-Browser type name (anim-clip for .esanim, timeline for .estimeline).
@@ -797,7 +806,7 @@ class ProjectStoreImpl {
* writes against.
*/
async getImportSettings(path: string): Promise<{ type: string; settings: Record<string, unknown> }> {
- const type = assetTypeOf(path.split('/').pop() ?? path);
+ const type = this.assetTypeAt(path);
const stored = JSON.parse(await window.estella.fs.read(path + '.meta')).importer as
| Record<string, unknown>
| undefined;
@@ -2038,12 +2047,31 @@ class ProjectStoreImpl {
return path ? { path, name: path.split('/').pop() ?? path } : null;
}
+ /**
+ * The Content-Browser type of a project file — the ONE answer the picker, the
+ * drag-drop guard and the browser tiles all read, so they cannot disagree about
+ * what a file is.
+ *
+ * The name decides it wherever an extension (or a `_ske.json`-style suffix) can:
+ * that claim is cheap, and holds for files the registry has never seen. Where
+ * the name says nothing, the registered `.meta` type does — it was minted from
+ * the file's own content, which is the only thing that can tell a Spine JSON
+ * skeleton from any other `.json`.
+ */
+ assetTypeAt(path: string): AssetType {
+ const byName = assetTypeOf(path.split('/').pop() ?? path);
+ if (byName !== 'file') return byName;
+ const uuid = this.pathToUuid.get(path);
+ const metaType = uuid ? this.uuidToType.get(uuid) : undefined;
+ return metaType && assetTypeDef(metaType) !== ASSET_TYPES.file ? (metaType as AssetType) : byName;
+ }
+
/** Project assets valid for an asset slot (the inspector's asset picker), by name. */
listAssets(fieldType?: string): AssetEntry[] {
const out: AssetEntry[] = [];
for (const [uuid, path] of this.uuidToPath) {
const name = path.split('/').pop() ?? path;
- const type = assetTypeOf(name);
+ const type = this.assetTypeAt(path);
if (!assetMatchesSlot(type, path, fieldType)) continue;
out.push({ ref: UUID_PREFIX + uuid, path, name, type });
}
@@ -2054,8 +2082,7 @@ class ProjectStoreImpl {
* the picker popover filters by, exposed so drag-drop can reject a wrong-typed asset. */
assetTypeAllowed(fieldType: string | undefined, path: string): boolean {
if (!fieldType) return true;
- const name = path.split('/').pop() ?? path;
- return assetMatchesSlot(assetTypeOf(name), path, fieldType);
+ return assetMatchesSlot(this.assetTypeAt(path), path, fieldType);
}
/**
diff --git a/desktop/src/project/assetFilter.ts b/desktop/src/project/assetFilter.ts
index 73e85b1b9..0ba743fc1 100644
--- a/desktop/src/project/assetFilter.ts
+++ b/desktop/src/project/assetFilter.ts
@@ -9,9 +9,12 @@
*/
export type AssetSort = 'name' | 'type';
-/** The minimal row shape the filter/sort needs (name + folder flag). */
+/** The minimal row shape the filter/sort needs (name + path + folder flag). The
+ * path is what `typeOf` is asked about: a file's type is not always readable
+ * from its name, so the caller resolves it against the asset registry. */
export interface AssetRowLike {
name: string;
+ path: string;
isDir: boolean;
}
@@ -47,7 +50,7 @@ export function filterAndSortAssets<T extends AssetRowLike>(
parsed: ParsedQuery,
chipTypes: ReadonlySet<string>,
sort: AssetSort,
- typeOf: (name: string) => string,
+ typeOf: (path: string) => string,
): T[] {
const constraints = [...new Set([...chipTypes, ...parsed.types])];
const hasType = constraints.length > 0;
@@ -55,13 +58,13 @@ export function filterAndSortAssets<T extends AssetRowLike>(
const list = entries.filter((e) => {
if (parsed.text && !e.name.toLowerCase().includes(parsed.text)) return false;
if (e.isDir) return !hasType;
- return !hasType || constraints.some((c) => matchesType(typeOf(e.name), c));
+ return !hasType || constraints.some((c) => matchesType(typeOf(e.path), c));
});
return [...list].sort((a, b) => {
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1; // folders first
if (sort === 'type' && !a.isDir && !b.isDir) {
- const t = typeOf(a.name).localeCompare(typeOf(b.name));
+ const t = typeOf(a.path).localeCompare(typeOf(b.path));
if (t !== 0) return t;
}
return a.name.localeCompare(b.name);
diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.ts
index acf3b17f8..ae02f6390 100644
--- a/desktop/src/project/assetTypes.ts
+++ b/desktop/src/project/assetTypes.ts
@@ -54,6 +54,10 @@ export const ASSET_TYPES: Record<BuiltinAssetType, AssetTypeDef> = {
scene: { extensions: ['esscene'], badge: 'SCN', icon: Film, tint: '#c98a93' },
texture: { extensions: ['png', 'webp'], badge: 'TEX', icon: FileImage, tint: '#7fa6c4', externalProgram: 'image' },
sprite: { extensions: ['jpg', 'jpeg', 'gif'], badge: 'IMG', icon: Image, tint: '#7fa6c4', externalProgram: 'image' },
+ // A skeleton exported as JSON has no extension of its own; it is typed at the
+ // `.meta` mint door by a marker in the file (tools/assetMetaTable.js) and reaches
+ // this vocabulary through ProjectStore.assetTypeAt — which is why every caller
+ // asks that by PATH rather than calling assetTypeOf on a bare name.
spine: { extensions: ['atlas', 'skel'], badge: 'SPN', icon: PersonStanding, tint: '#9b8fc0' },
// Both halves are one type, as Spine's .skel and .atlas are: which file plays
// which role is the component's business, not the content browser's.
diff --git a/desktop/tests/asset-db.test.ts b/desktop/tests/asset-db.test.ts
index 4081fdfc9..3f2ab95b9 100644
--- a/desktop/tests/asset-db.test.ts
+++ b/desktop/tests/asset-db.test.ts
@@ -146,4 +146,21 @@ describe('scanAssetDatabase — orphan adoption', () => {
expect(existsSync(`${abs}.meta`)).toBe(false);
rmSync(abs);
});
+
+ // "I dropped my spine folder into the project" — with a JSON skeleton, which is
+ // all Spine 2.1 can export. Nothing in the NAME says the `.json` is a skeleton,
+ // so a name-only adoption left it out of the registry entirely and its component
+ // slot had nothing to offer.
+ it('adopts a JSON Spine skeleton as spine, and leaves plain data JSON alone', async () => {
+ const skel = path.join(root, 'assets/skeleton.json');
+ const data = path.join(root, 'assets/levels.json');
+ writeFileSync(skel, '{"skeleton":{"hash":"h","spine":"2.1.27"},"bones":[{"name":"root"}]}');
+ writeFileSync(data, '{"levels":[1,2,3]}');
+ const res = await scanAssetDatabase(root, { write: false });
+ expect(res.adopted).toEqual(['assets/skeleton.json']);
+ expect(JSON.parse(readFileSync(`${skel}.meta`, 'utf8')).type).toBe('spine');
+ expect(existsSync(`${data}.meta`)).toBe(false);
+ expect(res.index.entries.find((e) => e.path === 'assets/skeleton.json')?.type).toBe('spine');
+ rmSync(skel); rmSync(`${skel}.meta`); rmSync(data);
+ });
});
diff --git a/desktop/tests/asset-filter.test.ts b/desktop/tests/asset-filter.test.ts
index 33fb58a86..d05707d53 100644
--- a/desktop/tests/asset-filter.test.ts
+++ b/desktop/tests/asset-filter.test.ts
@@ -5,23 +5,26 @@
* filter (tokens + chips, prefix match), and sort order.
*/
import { describe, it, expect } from 'vitest';
-import { parseAssetQuery, filterAndSortAssets, type AssetSort } from '@/project/assetFilter';
-import type { DirEntry } from '@/project/format';
+import { parseAssetQuery, filterAndSortAssets, type AssetSort, type AssetRowLike } from '@/project/assetFilter';
-const typeOf = (name: string): string => {
- if (name.endsWith('.png')) return 'texture';
- if (name.endsWith('.esmat')) return 'material';
- if (name.endsWith('.esscene')) return 'scene';
+// Typed by PATH, as the panel does: the registry — not the bare name — is what
+// can answer for a file whose name doesn't declare its kind.
+const typeOf = (path: string): string => {
+ if (path.endsWith('.png')) return 'texture';
+ if (path.endsWith('.esmat')) return 'material';
+ if (path.endsWith('.esscene')) return 'scene';
+ if (path === 'assets/skeleton.json') return 'spine';
return 'other';
};
-const E = (name: string, isDir = false): DirEntry => ({ name, isDir });
-const entries: DirEntry[] = [
+const E = (name: string, isDir = false): AssetRowLike => ({ name, path: `assets/${name}`, isDir });
+const entries: AssetRowLike[] = [
E('zfolder', true),
E('afolder', true),
E('villain.png'),
E('hero.png'),
E('ground.esmat'),
E('main.esscene'),
+ E('skeleton.json'),
];
const run = (q: string, chips: string[] = [], sort: AssetSort = 'name') =>
filterAndSortAssets(entries, parseAssetQuery(q), new Set(chips), sort, typeOf).map((e) => e.name);
@@ -54,12 +57,21 @@ describe('filterAndSortAssets', () => {
});
it('sort=name lists folders first, then files alphabetically', () => {
- expect(run('')).toEqual(['afolder', 'zfolder', 'ground.esmat', 'hero.png', 'main.esscene', 'villain.png']);
+ expect(run('')).toEqual([
+ 'afolder', 'zfolder', 'ground.esmat', 'hero.png', 'main.esscene', 'skeleton.json', 'villain.png',
+ ]);
});
it('sort=type groups files by type after the folders', () => {
- // material, scene, texture, texture — folders first.
- expect(run('', [], 'type')).toEqual(['afolder', 'zfolder', 'ground.esmat', 'main.esscene', 'hero.png', 'villain.png']);
+ // material, scene, spine, texture, texture — folders first.
+ expect(run('', [], 'type')).toEqual([
+ 'afolder', 'zfolder', 'ground.esmat', 'main.esscene', 'skeleton.json', 'hero.png', 'villain.png',
+ ]);
+ });
+
+ it('types a row by its PATH, so a name that cannot declare its kind still filters', () => {
+ // A Spine JSON skeleton is a plain `.json`; only the registry knows it is spine.
+ expect(run('type:spine')).toEqual(['skeleton.json']);
});
it('is generic — preserves extra row fields (e.g. a full path for recursive search)', () => {
diff --git a/desktop/tests/asset-meta-table.test.ts b/desktop/tests/asset-meta-table.test.ts
index fe0bcb3da..0e85eeed3 100644
--- a/desktop/tests/asset-meta-table.test.ts
+++ b/desktop/tests/asset-meta-table.test.ts
@@ -9,7 +9,9 @@
// never got a `.meta`).
import { describe, it, expect } from 'vitest';
import { EXT_TO_TYPE, metaTypeFor } from '../electron/assetMeta';
-import { EXT_TO_TYPE as SHARED } from '../../tools/assetMetaTable.js';
+import {
+ EXT_TO_TYPE as SHARED, metaTypeForContent, needsContentType,
+} from '../../tools/assetMetaTable.js';
describe('.meta type table (single source)', () => {
it('the editor mint door re-exports the shared table verbatim', () => {
@@ -37,4 +39,45 @@ describe('.meta type table (single source)', () => {
expect(metaTypeFor('notes.txt')).toBeNull();
expect(metaTypeFor('README.md')).toBeNull();
});
+
+ it('types a DragonBones pair by its name suffix (`.json` alone cannot)', () => {
+ expect(metaTypeFor('DragonBoy_ske.json')).toBe('dragonbones');
+ expect(metaTypeFor('DragonBoy_tex.json')).toBe('dragonbones');
+ expect(metaTypeFor('DragonBoy.dbbin')).toBe('dragonbones');
+ });
+});
+
+// A Spine skeleton exported as JSON is a plain `.json` under whatever name the
+// artist chose — and Spine 2.1 has NO binary export, so that is the only form
+// such a project can hand the editor. It is typed by the marker inside the file:
+// the same one the runtime's version detection reads, so the editor and the
+// runtime cannot disagree about what a given `.json` is.
+describe('content-typed assets', () => {
+ const SKELETON = '{"skeleton":{"hash":"4NGJIALC","spine":"2.1.27","width":1371.35},"bones":[]}';
+
+ it('claims only the files a name cannot type', () => {
+ expect(needsContentType('skeleton.json')).toBe(true);
+ expect(needsContentType('hero.png')).toBe(false);
+ expect(needsContentType('level.tmj')).toBe(false);
+ // A name that DOES type it is not up for content review.
+ expect(needsContentType('DragonBoy_ske.json')).toBe(false);
+ });
+
+ it('types a Spine JSON skeleton as spine', () => {
+ expect(metaTypeForContent('skeleton.json', SKELETON)).toBe('spine');
+ expect(metaTypeForContent('boy.json', '{"skeleton":{"spine":"4.2.31"},"bones":[]}')).toBe('spine');
+ // Pretty-printed exports read the same.
+ expect(metaTypeForContent('x.json', '{\n "skeleton": {\n "spine": "3.8.99"\n }\n}')).toBe('spine');
+ });
+
+ it('leaves project data alone — a `.json` is not an asset just for being JSON', () => {
+ expect(metaTypeForContent('levels.json', '{"levels":[1,2,3]}')).toBeNull();
+ // "spine" outside a skeleton header is not a skeleton.
+ expect(metaTypeForContent('notes.json', '{"about":"the spine: 4.2 runtime"}')).toBeNull();
+ });
+
+ it('never overrides a name that already typed the file', () => {
+ expect(metaTypeForContent('DragonBoy_ske.json', '{"armature":[]}')).toBe('dragonbones');
+ expect(metaTypeForContent('hero.png', SKELETON)).toBe('texture');
+ });
});
diff --git a/desktop/tests/import-assets.test.ts b/desktop/tests/import-assets.test.ts
index 91c4a8b25..5136f046c 100644
--- a/desktop/tests/import-assets.test.ts
+++ b/desktop/tests/import-assets.test.ts
@@ -10,7 +10,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync, readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
-import { importAssets, createAsset } from '../electron/importAssets';
+import { importAssets, createAsset, IMPORT_EXTENSIONS } from '../electron/importAssets';
let root: string;
let outside: string;
@@ -85,6 +85,30 @@ describe('importAssets', () => {
expect(res.imported).toEqual([]);
expect(res.skipped).toEqual(['notes.txt']);
});
+
+ // Spine 2.1 has no binary export: a project on that runtime ships `skeleton.json`,
+ // and a name-only door left it unregistered — so the Skeleton Path slot had nothing
+ // to offer and rejected the file the user dropped on it.
+ it('imports a Spine JSON skeleton as spine (typed by its content, not its name)', async () => {
+ const src = path.join(outside, 'skeleton.json');
+ writeFileSync(src, '{"skeleton":{"hash":"h","spine":"2.1.27"},"bones":[{"name":"root"}]}');
+ const res = await importAssets(root, 'assets/spine', [src]);
+ expect(res.imported).toEqual(['assets/spine/skeleton.json']);
+ expect(meta(path.join(root, 'assets/spine/skeleton.json')).type).toBe('spine');
+ });
+
+ it('still skips a plain data .json — being JSON does not make a file an asset', async () => {
+ const src = path.join(outside, 'levels.json');
+ writeFileSync(src, '{"levels":[1,2,3]}');
+ const res = await importAssets(root, 'assets', [src]);
+ expect(res.imported).toEqual([]);
+ expect(res.skipped).toEqual(['levels.json']);
+ });
+
+ it('offers the content-typed extensions in the dialog filter', () => {
+ expect(IMPORT_EXTENSIONS).toContain('json');
+ expect(new Set(IMPORT_EXTENSIONS).size).toBe(IMPORT_EXTENSIONS.length);
+ });
});
describe('createAsset', () => {
diff --git a/tools/asset-meta.js b/tools/asset-meta.js
index 69cea59fb..41ef07d45 100644
--- a/tools/asset-meta.js
+++ b/tools/asset-meta.js
@@ -23,11 +23,13 @@
* 2 — usage / IO error
*/
-import { readdir, stat, readFile, writeFile, access } from 'node:fs/promises';
-import { join, extname, basename, relative, resolve } from 'node:path';
+import { readdir, stat, readFile, writeFile, access, open } from 'node:fs/promises';
+import { join, relative, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { parseArgs } from 'node:util';
-import { EXT_TO_TYPE } from './assetMetaTable.js';
+import {
+ EXT_TO_TYPE, metaTypeForExt, metaTypeForContent, needsContentType, CONTENT_SNIFF_BYTES,
+} from './assetMetaTable.js';
const META_VERSION = '2.0';
@@ -43,8 +45,9 @@ const SKIP_FILES = new Set([
'.gitkeep', '.gitignore', '.gitattributes',
]);
-// Extension → `.meta` type is single-sourced in ./assetMetaTable.js (shared
-// with the editor's mint door, desktop/electron/assetMeta.ts).
+// File → `.meta` type is single-sourced in ./assetMetaTable.js (shared with the
+// editor's mint door, desktop/electron/assetMeta.ts) — extension, name suffix,
+// and the content sniff for the formats a name cannot type.
/**
* Default `importer` settings per type. Shapes match the examples/ meta
@@ -81,10 +84,31 @@ function getImporterDefaults(type) {
}
}
-/** Returns the asset type for a path, or null if the extension is unknown. */
-function getAssetType(filePath) {
- const ext = extname(filePath).toLowerCase();
- return EXT_TO_TYPE[ext] ?? null;
+/** The first `bytes` of a file as text, or '' if it can't be read. */
+async function readHead(filePath, bytes) {
+ let handle;
+ try {
+ handle = await open(filePath, 'r');
+ const buf = Buffer.alloc(bytes);
+ const { bytesRead } = await handle.read(buf, 0, bytes, 0);
+ return buf.subarray(0, bytesRead).toString('utf8');
+ } catch {
+ return '';
+ } finally {
+ await handle?.close();
+ }
+}
+
+/**
+ * The asset type for a path on disk, or null if nothing can type it. The name
+ * answers for almost everything; the formats it cannot type (Spine's JSON
+ * skeleton is a plain `.json`) are typed by a marker in the file's head — the
+ * same rule the editor's mint door applies.
+ */
+async function getAssetType(filePath) {
+ const byName = metaTypeForExt(filePath);
+ if (byName || !needsContentType(filePath)) return byName;
+ return metaTypeForContent(filePath, await readHead(filePath, CONTENT_SNIFF_BYTES));
}
/** Builds the meta object (JSON-shape) for a given type. */
@@ -153,7 +177,7 @@ export async function generateMetaForDir(dir, options = {}) {
const skipped = [];
for await (const filePath of walk(root)) {
- const type = getAssetType(filePath);
+ const type = await getAssetType(filePath);
if (type === null) {
if (verbose) skipped.push({ path: filePath, reason: 'unknown extension' });
continue;
@@ -224,7 +248,7 @@ export async function buildManifest(dir, options = {}) {
const warnings = [];
for await (const filePath of walk(root)) {
- const type = getAssetType(filePath);
+ const type = await getAssetType(filePath);
if (type === null) continue;
const metaPath = filePath + '.meta';
diff --git a/tools/assetMetaTable.d.ts b/tools/assetMetaTable.d.ts
index 50f36a4d7..9b8fe8e56 100644
--- a/tools/assetMetaTable.d.ts
+++ b/tools/assetMetaTable.d.ts
@@ -1,4 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export const EXT_TO_TYPE: Readonly<Record<string, string>>;
+export const SUFFIX_TO_TYPE: Readonly<Record<string, string>>;
+export const CONTENT_TYPED_EXTENSIONS: readonly string[];
+export const CONTENT_SNIFF_BYTES: number;
export function metaTypeForExt(fileOrExt: string): string | null;
+export function needsContentType(fileOrExt: string): boolean;
+export function metaTypeForContent(fileOrExt: string, head: string): string | null;
diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.js
index f5ae24b1d..992fcd93a 100644
--- a/tools/assetMetaTable.js
+++ b/tools/assetMetaTable.js
@@ -2,7 +2,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file assetMetaTable.js
- * @brief The ONE extension -> `.meta` type table.
+ * @brief The ONE file -> `.meta` type table: by extension, by name suffix, and
+ * — where neither can decide — by a marker in the file's content.
*
* The `.meta` sidecar's `type` field is minted from here by both the CLI
* (`tools/asset-meta.js`) and the editor's mint door
@@ -73,14 +74,72 @@ export const EXT_TO_TYPE = Object.freeze({
'.estilemap': 'tilemap',
'.tmx': 'tilemap',
'.tmj': 'tilemap',
- // Spine (skel / atlas — the .png pair is a plain texture)
+ // Spine (skel / atlas — the .png pair is a plain texture). A JSON skeleton has
+ // no extension of its own; see CONTENT_TYPED_EXTENSIONS below.
'.skel': 'spine',
'.atlas': 'spine',
+ // DragonBones binary skeleton; its JSON pair is named, see SUFFIX_TO_TYPE.
+ '.dbbin': 'dragonbones',
});
-/** The `.meta` type for a file name/path, or null for unknown extensions. */
+/**
+ * Full lower-case name endings claiming a type, checked BEFORE extensions
+ * because they are the more specific claim. DragonBones ships `_ske.json` beside
+ * `_tex.json`, and `.json` alone cannot see the difference. Mirrors the
+ * `suffixes` in sdk/src/assetTypes.ts and desktop/src/project/assetTypes.ts —
+ * without it this door was the only one of the three that could not type a
+ * DragonBones pair, so importing one skipped both halves.
+ */
+export const SUFFIX_TO_TYPE = Object.freeze({
+ '_ske.json': 'dragonbones',
+ '_tex.json': 'dragonbones',
+});
+
+/** The `.meta` type for a file name/path, or null when the NAME cannot say. */
export function metaTypeForExt(fileOrExt) {
- const dot = fileOrExt.lastIndexOf('.');
- const ext = (dot >= 0 ? fileOrExt.slice(dot) : fileOrExt).toLowerCase();
- return EXT_TO_TYPE[ext] ?? null;
+ const lower = fileOrExt.toLowerCase();
+ for (const suffix of Object.keys(SUFFIX_TO_TYPE)) {
+ if (lower.endsWith(suffix)) return SUFFIX_TO_TYPE[suffix];
+ }
+ const dot = lower.lastIndexOf('.');
+ return EXT_TO_TYPE[dot >= 0 ? lower.slice(dot) : lower] ?? null;
+}
+
+/**
+ * Extensions whose type the name cannot decide, so the mint doors read the
+ * file's head and ask {@link metaTypeForContent}. Spine's JSON skeleton export
+ * is what forces this: it is a plain `.json` under any name the artist chose,
+ * and Spine 2.1 has no binary export at all — a project on that runtime has
+ * nothing else to hand the editor.
+ */
+export const CONTENT_TYPED_EXTENSIONS = Object.freeze(['.json']);
+
+/** How much of a file's head the sniff needs. A skeleton's `"skeleton"` header
+ * is the first thing the exporter writes, and a bound keeps the scan from
+ * re-reading every unrelated multi-megabyte JSON in the project. */
+export const CONTENT_SNIFF_BYTES = 65536;
+
+/** Whether @p fileOrExt is one the name cannot type but content can. */
+export function needsContentType(fileOrExt) {
+ const lower = fileOrExt.toLowerCase();
+ return metaTypeForExt(lower) === null && CONTENT_TYPED_EXTENSIONS.some((ext) => lower.endsWith(ext));
+}
+
+/** Spine's JSON skeleton header — a `skeleton` object naming the editor version
+ * that wrote it. The same marker the runtime types the file by
+ * (SpineManager.detectVersionJson), so the editor and the runtime cannot
+ * disagree about what a given `.json` is. */
+const SPINE_SKELETON_JSON = /"skeleton"\s*:\s*\{[^{}]*"spine"\s*:\s*"\d/;
+
+/**
+ * The `.meta` type for a file whose head has been read — the name-derived one
+ * where a name suffices, else what the content declares. Null means neither
+ * could type it (a plain data `.json`), which the callers treat as "not an
+ * asset", exactly as an unknown extension is.
+ */
+export function metaTypeForContent(fileOrExt, head) {
+ const byName = metaTypeForExt(fileOrExt);
+ if (byName) return byName;
+ if (!needsContentType(fileOrExt)) return null;
+ return SPINE_SKELETON_JSON.test(head) ? 'spine' : null;
}