@hyperframes/studio 0.8.212 → 0.8.213

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/player.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Player
3
- } from "./chunk-HD6NXWGI.js";
3
+ } from "./chunk-UNZTUFD7.js";
4
4
  import "./chunk-7HZGKFFU.js";
5
5
  import "./chunk-OGIOFEC7.js";
6
6
  import "./chunk-MLKGABMK.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/studio",
3
- "version": "0.8.212",
3
+ "version": "0.8.213",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -60,12 +60,12 @@
60
60
  "dockview-react": "8.3.1",
61
61
  "gsap": "^3.13.0",
62
62
  "mediabunny": "^1.45.3",
63
- "@hyperframes/parsers": "0.8.212",
64
- "@hyperframes/core": "0.8.212",
65
- "@hyperframes/player": "0.8.212",
66
- "@hyperframes/sdk": "0.8.212",
67
- "@hyperframes/shader-transitions": "0.8.212",
68
- "@hyperframes/studio-server": "0.8.212"
63
+ "@hyperframes/core": "0.8.213",
64
+ "@hyperframes/player": "0.8.213",
65
+ "@hyperframes/parsers": "0.8.213",
66
+ "@hyperframes/sdk": "0.8.213",
67
+ "@hyperframes/shader-transitions": "0.8.213",
68
+ "@hyperframes/studio-server": "0.8.213"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@tailwindcss/vite": "^4.3.3",
@@ -82,7 +82,7 @@
82
82
  "vite": "^6.4.2",
83
83
  "vitest": "^4.1.11",
84
84
  "zustand": "^5.0.0",
85
- "@hyperframes/producer": "0.8.212"
85
+ "@hyperframes/producer": "0.8.213"
86
86
  },
87
87
  "peerDependencies": {
88
88
  "react": "19",
@@ -414,6 +414,31 @@ describe("persistTimelineBatchEdit", () => {
414
414
  ).rejects.toThrow("Unable to patch timeline element ghost in index.html");
415
415
  expect(writes).toHaveLength(0);
416
416
  });
417
+
418
+ it("names which lookups a missing clip had, never their values", async () => {
419
+ stubReadFileContent(SOURCE);
420
+ // As the timeline builds them: a clip with an id also carries `#id` as its selector.
421
+ const missing = (element: Partial<TimelineElement>) => {
422
+ const change = moveMember("ghost", 3, 0, 2);
423
+ change.element = { ...change.element, ...element };
424
+ return persistTimelineBatchEdit(batchInput([change], []));
425
+ };
426
+ await expect(
427
+ missing({
428
+ domId: "intro__hf2",
429
+ hfId: "hf-zz9q",
430
+ selector: "#intro__hf2",
431
+ sourceFile: "compositions/intro.html",
432
+ }),
433
+ ).rejects.toThrow("(by hf-id, runtime-renamed id; file from the clip)");
434
+ await expect(missing({ selector: "#ghost" })).rejects.toThrow("(by id; no file on the clip)");
435
+ await expect(
436
+ missing({ domId: undefined, selector: ".caption", selectorIndex: 4 }),
437
+ ).rejects.toThrow("(by class; no file on the clip)");
438
+ await expect(
439
+ missing({ domId: undefined, selector: '[data-composition-id="intro__hf2"]' }),
440
+ ).rejects.toThrow("(by runtime-renamed composition id; no file on the clip)");
441
+ });
417
442
  });
418
443
 
419
444
  describe("persistTimelineEdit", () => {
@@ -387,6 +387,20 @@ export function operationChanges(
387
387
  }));
388
388
  }
389
389
 
390
+ const RENAMED_MOUNT = /__hf\d+"?\]?$/;
391
+ const lookup = (value: string, kind: string) =>
392
+ RENAMED_MOUNT.test(value) ? `runtime-renamed ${kind}` : kind;
393
+ const selectorLookup = (selector: string) =>
394
+ selector.startsWith("[data-composition-id=")
395
+ ? lookup(selector, "composition id")
396
+ : /^\.[\w-]+$/.test(selector) && "class";
397
+
398
+ function missedLookups(element: Pick<TimelineElement, "sourceFile">, target: PatchTarget): string {
399
+ const kinds = [target.hfId && "hf-id", target.id && lookup(target.id, "id")];
400
+ const by = [...kinds, target.selector && selectorLookup(target.selector)].filter(Boolean);
401
+ return `by ${by.join(", ") || "nothing"}; ${element.sourceFile ? "file from the clip" : "no file on the clip"}`;
402
+ }
403
+
390
404
  /** Patches each change into `source`, failing loudly on a target the file does not hold. */
