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): typed propagation, from the plan's vertices to the effect

esengine01c1cd8eb920
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 1e98e0707..a747bbc04 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -766,7 +766,8 @@ ResourceDef<AssetsClass>
@internal appScope: AssetScope
@internal assetGraphSettled: () => Promise<void>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
-@internal dependentsOf: (ref: string, type?: string) => AssetIdentity[]
+@internal dependentsOfAsset: (asset: AssetIdentity) => AssetIdentity[]
+@internal dependentsOfSource: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 64dbc552a..f8eee5426 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -766,7 +766,8 @@ ResourceDef<AssetsClass>
@internal appScope: AssetScope
@internal assetGraphSettled: () => Promise<void>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
-@internal dependentsOf: (ref: string, type?: string) => AssetIdentity[]
+@internal dependentsOfAsset: (asset: AssetIdentity) => AssetIdentity[]
+@internal dependentsOfSource: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 3e438c9e8..c33fe45ae 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -761,7 +761,8 @@ ResourceDef<AssetsClass>
@internal appScope: AssetScope
@internal assetGraphSettled: () => Promise<void>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
-@internal dependentsOf: (ref: string, type?: string) => AssetIdentity[]
+@internal dependentsOfAsset: (asset: AssetIdentity) => AssetIdentity[]
+@internal dependentsOfSource: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 9b756a378..21c2aac03 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -761,7 +761,8 @@ ResourceDef<AssetsClass>
@internal appScope: AssetScope
@internal assetGraphSettled: () => Promise<void>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
-@internal dependentsOf: (ref: string, type?: string) => AssetIdentity[]
+@internal dependentsOfAsset: (asset: AssetIdentity) => AssetIdentity[]
+@internal dependentsOfSource: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index dd7f10a65..2a6c59184 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -761,7 +761,8 @@ ResourceDef<AssetsClass>
@internal appScope: AssetScope
@internal assetGraphSettled: () => Promise<void>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
-@internal dependentsOf: (ref: string, type?: string) => AssetIdentity[]
+@internal dependentsOfAsset: (asset: AssetIdentity) => AssetIdentity[]
+@internal dependentsOfSource: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 7e600a723..73379497d 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -1666,7 +1666,7 @@ export class Assets {
*/
invalidate(ref: string): boolean {
const plan = this.rebuildPlan_(ref);
- const { hit, rebuilt } = this.invalidateOne_(ref);
+ const { hit, rebuilt } = this.invalidateSource_(ref);
if (plan.length > 0) this.track_(rebuilt.then(() => this.rebuildAssetGraph_(plan)));
return hit;
}
@@ -1690,12 +1690,14 @@ export class Assets {
}
}
- /** What a change to `ref` reaches, after `ref` itself: this call ends its own
- * era, and a cycle back to it must not end it twice. */
+ /** What a change to `ref` reaches. Not filtered by path: an asset that
+ * happens to live at the changed file can still be what the chain reaches
+ * LAST, and dropping it there is the same erasure one level up. */
private rebuildPlan_(ref: string): AssetIdentity[][] {
- const root = this.resolveLoadPath_(ref);
- const plan = rebuildPlan(root, (path, type) => this.dependentsOf(path, type));
- return plan.map((group) => group.filter((v) => v.path !== root)).filter((g) => g.length > 0);
+ return rebuildPlan(this.resolveLoadPath_(ref), {
+ ofSource: (path) => this.dependentsOfSource(path),
+ ofAsset: (asset) => this.dependentsOfAsset(asset),
+ });
}
/** Count one propagation as in flight until it lands. It answers to nobody
@@ -1712,91 +1714,120 @@ export class Assets {
/** Each group only once everything it was built from has landed. */
private async rebuildAssetGraph_(plan: AssetIdentity[][]): Promise<void> {
for (const group of plan) {
- await Promise.all(group.map((vertex) => this.invalidateOne_(vertex.path).rebuilt));
+ await Promise.all(group.map((vertex) => this.invalidateAsset_(vertex).rebuilt));
}
}
- /** End one asset's era: drop every record of it, re-publish what is
- * published by name, and say which kind ended. `rebuilt` settles when its
- * own re-preparation has landed. */
- private invalidateOne_(ref: string): { hit: boolean; rebuilt: Promise<void> } {
- const path = this.resolveLoadPath_(ref);
- // The texture handle bound to this path, captured BEFORE the caches drop
- // it, so a rebind listener can swap it in live components (hot update).
- const oldTextureHandle = this.textureCache_.get(this.textureCacheKey_(path, true))?.handle ?? 0;
+ /**
+ * End every era at one PATH: a file changed, and whatever it names changed
+ * with it. What `invalidate(ref)` is, and what a hot update's changed key is.
+ */
+ private invalidateSource_(ref: string): { hit: boolean; rebuilt: Promise<void> } {
let hit = false;
- // What each kind of cache was holding for this path, so the event says
- // which kind ended rather than leaving a listener to infer it.
- const dropped = new Map<AssetFieldType | AddressableAssetType, unknown>();
-
- // Textures: cache_key has a flip flag suffix, so check both. The C++
- // pool's residency identity is severed too — an evictable entry under
- // this key is freed and can never be revived with stale bytes.
- const rm = getResourceManager();
- for (const flip of [true, false]) {
- const key = this.textureCacheKey_(path, flip);
- if (this.textureCache_.invalidate(key)) { hit = true; dropped.set('texture', oldTextureHandle); }
- // The ledger is NOT dropped: holders of the outgoing generation
- // still owe a release, and forgetting them is what stranded their
- // texture with nobody able to free it. Its era ends here, though —
- // the next acquire opens a generation of its own even if the pool
- // hands back a numerically equal handle.
- this.textureRefs_.supersede(key);
- if (typeof rm?.invalidateTexturePath === 'function') {
- if (rm.invalidateTexturePath(key)) { hit = true; dropped.set('texture', oldTextureHandle); }
- }
+ const work: Array<Promise<void>> = [];
+ for (const type of this.loaders_.keys()) {
+ const ended = this.invalidateAsset_({ type, path: ref });
+ hit = ended.hit || hit;
+ work.push(ended.rebuilt);
}
+ return { hit, rebuilt: Promise.all(work).then(() => undefined) };
+ }
- // Generic caches: material / font / anim-clip / tilemap / timeline / audio / prefab.
- for (const [type, cache] of this.genericCache_.entries()) {
- const bound = cache.get(path)?.value;
- if (cache.invalidate(path)) { hit = true; dropped.set(type as AssetFieldType, bound); }
- // The ledger stays: the outgoing generation's holders still owe a
- // release. Its era is closed so the next acquire cannot join it.
+ /**
+ * End ONE asset's era — its type all the way down. A path can name a texture
+ * and a material, and what one of them acquired changing is not a change to
+ * the other; a plan that knows the difference and then ends both has thrown
+ * away what it knew.
+ */
+ private invalidateAsset_(asset: AssetIdentity): { hit: boolean; rebuilt: Promise<void> } {
+ const { type } = asset;
+ const path = this.resolveLoadPath_(asset.path);
+ // Held by a cache or by a loader's own residency: what a listener is
+ // told about. A slot swaps its era instead, and reports nothing.
+ let dropped = false;
+ let oldValue: unknown;
+
+ if (type === 'texture') {
+ // The handle bound to this path, captured BEFORE the caches drop it,
+ // so a rebind listener can swap it in live components.
+ oldValue = this.textureCache_.get(this.textureCacheKey_(path, true))?.handle ?? 0;
+ const rm = getResourceManager();
+ // Both flip variants: the cache key carries the flag. The C++ pool's
+ // residency identity is severed too — an evictable entry under this
+ // key is freed and can never be revived with stale bytes.
+ for (const flip of [true, false]) {
+ const key = this.textureCacheKey_(path, flip);
+ if (this.textureCache_.invalidate(key)) dropped = true;
+ // The ledger is NOT dropped: holders of the outgoing generation
+ // still owe a release, and forgetting them strands their texture
+ // with nobody able to free it. The era still ends here.
+ this.textureRefs_.supersede(key);
+ if (typeof rm?.invalidateTexturePath === 'function' && rm.invalidateTexturePath(key)) {
+ dropped = true;
+ }
+ }
+ } else {
+ const cache = this.genericCache_.get(type);
+ if (cache) {
+ oldValue = cache.get(path)?.value;
+ if (cache.invalidate(path)) dropped = true;
+ }
+ // The ledger stays, for the same reason as a texture's.
this.genericRefs_.supersede(`${type}:${path}`);
}
// A registry-backed asset has no cache entry to drop and no handle to
// swap: the update IS a new era published under the same names.
- const slots = this.republishSlots_(ref);
- if (slots.found) hit = true;
+ const slot = this.republishSlot_(type, asset.path);
- // Loader-owned residency (e.g. the AudioAPI warm cache) can outlive
- // the Assets-level entry — sever it unconditionally so a warm-cache
- // revive can never serve stale bytes after a hot reload.
- for (const [type, loader] of this.loaders_) {
- if (!loader.invalidate?.(path)) continue;
- hit = true;
- if (!dropped.has(type as AssetFieldType)) dropped.set(type as AssetFieldType, undefined);
- }
+ // Loader-owned residency (e.g. the AudioAPI warm cache) can outlive the
+ // Assets-level entry — sever it so a warm-cache revive can never serve
+ // stale bytes after a hot reload.
+ if (this.loaders_.get(type)?.invalidate?.(path)) dropped = true;
- // The reverse handle→path records for this path are stale now too — a
- // reload mints new handles; the old ones must stop naming the asset.
- for (const [key, p] of this.handleToPath_) {
- if (p === path) this.handleToPath_.delete(key);
+ // The reverse handle→path records of this kind are stale now: a reload
+ // mints new handles, and the old ones must stop naming the asset.
+ for (const [key, held] of this.handleToPath_) {
+ if (held === path && key.startsWith(`${type}:`)) this.handleToPath_.delete(key);
}
- for (const [type, oldValue] of dropped) this.fireInvalidate_({ ref, type, oldValue });
-
- return { hit, rebuilt: slots.rebuilt };
+ if (dropped) {
+ this.fireInvalidate_({ ref: asset.path, type: type as AssetFieldType, oldValue });
+ }
+ return { hit: dropped || slot.found, rebuilt: slot.rebuilt };
}
/**
- * Prepare a new era for every registry slot this ref names, and publish each
+ * Prepare a new era for the slot (type, ref) names, and publish it
* atomically. By IDENTITY: the slot is keyed by what the asset is, and this
* preparation resolves where the current revision serves it.
*/
- private republishSlots_(ref: string): { found: boolean; rebuilt: Promise<void> } {
+ private republishSlot_(type: string, ref: string): { found: boolean; rebuilt: Promise<void> } {
+ const kind = this.registryKind_(type);
const identity = this.assetIdentity_(ref);
- const work: Array<Promise<unknown>> = [];
- for (const [type] of this.loaders_) {
- const kind = this.registryKind_(type);
- if (!kind || !this.registrySlots_.has(type, identity)) continue;
- work.push(this.registrySlots_.republish(kind, type, identity).catch((e: unknown) => {
+ if (!kind || !this.registrySlots_.has(type, identity)) {
+ return { found: false, rebuilt: Promise.resolve() };
+ }
+ const rebuilt = this.registrySlots_.republish(kind, type, identity).then(
+ () => undefined,
+ (e: unknown) => {
log.warn('asset', `hot update: re-publishing "${ref}" failed; holders keep the era they have`, e);
- }));
+ },
+ );
+ return { found: true, rebuilt };
+ }
+
+ /** {@link republishSlot_} for every type this ref names one of — a changed
+ * FILE, which does not say what kind of asset lives at it. */
+ private republishSlots_(ref: string): { found: boolean; rebuilt: Promise<void> } {
+ const work: Array<Promise<void>> = [];
+ let found = false;
+ for (const type of this.loaders_.keys()) {
+ const slot = this.republishSlot_(type, ref);
+ found = slot.found || found;
+ work.push(slot.rebuilt);
}
- return { found: work.length > 0, rebuilt: Promise.all(work).then(() => undefined) };
+ return { found, rebuilt: Promise.all(work).then(() => undefined) };
}
/** Fire every onInvalidate listener with one generation's ending. Isolates
@@ -2206,7 +2237,26 @@ export class Assets {
*
* @internal
*/
- dependentsOf(ref: string, type?: string): AssetIdentity[] {
+ dependentsOfSource(ref: string): AssetIdentity[] {
+ // Both meanings of a file: whoever READ it, and whoever acquired the
+ // asset that lives at it.
+ return this.dependents_(ref, isInvalidatable);
+ }
+
+ /**
+ * Every asset of this realm that ACQUIRED this one — the edge to follow once
+ * the walk is past the file that changed. A source read is NOT one: those
+ * bytes are exactly as their reader read them, and what ended here is this
+ * asset's own generation.
+ *
+ * @internal
+ */
+ dependentsOfAsset(asset: AssetIdentity): AssetIdentity[] {
+ return this.dependents_(asset.path, (e) => e.kind === 'owned' && e.type === asset.type);
+ }
+
+ /** Every era with an edge that `names` — the walk both doors share. */
+ private dependents_(ref: string, names: (e: DependencyReceipt) => boolean): AssetIdentity[] {
const canonical = new Map<string, string>();
const identify = (path: string): string => {
let known = canonical.get(path);
@@ -2217,14 +2267,11 @@ export class Assets {
return known;
};
const target = identify(ref);
- // An acquisition names an ASSET, so a type narrows it; a source read
- // names CONTENT, which is the same file whatever else lives at it.
- const names = (e: DependencyReceipt): boolean =>
- isInvalidatable(e) && identify(e.path) === target
- && (type === undefined || e.kind === 'source' || e.type === type);
const out: AssetIdentity[] = [];
for (const era of this.eras_()) {
- if (era.edges.some(names)) out.push({ type: era.type, path: era.path });
+ if (era.edges.some((e) => names(e) && identify(e.path) === target)) {
+ out.push({ type: era.type, path: era.path });
+ }
}
return out;
}
diff --git a/sdk/src/asset/dependencies.ts b/sdk/src/asset/dependencies.ts
index 33bf8ad7f..91298bee0 100644
--- a/sdk/src/asset/dependencies.ts
+++ b/sdk/src/asset/dependencies.ts
@@ -71,6 +71,18 @@ export interface Preparation {
readonly edges: readonly DependencyReceipt[];
}
+/**
+ * The two reverse questions, which are not one question with a flag.
+ *
+ * `ofSource` is asked of the file that changed: whoever READ it, and whoever
+ * acquired the asset living at it. `ofAsset` is asked of every vertex after
+ * that, and answers acquisitions only — those bytes have not changed.
+ */
+export interface DependencyOracle {
+ ofSource(path: string): readonly AssetIdentity[];
+ ofAsset(asset: AssetIdentity): readonly AssetIdentity[];
+}
+
/**
* What to rebuild after `changed` changed, deepest dependency first, each cycle
* one group. The root is a PATH (a change names a file, which need not be an
@@ -78,8 +90,7 @@ export interface Preparation {
* share a path invents a cycle between them. Tarjan emits last-reached first.
*/
export function rebuildPlan(
- changed: string,
- dependents: (path: string, type?: string) => readonly AssetIdentity[],
+ changed: string, dependents: DependencyOracle,
): AssetIdentity[][] {
const index = new Map<string, number>();
const low = new Map<string, number>();
@@ -96,7 +107,7 @@ export function rebuildPlan(
next++;
stack.push(node);
open.add(key);
- for (const parent of dependents(node.path, node.type)) {
+ for (const parent of dependents.ofAsset(node)) {
const above = keyOf(parent);
if (!index.has(above)) {
visit(parent);
@@ -118,7 +129,7 @@ export function rebuildPlan(
// A forest, not a tree: the changed file can be read by several assets, and
// one already visited through another root is not visited again.
- for (const root of dependents(changed)) {
+ for (const root of dependents.ofSource(changed)) {
if (!index.has(keyOf(root))) visit(root);
}
return groups.reverse();
diff --git a/sdk/tests/asset-dependencies.test.ts b/sdk/tests/asset-dependencies.test.ts
index b0386da01..70625e4d5 100644
--- a/sdk/tests/asset-dependencies.test.ts
+++ b/sdk/tests/asset-dependencies.test.ts
@@ -14,6 +14,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Assets } from '../src/asset/Assets';
import { Catalog } from '../src/asset/Catalog';
import type { Backend } from '../src/asset/Backend';
+import type { LoadContext } from '../src/asset/AssetLoader';
function createPoolFake() {
const live = new Set<number>();
@@ -393,7 +394,7 @@ describe('what must be rebuilt when this changes', () => {
const assets = realm({ 'level.tmj': MAP_WITH_EXTERNAL, 'terrain.tsj': EXTERNAL_TILESET });
await assets.acquireTyped('tilemap', 'maps/level.tmj');
- expect(assets.dependentsOf('maps/terrain.tsj'))
+ expect(assets.dependentsOfSource('maps/terrain.tsj'))
.toEqual([{ type: 'tilemap', path: 'maps/level.tmj' }]);
});
@@ -401,7 +402,7 @@ describe('what must be rebuilt when this changes', () => {
const assets = realm({ 'hero.esmaterial': MATERIAL });
await assets.acquireTyped('material', 'materials/hero.esmaterial');
- expect(assets.dependentsOf('materials/wall.png'))
+ expect(assets.dependentsOfSource('materials/wall.png'))
.toEqual([{ type: 'material', path: 'materials/hero.esmaterial' }]);
});
@@ -414,7 +415,7 @@ describe('what must be rebuilt when this changes', () => {
const composed = assets.dependenciesOf('tilemap', 'maps/level.tmj')
.find((e) => e.path.startsWith('composed:'))!;
- expect(assets.dependentsOf(composed.path)).toEqual([]);
+ expect(assets.dependentsOfSource(composed.path)).toEqual([]);
});
it('a receipt spelled as a uuid answers to the file it resolves to', async () => {
@@ -434,8 +435,8 @@ describe('what must be rebuilt when this changes', () => {
});
await assets.acquireTyped('widget', 'x.widget');
- expect(assets.dependentsOf('art/skin.png')).toEqual([{ type: 'widget', path: 'x.widget' }]);
- expect(assets.dependentsOf('@uuid:skin'), 'the same asset, spelled the other way')
+ expect(assets.dependentsOfSource('art/skin.png')).toEqual([{ type: 'widget', path: 'x.widget' }]);
+ expect(assets.dependentsOfSource('@uuid:skin'), 'the same asset, spelled the other way')
.toEqual([{ type: 'widget', path: 'x.widget' }]);
});
@@ -444,7 +445,7 @@ describe('what must be rebuilt when this changes', () => {
const held = await assets.acquireTyped('tilemap', 'maps/level.tmj');
held.release();
- expect(assets.dependentsOf('maps/terrain.tsj')).toEqual([]);
+ expect(assets.dependentsOfSource('maps/terrain.tsj')).toEqual([]);
});
});
@@ -521,10 +522,10 @@ describe('a change reaches what was built from it', () => {
expect(events).toEqual(['child:start', 'child:end', 'parent:start', 'parent:end']);
});
- it('a cycle is a plan of one group, not a hang', async () => {
- // `A takes B` while B READ A is a real shape. What must be acyclic is the
- // plan, which is this graph's condensation — so each of them rebuilds
- // once and the walk terminates.
+ it('a cycle is a plan, not a hang', async () => {
+ // `A takes B` while B READ A is a real shape. Entered at the file A lives
+ // at: A rebuilds, B because it read that file, then A again because the B
+ // it holds is a new era. Each vertex is planned once, so it terminates.
const prepared: string[] = [];
const assets = realm({ 'a.aa': '{}', 'b.bb': '{}' });
assets.register({
@@ -553,6 +554,119 @@ describe('a change reaches what was built from it', () => {
assets.invalidate('a.aa');
await settled();
- expect(prepared).toEqual(['aa', 'bb']);
+ expect(prepared).toEqual(['aa', 'bb', 'aa']);
+ });
+});
+
+describe('propagation keeps the type all the way to the effect', () => {
+ beforeEach(() => { pool = createPoolFake(); materialFake.reset(); });
+
+ /** Three assets, two of them under ONE path: (aa,p) reads the file x,
+ * (bb,q) takes aa, (cc,p) takes bb. */
+ function chainOverOnePath(assets: Assets, prepared: string[]): void {
+ const link = (type: string, take: (ctx: LoadContext) => Promise<unknown>): void => {
+ assets.register({
+ type, extensions: [`.${type}`],
+ registry: {
+ prepare: async (path, ctx) => {
+ prepared.push(type);
+ await take(ctx);
+ return { published: { path }, value: { id: type } };
+ },
+ },
+ });
+ };
+ link('aa', (ctx) => ctx.readSource!('x'));
+ link('bb', (ctx) => ctx.acquireAsset('aa', 'p'));
+ link('cc', (ctx) => ctx.acquireAsset('bb', 'q'));
+ }
+
+ it('a path that names two assets rebuilds them in the order the plan says', async () => {
+ // The plan already knows (aa,p) and (cc,p) are two vertices. Ending an
+ // era by PATH ends both of them at once, so cc is rebuilt against the bb
+ // it already had — before bb itself has been touched.
+ const assets = realm({});
+ const prepared: string[] = [];
+ chainOverOnePath(assets, prepared);
+ await assets.acquireTyped('cc', 'p');
+ expect(prepared).toEqual(['cc', 'bb', 'aa']);
+
+ prepared.length = 0;
+ assets.invalidate('x');
+ await settled();
+
+ expect(prepared).toEqual(['aa', 'bb', 'cc']);
+ });
+
+ it('an asset at the changed path is still rebuilt in its turn', async () => {
+ // It was filtered out of every group for sharing the changed path, which
+ // is the same type-erasure one level up: (cc,p) is not the thing that
+ // changed, it is what the chain reaches last.
+ const assets = realm({});
+ const prepared: string[] = [];
+ chainOverOnePath(assets, prepared);
+ await assets.acquireTyped('cc', 'p');
+
+ prepared.length = 0;
+ assets.invalidate('p');
+ await settled();
+
+ expect(prepared.lastIndexOf('cc'), 'cc last rebuilt before bb, so from the old bb')
+ .toBeGreaterThan(prepared.indexOf('bb'));
+ });
+
+ /** An asset AT p, and an asset that READ the file at p. */
+ function overOnePath(assets: Assets, prepared: string[]): void {
+ assets.register({
+ type: 'skin', extensions: ['.skin'],
+ registry: {
+ prepare: async (path, ctx) => {
+ prepared.push('skin');
+ await ctx.acquireTexture('t.png');
+ return { published: { path }, value: { id: 'skin' } };
+ },
+ },
+ });
+ assets.register({
+ type: 'reader', extensions: ['.reader'],
+ registry: {
+ prepare: async (path, ctx) => {
+ prepared.push('reader');
+ await ctx.readSource!('p');
+ return { published: { path }, value: { id: 'reader' } };
+ },
+ },
+ });
+ }
+
+ it('an asset whose dependency changed is not a change to the FILE it lives at', async () => {
+ // The reader read the bytes at p. What changed is the texture (skin,p)
+ // acquired, so those bytes are exactly as it read them.
+ const assets = realm({});
+ const prepared: string[] = [];
+ overOnePath(assets, prepared);
+ await assets.acquireTyped('skin', 'p');
+ await assets.acquireTyped('reader', 'q');
+
+ prepared.length = 0;
+ assets.invalidate('t.png');
+ await settled();
+
+ expect(prepared).toEqual(['skin']);
+ });
+
+ it('a change to the file itself reaches both meanings of it', async () => {
+ const assets = realm({});
+ const prepared: string[] = [];
+ overOnePath(assets, prepared);
+ await assets.acquireTyped('skin', 'p');
+ await assets.acquireTyped('reader', 'q');
+
+ prepared.length = 0;
+ assets.invalidate('p');
+ await settled();
+
+ expect(prepared, 'the asset at p').toContain('skin');
+ expect(prepared, 'the asset that read p').toContain('reader');
});
});
diff --git a/sdk/tests/rebuild-plan.test.ts b/sdk/tests/rebuild-plan.test.ts
index 314da3052..da5ffd086 100644
--- a/sdk/tests/rebuild-plan.test.ts
+++ b/sdk/tests/rebuild-plan.test.ts
@@ -13,10 +13,14 @@ import { describe, it, expect } from 'vitest';
import { rebuildPlan } from '../src/asset/dependencies';
import type { AssetIdentity } from '../src/asset/dependencies';
-/** A reverse graph as a table: what depends on (path, type). */
+/** A reverse graph as a table: the file's readers under its path, and each
+ * asset's acquirers under `type:path`. */
function graph(edges: Record<string, AssetIdentity[]>) {
- return (path: string, type?: string): readonly AssetIdentity[] =>
- edges[type === undefined ? path : `${type}:${path}`] ?? [];
+ return {
+ ofSource: (path: string): readonly AssetIdentity[] => edges[path] ?? [],
+ ofAsset: (asset: AssetIdentity): readonly AssetIdentity[] =>
+ edges[`${asset.type}:${asset.path}`] ?? [],
+ };
}
describe('a rebuild plan is over assets, not over paths', () => {