diff --git a/apps/editor/lib/local-asset-gc.test.ts b/apps/editor/lib/local-asset-gc.test.ts new file mode 100644 index 0000000000..a3c0c62be6 --- /dev/null +++ b/apps/editor/lib/local-asset-gc.test.ts @@ -0,0 +1,181 @@ +import 'fake-indexeddb/auto' +import { describe, expect, test } from 'bun:test' +import { deleteAsset, loadAssetUrl, saveAsset } from '@pascal-app/core' +import { collectNodeAssetUrlList, runLocalAssetGc } from './local-asset-gc' + +type FetchHandler = (url: string) => Response | Promise + +function mockFetch(handler: FetchHandler): () => void { + const original = globalThis.fetch + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input.toString() + return handler(url) + }) as typeof fetch + return () => { + globalThis.fetch = original + } +} + +function json(body: unknown, ok = true, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }) +} + +describe('local-asset-gc collectors', () => { + test('collectNodeAssetUrlList walks url and src', () => { + const urls = collectNodeAssetUrlList({ + a: { url: 'asset://guide' }, + b: { src: 'asset://model' }, + c: { src: 'https://cdn.example.com/x.glb' }, + }) + expect(urls.sort()).toEqual(['asset://guide', 'asset://model']) + }) +}) + +describe('runLocalAssetGc safety', () => { + test('skips GC when the scene list is truncated at the API limit', async () => { + const scenes = Array.from({ length: 500 }, (_, i) => ({ id: `scene-${i}` })) + const restore = mockFetch((url) => { + if (url.includes('/api/scenes?')) return json({ scenes }) + return json({ graph: { nodes: {} } }) + }) + try { + const result = await runLocalAssetGc(() => ({ nodes: {} })) + expect(result).toBeNull() + } finally { + restore() + } + }) + + test('skips GC when listing scenes fails', async () => { + const restore = mockFetch(() => json({ error: 'no' }, false, 500)) + try { + expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull() + } finally { + restore() + } + }) + + test('skips GC when the scene inventory is malformed', async () => { + for (const body of [{}, { scenes: [{ id: null }] }]) { + const restore = mockFetch(() => json(body)) + try { + expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull() + } finally { + restore() + } + } + }) + + test('skips GC when a listed scene has no graph', async () => { + const restore = mockFetch((url) => + url.includes('/api/scenes?') ? json({ scenes: [{ id: 'scene-1' }] }) : json({}), + ) + try { + expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull() + } finally { + restore() + } + }) + + test('skips a graph with a missing or malformed node map', async () => { + const asset = await saveAsset(new File(['keep'], 'keep.txt')) + try { + for (const graph of [{}, { nodes: null }, { nodes: [] }]) { + const restore = mockFetch((url) => + url.includes('/api/scenes?') ? json({ scenes: [{ id: 'scene-1' }] }) : json({ graph }), + ) + try { + expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull() + expect(await loadAssetUrl(asset)).not.toBeNull() + } finally { + restore() + } + } + } finally { + await deleteAsset(asset) + } + }) + + test('keeps deeply nested references and references outside nodes and materials', async () => { + const deepAsset = await saveAsset(new File(['deep'], 'deep.txt')) + const collectionAsset = await saveAsset(new File(['collection'], 'collection.txt')) + let nested: unknown = deepAsset + for (let depth = 0; depth < 12; depth++) nested = { nested } + const graph = { nodes: { plugin: { nested } }, collections: { preview: collectionAsset } } + const restore = mockFetch((url) => + url.includes('/api/scenes?') ? json({ scenes: [{ id: 'scene-1' }] }) : json({ graph }), + ) + try { + await runLocalAssetGc(() => ({ nodes: {} })) + expect(await loadAssetUrl(deepAsset)).not.toBeNull() + expect(await loadAssetUrl(collectionAsset)).not.toBeNull() + } finally { + restore() + await deleteAsset(deepAsset) + await deleteAsset(collectionAsset) + } + }) + + test('skips GC when the local scene cannot be parsed', async () => { + const previous = Object.getOwnPropertyDescriptor(globalThis, 'localStorage') + Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + value: { getItem: () => '{not-json' }, + }) + const restore = mockFetch(() => json({ scenes: [] })) + try { + expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull() + } finally { + restore() + if (previous) Object.defineProperty(globalThis, 'localStorage', previous) + else Reflect.deleteProperty(globalThis, 'localStorage') + } + }) + + test('re-reads live nodes so mid-GC uploads stay in the keep-set', async () => { + // Live graph is empty when GC starts, then gains a guide during the + // per-scene fetch — the File must survive the sweep. + let live: Record = {} + const lateAsset = 'asset://uploaded-mid-gc' + const restore = mockFetch(async (url) => { + if (url.includes('/api/scenes?')) { + // Simulate latency while the user uploads. + live = { guide: { url: lateAsset } } + return json({ scenes: [] }) + } + return json({ graph: { nodes: {} } }) + }) + try { + const result = await runLocalAssetGc(() => ({ nodes: live })) + // Keep-set included the late upload, so sweep ran but did not need to + // delete it (result is a count of removals — File itself is not present + // in this unit test's IDB; the contract is "keep-set includes live URLs"). + expect(result).not.toBeNull() + expect(collectNodeAssetUrlList(live)).toContain(lateAsset) + } finally { + restore() + } + }) + + test('keeps a material texture added to the live graph during inventory', async () => { + const assetUrl = await saveAsset(new File(['texture'], 'texture.png')) + let materials: unknown = {} + const restore = mockFetch((url) => { + if (url.includes('/api/scenes?')) { + materials = { floor: { texture: { url: assetUrl } } } + return json({ scenes: [] }) + } + return json({ graph: { nodes: {} } }) + }) + try { + await runLocalAssetGc(() => ({ nodes: {}, materials })) + expect(await loadAssetUrl(assetUrl)).not.toBeNull() + } finally { + restore() + await deleteAsset(assetUrl) + } + }) +}) diff --git a/apps/editor/lib/local-asset-gc.ts b/apps/editor/lib/local-asset-gc.ts new file mode 100644 index 0000000000..599785ddf1 --- /dev/null +++ b/apps/editor/lib/local-asset-gc.ts @@ -0,0 +1,132 @@ +import { + collectLocalAssetUrls, + collectNodeAssetUrls, + sweepLocalAssetsExcept, +} from '@pascal-app/core' + +const LOCAL_STORAGE_SCENE_KEY = 'pascal-editor-scene' +/** Must match apps/editor/app/api/scenes/route.ts listQuerySchema max. */ +const SCENES_LIST_MAX = 500 + +type SceneGraphLike = { + nodes?: Record + materials?: unknown +} + +function collectGraphAssetUrls(graph: unknown): string[] | null { + if (!graph || typeof graph !== 'object' || !('nodes' in graph)) return null + const nodes = graph.nodes + if (!nodes || typeof nodes !== 'object' || Array.isArray(nodes)) return null + return collectLocalAssetUrls(graph) +} + +/** Asset URLs still referenced by the browser's localStorage scene, if any. */ +export function collectLocalStorageSceneAssetUrls(): string[] | null { + if (typeof localStorage === 'undefined') return [] + try { + const raw = localStorage.getItem(LOCAL_STORAGE_SCENE_KEY) + if (raw === null) return [] + return collectGraphAssetUrls(JSON.parse(raw)) + } catch { + return null + } +} + +/** + * Union of asset URLs across every graph this origin can still open. + * Returns null when the inventory cannot be proven complete — callers must + * skip GC rather than sweep from a partial keep-set. + */ +export async function collectAllPersistedAssetUrls( + currentGraph: SceneGraphLike, +): Promise { + const currentUrls = collectGraphAssetUrls(currentGraph) + if (currentUrls === null) return null + const keep = new Set(currentUrls) + const localUrls = collectLocalStorageSceneAssetUrls() + if (localUrls === null) return null + for (const url of localUrls) keep.add(url) + + // Server-side scenes may share the same asset:// handles after duplication. + // If listing fails or is truncated we cannot prove the keep-set is complete. + let scenesJson: { data?: { scenes?: unknown[] }; scenes?: unknown[] } | null = null + try { + const res = await fetch(`/api/scenes?limit=${SCENES_LIST_MAX}`) + if (!res.ok) return null + scenesJson = (await res.json()) as { + data?: { scenes?: unknown[] } + scenes?: unknown[] + } + } catch { + return null + } + + const list = scenesJson?.data?.scenes ?? scenesJson?.scenes + if (!Array.isArray(list)) return null + // The API has no cursor/total. A full page means older scenes were dropped + // by `limit` — treating it as complete would delete their Files. + if (list.length >= SCENES_LIST_MAX) return null + + for (const entry of list) { + const id = (entry as { id?: unknown } | null)?.id + if (typeof id !== 'string' || !id) return null + try { + const res = await fetch(`/api/scenes/${encodeURIComponent(id)}`) + if (!res.ok) return null + const body = (await res.json()) as { + data?: { graph?: SceneGraphLike; scene?: { graph?: SceneGraphLike } } + graph?: SceneGraphLike + } + const graph = body.data?.graph ?? body.data?.scene?.graph ?? body.graph ?? null + const urls = collectGraphAssetUrls(graph) + if (urls === null) return null + for (const url of urls) keep.add(url) + } catch { + return null + } + } + + return [...keep] +} + +/** + * Explicit GC: delete IndexedDB Files that no persisted scene references. + * + * **Do not call this from scene mount / load.** Automatic mount-time GC races + * keepalive flushes, other tabs, and uploads that have hit IndexedDB but are + * not yet on a node; a sequential GET per scene also burns the shared API rate + * bucket used by autosave (#733 review). Call only when the host can prove: + * no in-flight writes, a complete scene inventory, and spare rate budget. + * Pass references from any other recoverable snapshots in extraKeepUrls. + * + * `getLiveGraph` is re-read immediately before sweeping so both nodes and + * unsaved material texture references survive. + * No-ops when the full keep-set cannot be built (never partial-sweeps). + */ +export async function runLocalAssetGc( + getLiveGraph: () => SceneGraphLike, + extraKeepUrls: Iterable = [], +): Promise { + const keep = await collectAllPersistedAssetUrls(getLiveGraph()) + if (keep === null) return null + + const finalKeep = new Set(keep) + const liveUrls = collectGraphAssetUrls(getLiveGraph()) + if (liveUrls === null) return null + for (const url of liveUrls) { + finalKeep.add(url) + } + for (const url of extraKeepUrls) { + if (typeof url === 'string' && url.startsWith('asset://')) finalKeep.add(url) + } + return sweepLocalAssetsExcept(finalKeep) +} + +/** For tests: collect urls from an arbitrary node map. */ +export function collectNodeAssetUrlList(nodes: Record): string[] { + const urls: string[] = [] + for (const node of Object.values(nodes)) { + urls.push(...collectNodeAssetUrls(node as never)) + } + return urls +} diff --git a/apps/editor/package.json b/apps/editor/package.json index 92cb0c7d77..4fac5f0769 100644 --- a/apps/editor/package.json +++ b/apps/editor/package.json @@ -54,6 +54,7 @@ "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "agentation": "^3.1.2", + "fake-indexeddb": "^6.2.6", "react-grab": "^0.2.0", "react-scan": "^0.5.7", "typescript": "7.0.2" diff --git a/bun.lock b/bun.lock index 0520ddb77b..11c64c6aad 100644 --- a/bun.lock +++ b/bun.lock @@ -81,6 +81,7 @@ "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "agentation": "^3.1.2", + "fake-indexeddb": "^6.2.6", "react-grab": "^0.2.0", "react-scan": "^0.5.7", "typescript": "7.0.2", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c13bdf7de5..0eca190601 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -137,7 +137,13 @@ export { type ResolvedAssemblyLayer, resolveAssemblyStack, } from './lib/assembly-stack' -export { loadAssetUrl, saveAsset } from './lib/asset-storage' +export { + deleteAsset, + listLocalAssetUrls, + loadAssetUrl, + saveAsset, + sweepLocalAssetsExcept, +} from './lib/asset-storage' export { BEAM_MATERIAL_LABELS, BEAM_MATERIAL_LIBRARY_REFS, @@ -491,6 +497,12 @@ export { roomClearPolygon, } from './lib/level-footprints' export { getDefaultLevelName, getLevelDisplayName } from './lib/level-name' +export { + collectGraphAssetUrlsFromParts, + collectLocalAssetUrls, + collectNodeAssetUrls, + collectSceneAssetUrls, +} from './lib/local-asset-lifecycle' export { areMeasurementPointsCoplanar, closestMeasurementFeatureBinding, diff --git a/packages/core/src/lib/asset-storage.test.ts b/packages/core/src/lib/asset-storage.test.ts index 97889f1c12..6ec54d6c75 100644 --- a/packages/core/src/lib/asset-storage.test.ts +++ b/packages/core/src/lib/asset-storage.test.ts @@ -1,6 +1,16 @@ import 'fake-indexeddb/auto' import { afterEach, describe, expect, test } from 'bun:test' -import { loadAssetUrl, saveAsset } from './asset-storage' +import { get, set } from 'idb-keyval' +import { + deleteAsset, + listLocalAssetUrls, + loadAssetUrl, + randomId, + saveAsset, + sweepLocalAssetsExcept, +} from '../index' + +const ASSET_PREFIX = 'asset_data:' function file(contents: string, name = 'test.txt'): File { return new File([contents], name, { type: 'text/plain' }) @@ -69,3 +79,58 @@ describe('loadAssetUrl', () => { expect(await loadAssetUrl('/assets/x.png')).toBe('/assets/x.png') }) }) + +describe('deleteAsset', () => { + test('removes the IndexedDB entry so later loads miss', async () => { + const url = await saveAsset(file('delete-me')) + expect(await loadAssetUrl(url)).not.toBeNull() + + expect(await deleteAsset(url)).toBe(true) + expect(await loadAssetUrl(url)).toBeNull() + }) + + test('ignores non-asset URLs', async () => { + expect(await deleteAsset('https://cdn.example.com/a.glb')).toBe(false) + expect(await deleteAsset('')).toBe(false) + }) +}) + +describe('local asset record formats', () => { + test('lists and deletes legacy Files and versioned byte records without touching other keys', async () => { + const legacyId = randomId() + const bytesId = randomId() + const otherKey = `other:${randomId()}` + const legacyUrl = `asset://${legacyId}` + const bytesUrl = `asset://${bytesId}` + const bytes = new TextEncoder().encode('portable').buffer + const record = { assetVersion: 1, bytes, type: 'text/plain' } + await set(`${ASSET_PREFIX}${legacyId}`, file('legacy')) + await set(`${ASSET_PREFIX}${bytesId}`, record) + await set(otherKey, 'unrelated') + + const urls = await listLocalAssetUrls() + expect(urls).toContain(legacyUrl) + expect(urls).toContain(bytesUrl) + expect(urls).not.toContain(`asset://${otherKey}`) + expect(await deleteAsset(legacyUrl)).toBe(true) + expect(await get(`${ASSET_PREFIX}${legacyId}`)).toBeUndefined() + expect(await get(`${ASSET_PREFIX}${bytesId}`)).toEqual(record) + expect(await deleteAsset(bytesUrl)).toBe(true) + expect(await get(`${ASSET_PREFIX}${bytesId}`)).toBeUndefined() + expect(await get(otherKey)).toBe('unrelated') + }) + + test('preserves referenced byte records during an explicit sweep', async () => { + const keepId = randomId() + const orphanId = randomId() + const record = { assetVersion: 1, bytes: new Uint8Array([1, 2, 3]).buffer, type: 'image/png' } + await set(`${ASSET_PREFIX}${keepId}`, record) + await set(`${ASSET_PREFIX}${orphanId}`, record) + const keep = (await listLocalAssetUrls()).filter((url) => url !== `asset://${orphanId}`) + + expect(await sweepLocalAssetsExcept(keep)).toBe(1) + expect(await get(`${ASSET_PREFIX}${keepId}`)).toEqual(record) + expect(await get(`${ASSET_PREFIX}${orphanId}`)).toBeUndefined() + await deleteAsset(`asset://${keepId}`) + }) +}) diff --git a/packages/core/src/lib/asset-storage.ts b/packages/core/src/lib/asset-storage.ts index ff4ed61cb6..c2fcf25f47 100644 --- a/packages/core/src/lib/asset-storage.ts +++ b/packages/core/src/lib/asset-storage.ts @@ -1,4 +1,4 @@ -import { get, set } from 'idb-keyval' +import { del, get, keys, set } from 'idb-keyval' import { isSchemeRelativeUrl } from '../schema/asset-url' import { ARTIFACT_URL_PREFIX, resolveArtifactUrl } from './artifact-store' import { randomId } from './random-id' @@ -8,6 +8,19 @@ export const ASSET_PREFIX = 'asset_data:' // Cache for active object URLs to prevent leaks and flickering const urlCache = new Map() +function assetIdFromUrl(url: string): string | null { + if (!url.startsWith('asset://')) return null + return url.replace('asset://', '') || null +} + +function revokeCachedObjectUrl(id: string) { + const objectUrl = urlCache.get(id) + if (objectUrl) { + URL.revokeObjectURL(objectUrl) + urlCache.delete(id) + } +} + /** * Save a file to IndexedDB and return a custom protocol URL */ @@ -59,3 +72,67 @@ export async function loadAssetUrl(url: string): Promise { // Legacy data URLs are returned as is return url } + +/** + * Delete a locally stored `asset://` file from IndexedDB and drop any cached + * object URL. No-op for non-asset URLs. + * + * Callers must only invoke this when no *persisted* scene still references + * the URL — IndexedDB is origin-global and not scoped by project (#733). + */ +export async function deleteAsset(url: string): Promise { + const id = assetIdFromUrl(url) + if (!id) return false + revokeCachedObjectUrl(id) + try { + await del(`${ASSET_PREFIX}${id}`) + return true + } catch (error) { + console.error('Failed to delete asset:', error) + return false + } +} + +/** Every `asset://` id currently stored in IndexedDB. */ +export async function listLocalAssetUrls(): Promise { + try { + const allKeys = await keys() + const urls: string[] = [] + for (const key of allKeys) { + if (typeof key === 'string' && key.startsWith(ASSET_PREFIX)) { + urls.push(`asset://${key.slice(ASSET_PREFIX.length)}`) + } + } + return urls + } catch (error) { + console.error('Failed to list local assets:', error) + return [] + } +} + +/** + * Explicit garbage collection: delete every local asset URL not in + * `keepUrls`. + * + * `keepUrls` MUST be the union of asset references across **every persisted + * graph** the origin can still open (current scene, localStorage scene, + * server scenes). A keep-set built from only the active graph will corrupt + * other projects that share an `asset://` handle after duplication (#733). + */ +export async function sweepLocalAssetsExcept(keepUrls: Iterable): Promise { + const keep = new Set() + for (const url of keepUrls) { + if (typeof url === 'string' && url.startsWith('asset://')) keep.add(url) + } + + let removed = 0 + try { + for (const url of await listLocalAssetUrls()) { + if (keep.has(url)) continue + if (await deleteAsset(url)) removed += 1 + } + } catch (error) { + console.error('Failed to sweep local assets:', error) + } + return removed +} diff --git a/packages/core/src/lib/local-asset-lifecycle.test.ts b/packages/core/src/lib/local-asset-lifecycle.test.ts new file mode 100644 index 0000000000..c53bea38a5 --- /dev/null +++ b/packages/core/src/lib/local-asset-lifecycle.test.ts @@ -0,0 +1,100 @@ +import 'fake-indexeddb/auto' +import { describe, expect, test } from 'bun:test' +import { + listLocalAssetUrls, + loadAssetUrl, + saveAsset, + sweepLocalAssetsExcept, +} from './asset-storage' +import { + collectGraphAssetUrlsFromParts, + collectNodeAssetUrls, + collectSceneAssetUrls, +} from './local-asset-lifecycle' + +function file(contents: string, name = 'test.txt'): File { + return new File([contents], name, { type: 'text/plain' }) +} + +describe('collectNodeAssetUrls', () => { + test('collects url and src asset:// references', () => { + const urls = [ + ...collectNodeAssetUrls({ id: 'a', type: 'guide', url: 'asset://guide-1' } as never), + ...collectNodeAssetUrls({ id: 'b', type: 'item', src: 'asset://model-1' } as never), + ...collectNodeAssetUrls({ + id: 'c', + type: 'item', + src: 'https://cdn.example.com/x.glb', + } as never), + ] + expect(urls.sort()).toEqual(['asset://guide-1', 'asset://model-1']) + }) + + test('collects nested item.asset and captureSession URLs', () => { + const urls = collectNodeAssetUrls({ + id: 'item1', + type: 'item', + asset: { src: 'asset://chair.glb', thumbnail: 'asset://chair.png' }, + extra: { nested: { ref: 'asset://deep' } }, + } as never) + expect(urls.sort()).toEqual(['asset://chair.glb', 'asset://chair.png', 'asset://deep']) + }) +}) + +describe('collectSceneAssetUrls', () => { + test('walks url and src across nodes', () => { + const urls = collectSceneAssetUrls({ + a: { id: 'a', type: 'guide', url: 'asset://g' } as never, + b: { id: 'b', type: 'item', src: 'asset://s' } as never, + }) + expect(urls.sort()).toEqual(['asset://g', 'asset://s']) + }) +}) + +describe('collectGraphAssetUrlsFromParts', () => { + test('includes materials texture maps', () => { + const urls = collectGraphAssetUrlsFromParts( + { guide: { id: 'guide', type: 'guide', url: 'asset://g' } } as never, + { + mat1: { + url: 'asset://tex-albedo', + albedoMap: 'asset://albedo', + maps: [{ url: 'asset://map-0' }], + }, + }, + ) + expect(urls.sort()).toEqual([ + 'asset://albedo', + 'asset://g', + 'asset://map-0', + 'asset://tex-albedo', + ]) + }) +}) + +describe('sweepLocalAssetsExcept', () => { + test('keeps assets referenced by any persisted scene in the keep-set', async () => { + const shared = await saveAsset(file('shared-by-two-scenes')) + const orphan = await saveAsset(file('orphan')) + + // Simulate two persisted scenes sharing `shared`. + const sceneA = collectSceneAssetUrls({ + guide: { id: 'guide', type: 'guide', url: shared } as never, + }) + const sceneB = collectSceneAssetUrls({ + scan: { id: 'scan', type: 'scan', url: shared } as never, + }) + const removed = await sweepLocalAssetsExcept([...sceneA, ...sceneB]) + + expect(removed).toBeGreaterThanOrEqual(1) + expect(await loadAssetUrl(shared)).not.toBeNull() + expect(await loadAssetUrl(orphan)).toBeNull() + expect((await listLocalAssetUrls()).includes(orphan)).toBe(false) + }) + + test('deletes Files referenced only by nothing', async () => { + const url = await saveAsset(file('unreferenced')) + await sweepLocalAssetsExcept([]) + expect(await loadAssetUrl(url)).toBeNull() + }) +}) diff --git a/packages/core/src/lib/local-asset-lifecycle.ts b/packages/core/src/lib/local-asset-lifecycle.ts new file mode 100644 index 0000000000..e9763715ff --- /dev/null +++ b/packages/core/src/lib/local-asset-lifecycle.ts @@ -0,0 +1,43 @@ +import type { AnyNode } from '../schema' + +/** + * Local `asset://` reference collection. + * + * IndexedDB is origin-global and not scoped by scene. Physical deletion must + * only happen via an explicit GC that unions references from **every + * persisted graph** (see `sweepLocalAssetsExcept` in asset-storage). This + * module never deletes Files (#733 review). + */ +export const ASSET_URL_PREFIX = 'asset://' + +/** Collect local references from JSON-shaped scene data, including plugin fields. */ +export function collectLocalAssetUrls(value: unknown): string[] { + const pending: unknown[] = [value] + const urls: string[] = [] + const seen = new WeakSet() + while (pending.length > 0) { + const current = pending.pop() + if (typeof current === 'string' && current.startsWith(ASSET_URL_PREFIX)) { + urls.push(current) + } else if (current !== null && typeof current === 'object' && !seen.has(current)) { + seen.add(current) + for (const child of Object.values(current)) pending.push(child) + } + } + return urls +} + +export function collectNodeAssetUrls(node: AnyNode | undefined): string[] { + return collectLocalAssetUrls(node) +} + +export function collectSceneAssetUrls(nodes: Record): string[] { + return collectLocalAssetUrls(nodes) +} + +export function collectGraphAssetUrlsFromParts( + nodes: Record | undefined, + materials: unknown, +): string[] { + return collectLocalAssetUrls([nodes, materials]) +} diff --git a/packages/editor/src/lib/local-asset-lifecycle.ts b/packages/editor/src/lib/local-asset-lifecycle.ts new file mode 100644 index 0000000000..68de4278d8 --- /dev/null +++ b/packages/editor/src/lib/local-asset-lifecycle.ts @@ -0,0 +1,6 @@ +/** + * Re-export local asset helpers. + * Physical deletion lives in an explicit multi-scene GC + * (`sweepLocalAssetsExcept`) — never from a single active graph (#733). + */ +export { collectNodeAssetUrls, collectSceneAssetUrls } from '@pascal-app/core'