391
405
  export function patchTimelineChangesInSource(
392
406
  source: string,
@@ -399,7 +413,9 @@ export function patchTimelineChangesInSource(
399
413
  if (!target) throw new Error(`Timeline element ${element.id} is missing a patchable target`);
400
414
  // Resolve first: a member already at its target values patches to the same string, a missing one must throw.
401
415
  if (!findTagByTarget(current, target)) {
402
- throw new Error(`Unable to patch timeline element ${element.id} in ${targetPath}`);
416
+ throw new Error(
417
+ `Unable to patch timeline element ${element.id} in ${targetPath} (${missedLookups(element, target)})`,
418
+ );
403
419
  }
404
420
  current = buildPatches(current, target);
405
421
  }
@@ -128,6 +128,46 @@ describe("preview quality messages", () => {
128
128
  expect(usePlayerStore.getState().previewFacts).toBeNull();
129
129
  });
130
130
 
131
+ it("keeps each failed media load the preview reports, and ignores other diagnostics", () => {
132
+ const details = {
133
+ asset: "assets/x.mp3",
134
+ elementId: "music",
135
+ kind: "audio",
136
+ stage: "decode",
137
+ code: null,
138
+ bytes: 8,
139
+ extension: "mp3",
140
+ };
141
+ routeMessage({
142
+ source: "hf-preview",
143
+ type: "diagnostic",
144
+ code: "runtime_media_load_failed",
145
+ details,
146
+ });
147
+ expect(usePlayerStore.getState().mediaLoadFailure).toEqual({
148
+ elementId: "music",
149
+ kind: "audio",
150
+ stage: "decode",
151
+ code: null,
152
+ bytes: 8,
153
+ extension: "mp3",
154
+ });
155
+ const kept = usePlayerStore.getState().mediaLoadFailure;
156
+ routeMessage({
157
+ source: "hf-preview",
158
+ type: "diagnostic",
159
+ code: "runtime_web_audio_bypass",
160
+ details,
161
+ });
162
+ routeMessage({
163
+ source: "hf-preview",
164
+ type: "diagnostic",
165
+ code: "runtime_media_load_failed",
166
+ details: { ...details, stage: "?" },
167
+ });
168
+ expect(usePlayerStore.getState().mediaLoadFailure).toBe(kept);
169
+ });
170
+
131
171
  it("sends the chosen quality to a preview that has just loaded", () => {
132
172
  usePlayerStore.getState().setPreviewQuality(0.25);
133
173
  const postMessage = vi.fn();
@@ -13,6 +13,10 @@ import { usePlayerStore, type TimelineElement } from "../store/playerStore";
13
13
  import type { ClipManifestClip, IframeWindow, PlaybackAdapter } from "../lib/playbackTypes";
14
14
  import { hasTimelinePerformanceFixtureLease } from "../lib/timelinePerformanceFixture";
15
15
  import { acceptStudioRuntimeMessage, postRuntimeControlMessage } from "../lib/runtimeProtocol";
16
+ import {
17
+ parseMediaLoadFailure,
18
+ RUNTIME_MEDIA_LOAD_FAILED,
19
+ } from "@hyperframes/core/runtime/protocol";
16
20
  import {
17
21
  parsePlaybackHealth,
18
22
  parsePreviewCopies,
@@ -38,6 +42,8 @@ interface PreviewMessage {
38
42
  copies?: unknown;
39
43
  health?: unknown;
40
44
  facts?: unknown;
45
+ code?: unknown;
46
+ details?: unknown;
41
47
  }
42
48
 
43
49
  export interface PreviewMessageRouterDeps {
@@ -136,6 +142,12 @@ function applyStoreReport(data: PreviewMessage): boolean {
136
142
  case "preview-facts":
137
143
  store.setPreviewFacts(parsePreviewFacts(data.facts));
138
144
  return true;
145
+ case "diagnostic": {
146
+ if (data.code !== RUNTIME_MEDIA_LOAD_FAILED) return false;
147
+ const failure = parseMediaLoadFailure(data.details);
148
+ if (failure) store.setMediaLoadFailure(failure);
149
+ return true;
150
+ }
139
151
  default:
140
152
  return false;
141
153
  }
@@ -177,6 +177,9 @@ export function mediaUrlSourceOptions(reader: MediaReader) {
177
177
  const failuresByStart = new Map<number | null, number>();
178
178
  const inFlightReads = new AbortController();
179
179
  let ranges: "unknown" | "readable" | "hidden" = reader === "thumbnail" ? "unknown" : "hidden";
180
+ let etag: string | undefined;
181
+ const noteEtag = (response: Response) =>
182
+ void (etag ??= response.headers.get("ETag") ?? undefined);
180
183
  const fetchFn = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
181
184
  const sent = ranges === "readable" ? boundedRange(init) : init;
182
185
  const asked = Number(rangeStart(sent, true) ?? 0);
@@ -187,6 +190,7 @@ export function mediaUrlSourceOptions(reader: MediaReader) {
187
190
  );
188
191
  const response = await typedFetch(reader, input, sent ?? {}, asked, request);
189
192
  if (ranges !== "hidden") ranges = rangesReadable(sent, response) ? "readable" : "hidden";
193
+ noteEtag(response);
190
194
  return typedResponse(response, asked, request);
191
195
  };
192
196
  const getRetryDelay = (_previousAttempts: number, error: unknown): number | null => {
@@ -201,8 +205,9 @@ export function mediaUrlSourceOptions(reader: MediaReader) {
201
205
  };
202
206
  const cancelReads = () =>
203
207
  inFlightReads.abort(new DOMException("Media reads cancelled", "AbortError"));
204
- if (reader === "probe") return { fetchFn, getRetryDelay, cancelReads };
205
- return { fetchFn, getRetryDelay, cancelReads, maxCacheSize: POOLED_READER_CACHE_BYTES };
208
+ const etagOf = () => etag;
209
+ if (reader === "probe") return { fetchFn, getRetryDelay, cancelReads, etagOf };
210
+ return { fetchFn, getRetryDelay, cancelReads, etagOf, maxCacheSize: POOLED_READER_CACHE_BYTES };
206
211
  }
207
212
 
208
213
  export function reportMediaFetchFailure(error: unknown): void {
@@ -0,0 +1,158 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import {
5
+ readStoredFrame,
6
+ readStoredInfo,
7
+ rememberVersion,
8
+ resetStoredThumbnailsForTests,
9
+ STORED_THUMBNAIL_BYTES,
10
+ storedVersion,
11
+ storeFrame,
12
+ storeInfo,
13
+ } from "./thumbnailDiskCache";
14
+
15
+ /** Cache Storage as a Map of Maps: what a browser keeps across sessions. */
16
+ function fakeCacheStorage() {
17
+ const stores = new Map<string, Map<string, Response>>();
18
+ const storage = {
19
+ open: async (name: string) => {
20
+ const store = stores.get(name) ?? new Map<string, Response>();
21
+ stores.set(name, store);
22
+ return {
23
+ match: async (url: string) => store.get(String(url))?.clone(),
24
+ put: async (url: string, response: Response) => void store.set(String(url), response),
25
+ };
26
+ },
27
+ has: async (name: string) => stores.has(name),
28
+ keys: async () => [...stores.keys()],
29
+ delete: async (name: string) => stores.delete(name),
30
+ };
31
+ return { storage, stores };
32
+ }
33
+
34
+ const v1 = { source: "/media/take.mp4", etag: '"one"' };
35
+ const v2 = { source: "/media/take.mp4", etag: '"two"' };
36
+ // a picture that reports `bytes` without holding them, so the budget test needs no real 128 MB
37
+ function jpeg(bytes = 5): Blob {
38
+ const blob = new Blob([new Uint8Array(Math.min(bytes, 5))], { type: "image/jpeg" });
39
+ return Object.defineProperty(blob, "size", { value: bytes });
40
+ }
41
+
42
+ let stores: Map<string, Map<string, Response>>;
43
+
44
+ beforeEach(() => {
45
+ resetStoredThumbnailsForTests();
46
+ localStorage.clear();
47
+ const fake = fakeCacheStorage();
48
+ stores = fake.stores;
49
+ vi.stubGlobal("caches", fake.storage);
50
+ });
51
+
52
+ afterEach(() => {
53
+ vi.unstubAllGlobals();
54
+ vi.restoreAllMocks();
55
+ });
56
+
57
+ describe("stored thumbnails", () => {
58
+ it("keep a source's facts and each frame with the time it was decoded at", async () => {
59
+ await storeInfo(v1, { aspect: 16 / 9, metadataDuration: 30 });
60
+ await storeFrame(v1, "cover 320x180 2.5", 2.4, jpeg());
61
+
62
+ expect(await readStoredInfo(v1)).toEqual({ aspect: 16 / 9, metadataDuration: 30 });
63
+ const frame = await readStoredFrame(v1, "cover 320x180 2.5");
64
+ expect(frame?.decodedAt).toBe(2.4);
65
+ expect(frame?.blob.size).toBe(5);
66
+ expect(await readStoredFrame(v1, "cover 320x180 5")).toBeUndefined();
67
+ expect(await readStoredFrame(v2, "cover 320x180 2.5")).toBeUndefined();
68
+ });
69
+
70
+ it("are trusted in a new session only when the server answers the stored ETag with a 304", async () => {
71
+ const fetch = vi.fn(async () => new Response(null, { status: 304 }));
72
+ vi.stubGlobal("fetch", fetch);
73
+ expect(await storedVersion(v1.source)).toBeUndefined();
74
+ expect(fetch).not.toHaveBeenCalled();
75
+
76
+ await rememberVersion(v1);
77
+ expect(await storedVersion(v1.source)).toEqual(v1);
78
+ expect(fetch).toHaveBeenCalledWith(v1.source, {
79
+ headers: { Range: "bytes=0-0", "If-None-Match": '"one"' },
80
+ });
81
+ fetch.mockResolvedValueOnce(new Response("x", { status: 206 }));
82
+ expect(await storedVersion(v1.source)).toBeUndefined();
83
+ });
84
+
85
+ it("drop what was stored for a file's earlier version once a new one is read", async () => {
86
+ await rememberVersion(v1);
87
+ await storeFrame(v1, "cover 320x180 1", 1, jpeg());
88
+ await rememberVersion(v2);
89
+
90
+ expect(await readStoredFrame(v1, "cover 320x180 1")).toBeUndefined();
91
+ expect(stores.size).toBe(0);
92
+ });
93
+
94
+ it("drop the least recently used sources once they pass the budget", async () => {
95
+ const big = Math.floor(STORED_THUMBNAIL_BYTES / 2) + 1;
96
+ const others = ["/a.mp4", "/b.mp4", "/c.mp4"].map((source) => ({ source, etag: '"1"' }));
97
+ for (const version of others) {
98
+ await storeFrame(version, "cover 1x1 0", 0, jpeg(big));
99
+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + 1000);
100
+ }
101
+
102
+ expect(await readStoredFrame(others[0]!, "cover 1x1 0")).toBeUndefined();
103
+ expect(await readStoredFrame(others[2]!, "cover 1x1 0")).toBeDefined();
104
+ });
105
+
106
+ it("never fail a thumbnail: a broken store warns once and reads as empty", async () => {
107
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
108
+ vi.stubGlobal("caches", {
109
+ open: async () => {
110
+ throw new DOMException("quota", "QuotaExceededError");
111
+ },
112
+ });
113
+
114
+ expect(await readStoredInfo(v1)).toBeUndefined();
115
+ expect(await storeFrame(v1, "cover 1x1 0", 0, jpeg())).toBeUndefined();
116
+ expect(warn).toHaveBeenCalledTimes(1);
117
+ });
118
+
119
+ it("are skipped where the browser offers no Cache Storage", async () => {
120
+ vi.stubGlobal("caches", undefined);
121
+ expect(await readStoredInfo(v1)).toBeUndefined();
122
+ expect(await storeInfo(v1, { aspect: 1, metadataDuration: 1 })).toBeUndefined();
123
+ });
124
+
125
+ it("count a frame stored again under its name once, so the budget holds", async () => {
126
+ await storeFrame(v1, "cover 1x1 0", 0, jpeg(100));
127
+ await storeFrame(v1, "cover 1x1 0", 0, jpeg(100));
128
+
129
+ await vi.waitFor(() => expect(localStorage.getItem("hf-thumbnails-index")).toContain("bytes"), {
130
+ timeout: 3000,
131
+ });
132
+ const saved = JSON.parse(localStorage.getItem("hf-thumbnails-index")!);
133
+ expect(Object.values(saved.caches)).toMatchObject([{ bytes: 100 }]);
134
+ });
135
+
136
+ it("keep what another tab stored when saving, but not what this tab dropped", async () => {
137
+ await rememberVersion(v1);
138
+ await storeFrame(v1, "cover 1x1 0", 0, jpeg());
139
+ await vi.waitFor(() => expect(localStorage.getItem("hf-thumbnails-index")).toContain("bytes"), {
140
+ timeout: 3000,
141
+ });
142
+ // another tab saves its snapshot: a source of its own, and v1 as it was before this tab moved on
143
+ const other = JSON.parse(localStorage.getItem("hf-thumbnails-index")!);
144
+ other.caches["hf-thumbnails:other:tab"] = { usedAt: Date.now(), bytes: 7 };
145
+ localStorage.setItem("hf-thumbnails-index", JSON.stringify(other));
146
+ const v1Cache = Object.keys(other.caches).find((name) => name !== "hf-thumbnails:other:tab")!;
147
+ await rememberVersion(v2);
148
+ await storeFrame(v2, "cover 1x1 0", 0, jpeg());
149
+
150
+ await vi.waitFor(
151
+ () => expect(localStorage.getItem("hf-thumbnails-index")).not.toContain(v1Cache),
152
+ { timeout: 3000 },
153
+ );
154
+ const saved = JSON.parse(localStorage.getItem("hf-thumbnails-index")!);
155
+ expect(Object.keys(saved.caches)).toContain("hf-thumbnails:other:tab");
156
+ expect(Object.keys(saved.caches)).toHaveLength(2);
157
+ });
158
+ });
@@ -0,0 +1,212 @@
1
+ import type { SourceInfo } from "./thumbnailSourcePool";
2
+
3
+ /** A video as the server serves it now: its URL and the ETag of this version of its file. */
4
+ export interface StoredSource {
5
+ source: string;
6
+ etag: string;
7
+ }
8
+
9
+ interface StoredFrame {
10
+ blob: Blob;
11
+ decodedAt: number;
12
+ }
13
+
14
+ const CACHE_PREFIX = "hf-thumbnails:";
15
+ const INDEX_KEY = "hf-thumbnails-index";
16
+ const ENTRY_ORIGIN = "https://hf-thumbnail.invalid/";
17
+ export const STORED_THUMBNAIL_BYTES = 256 * 1024 * 1024;
18
+
19
+ interface Index {
20
+ etags: Record<string, string>;
21
+ caches: Record<string, { usedAt: number; bytes: number }>;
22
+ }
23
+
24
+ let index: Index | undefined;
25
+ // caches this tab dropped since its last save, which another tab's older snapshot must not bring back
26
+ const dropped = new Set<string>();
27
+ let saveTimer: ReturnType<typeof setTimeout> | undefined;
28
+ let warned = false;
29
+
30
+ const available = () => typeof caches !== "undefined" && typeof crypto?.subtle !== "undefined";
31
+
32
+ /** Disk is a shortcut, never a reason a thumbnail fails: a broken store says so once and is skipped. */
33
+ async function quietly<T>(work: () => Promise<T>): Promise<T | undefined> {
34
+ if (!available()) return undefined;
35
+ try {
36
+ return await work();
37
+ } catch (error) {
38
+ if (!warned) console.warn("[Studio] timeline thumbnails stay in memory:", error);
39
+ warned = true;
40
+ return undefined;
41
+ }
42
+ }
43
+
44
+ async function digest(text: string): Promise<string> {
45
+ const bytes = new Uint8Array(
46
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)),
47
+ );
48
+ return Array.from(bytes.subarray(0, 12), (byte) => byte.toString(16).padStart(2, "0")).join("");
49
+ }
50
+
51
+ const cacheNameOf = async ({ source, etag }: StoredSource) =>
52
+ `${CACHE_PREFIX}${await digest(source)}:${await digest(etag)}`;
53
+
54
+ function savedIndex(): Index | undefined {
55
+ try {
56
+ const saved = JSON.parse(localStorage.getItem(INDEX_KEY) ?? "null") as Index | null;
57
+ return saved?.etags && saved.caches ? saved : undefined;
58
+ } catch {
59
+ return undefined; // expected: no storage (a private window) or a value this version can't read
60
+ }
61
+ }
62
+
63
+ function loadIndex(): Index {
64
+ return (index ??= savedIndex() ?? { etags: {}, caches: {} });
65
+ }
66
+
67
+ type CacheEntry = Index["caches"][string];
68
+
69
+ /** Another tab's entry when it was used later than this tab's, with the larger count of bytes. */
70
+ function laterOf(own: CacheEntry | undefined, theirs: CacheEntry): CacheEntry | undefined {
71
+ if (own && own.usedAt >= theirs.usedAt) return undefined;
72
+ return { usedAt: theirs.usedAt, bytes: Math.max(theirs.bytes, own?.bytes ?? 0) };
73
+ }
74
+
75
+ /** This tab's index with what other tabs saved since: each cache at its latest use, none this tab dropped. */
76
+ function mergedIndex(): Index {
77
+ const mine = loadIndex();
78
+ const theirs = savedIndex() ?? { etags: {}, caches: {} };
79
+ for (const [name, entry] of Object.entries(theirs.caches)) {
80
+ const later = dropped.has(name) ? undefined : laterOf(mine.caches[name], entry);
81
+ if (later) mine.caches[name] = later;
82
+ }
83
+ mine.etags = { ...theirs.etags, ...mine.etags };
84
+ dropped.clear();
85
+ return mine;
86
+ }
87
+
88
+ function saveIndexSoon(): void {
89
+ saveTimer ??= setTimeout(() => {
90
+ saveTimer = undefined;
91
+ try {
92
+ localStorage.setItem(INDEX_KEY, JSON.stringify(mergedIndex()));
93
+ } catch {
94
+ // expected: storage refused; the caches still hold the frames, only their order of use is lost
95
+ }
96
+ }, 1000);
97
+ }
98
+
99
+ function used(name: string, addedBytes = 0): void {
100
+ const caches = loadIndex().caches;
101
+ caches[name] = { usedAt: Date.now(), bytes: (caches[name]?.bytes ?? 0) + addedBytes };
102
+ saveIndexSoon();
103
+ }
104
+
105
+ /** The version stored for `source`, when one conditional one-byte read says the server still has it (304). */
106
+ export const storedVersion = (source: string) =>
107
+ quietly(async (): Promise<StoredSource | undefined> => {
108
+ const etag = loadIndex().etags[await digest(source)];
109
+ if (!etag) return undefined;
110
+ // oxlint-disable-next-line no-restricted-globals -- one validation read, on the media's own route like mediabunny's
111
+ const response = await fetch(source, {
112
+ headers: { Range: "bytes=0-0", "If-None-Match": etag },
113
+ });
114
+ await response.body?.cancel();
115
+ return response.status === 304 ? { source, etag } : undefined;
116
+ });
117
+
118
+ /** Records the version the server now has, dropping what was stored for the source's earlier versions. */
119
+ export const rememberVersion = (stored: StoredSource) =>
120
+ quietly(async () => {
121
+ const key = await digest(stored.source);
122
+ const saved = loadIndex();
123
+ if (saved.etags[key] === stored.etag) return;
124
+ saved.etags[key] = stored.etag;
125
+ saveIndexSoon();
126
+ const keep = await cacheNameOf(stored);
127
+ for (const name of await caches.keys()) {
128
+ if (!name.startsWith(`${CACHE_PREFIX}${key}:`) || name === keep) continue;
129
+ await caches.delete(name);
130
+ delete saved.caches[name];
131
+ dropped.add(name);
132
+ }
133
+ });
134
+
135
+ async function entry(stored: StoredSource, path: string) {
136
+ const name = await cacheNameOf(stored);
137
+ return { name, cache: await caches.open(name), url: `${ENTRY_ORIGIN}${path}` };
138
+ }
139
+
140
+ /** A read opens nothing: opening a cache creates it, and an empty one for a gone version would never be dropped. */
141
+ async function storedEntry(stored: StoredSource, path: string) {
142
+ const name = await cacheNameOf(stored);
143
+ return (await caches.has(name)) ? entry(stored, path) : undefined;
144
+ }
145
+
146
+ export const readStoredInfo = (stored: StoredSource) =>
147
+ quietly(async (): Promise<SourceInfo | undefined> => {
148
+ const found = await storedEntry(stored, "info");
149
+ if (!found) return undefined;
150
+ const { name, cache, url } = found;
151
+ const info = (await (await cache.match(url))?.json()) as SourceInfo | undefined;
152
+ if (!(info && info.aspect > 0)) return undefined;
153
+ used(name);
154
+ return info;
155
+ });
156
+
157
+ export const storeInfo = (stored: StoredSource, info: SourceInfo) =>
158
+ quietly(async () => {
159
+ const { name, cache, url } = await entry(stored, "info");
160
+ await cache.put(url, new Response(JSON.stringify(info)));
161
+ used(name);
162
+ });
163
+
164
+ /** `frame` names one picture of the source: its fit, size and the time it was asked for. */
165
+ export const readStoredFrame = (stored: StoredSource, frame: string) =>
166
+ quietly(async (): Promise<StoredFrame | undefined> => {
167
+ const found = await storedEntry(stored, `frame?${encodeURIComponent(frame)}`);
168
+ if (!found) return undefined;
169
+ const { name, cache, url } = found;
170
+ const response = await cache.match(url);
171
+ const decodedAt = Number(response?.headers.get("x-decoded-at"));
172
+ if (!response || !Number.isFinite(decodedAt)) return undefined;
173
+ used(name);
174
+ return { blob: await response.blob(), decodedAt };
175
+ });
176
+
177
+ export const storeFrame = (stored: StoredSource, frame: string, decodedAt: number, blob: Blob) =>
178
+ quietly(async () => {
179
+ const { name, cache, url } = await entry(stored, `frame?${encodeURIComponent(frame)}`);
180
+ const replaced = Number((await cache.match(url))?.headers.get("x-bytes")) || 0;
181
+ const headers = {
182
+ "content-type": blob.type,
183
+ "x-decoded-at": String(decodedAt),
184
+ "x-bytes": String(blob.size),
185
+ };
186
+ await cache.put(url, new Response(blob, { headers }));
187
+ used(name, blob.size - replaced);
188
+ await dropLeastUsed(STORED_THUMBNAIL_BYTES);
189
+ });
190
+
191
+ /** Whole sources go, least recently used first, until what is stored fits `budgetBytes`. */
192
+ async function dropLeastUsed(budgetBytes: number): Promise<void> {
193
+ const saved = loadIndex();
194
+ let total = Object.values(saved.caches).reduce((sum, { bytes }) => sum + bytes, 0);
195
+ const oldestFirst = Object.entries(saved.caches).sort(([, a], [, b]) => a.usedAt - b.usedAt);
196
+ for (const [name, { bytes }] of oldestFirst) {
197
+ if (total <= budgetBytes) break;
198
+ await caches.delete(name);
199
+ delete saved.caches[name];
200
+ dropped.add(name);
201
+ total -= bytes;
202
+ }
203
+ saveIndexSoon();
204
+ }
205
+
206
+ /** Tests only: forget the in-memory index and any pending save. */
207
+ export function resetStoredThumbnailsForTests(): void {
208
+ clearTimeout(saveTimer);
209
+ saveTimer = undefined;
210
+ index = undefined;
211
+ warned = false;
212
+ }
@@ -12,6 +12,7 @@ interface OpenedSource {
12
12
  mediabunny: Mediabunny;
13
13
  track: InputVideoTrack;
14
14
  info: SourceInfo;
15
+ etag: string | undefined;
15
16
  }
16
17
 
17
18
  export interface ThumbnailSource extends OpenedSource {
@@ -88,7 +89,8 @@ async function open(source: string, pooled: () => PooledSource): Promise<OpenedS
88
89
  }
89
90
  const metadataDuration = await track.getDurationFromMetadata({ skipLiveWait: true });
90
91
  live();
91
- return { mediabunny, track, info: { aspect: displayWidth / displayHeight, metadataDuration } };
92
+ const info = { aspect: displayWidth / displayHeight, metadataDuration };
93
+ return { mediabunny, track, info, etag: options.etagOf() };
92
94
  }
93
95
 
94
96
  function pooledSource(source: string, version: string | undefined): PooledSource {