@hyperframes/studio 0.9.1 → 0.9.3

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.
@@ -1,4 +1,4 @@
1
- import{n as Qi}from"./index-Dh1BiGcb.js";/*!
1
+ import{n as Qi}from"./index-CWzE624c.js";/*!
2
2
  * Copyright (c) 2026-present, Vanilagy and contributors
3
3
  *
4
4
  * This Source Code Form is subject to the terms of the Mozilla Public
@@ -1103,6 +1103,582 @@ function whenPreviewBooted(projectId) {
1103
1103
  });
1104
1104
  }
1105
1105
 
1106
+ // src/utils/studioFileVersion.ts
1107
+ var WRITE_TOKEN_TTL_MS = 5 * 6e4;
1108
+ var studioWriteTokens = /* @__PURE__ */ new Map();
1109
+ var fileRevision = 0;
1110
+ function studioFileRevision() {
1111
+ return fileRevision;
1112
+ }
1113
+ function pruneStudioWriteTokens(now) {
1114
+ for (const [token, createdAt] of studioWriteTokens) {
1115
+ if (now - createdAt >= WRITE_TOKEN_TTL_MS) studioWriteTokens.delete(token);
1116
+ }
1117
+ }
1118
+ function markStudioWriteToken(token, now = Date.now()) {
1119
+ pruneStudioWriteTokens(now);
1120
+ studioWriteTokens.set(token, now);
1121
+ fileRevision += 1;
1122
+ }
1123
+ function consumeStudioWriteToken(token, now = Date.now()) {
1124
+ pruneStudioWriteTokens(now);
1125
+ if (!token || !studioWriteTokens.has(token)) return false;
1126
+ studioWriteTokens.delete(token);
1127
+ return true;
1128
+ }
1129
+ async function studioFileContentVersion(content) {
1130
+ const bytes = new TextEncoder().encode(content);
1131
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1132
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(
1133
+ ""
1134
+ );
1135
+ return `"sha256:${hex}"`;
1136
+ }
1137
+ async function studioExpectedFileVersion(versions, path, expectedContent) {
1138
+ if (expectedContent !== void 0) return studioFileContentVersion(expectedContent);
1139
+ return versions.get(path);
1140
+ }
1141
+ function createStudioWriteToken() {
1142
+ const webCrypto = globalThis.crypto;
1143
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
1144
+ if (typeof webCrypto?.getRandomValues !== "function") {
1145
+ throw new Error("Web Crypto getRandomValues is required for Studio write identity");
1146
+ }
1147
+ const bytes = webCrypto.getRandomValues(new Uint8Array(16));
1148
+ bytes[6] = bytes[6] & 15 | 64;
1149
+ bytes[8] = bytes[8] & 63 | 128;
1150
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1151
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1152
+ }
1153
+ function studioWriteHeaders() {
1154
+ const token = createStudioWriteToken();
1155
+ markStudioWriteToken(token);
1156
+ return { "X-Hyperframes-Write-Token": token };
1157
+ }
1158
+
1159
+ // src/utils/studioDebug.ts
1160
+ function makeStudioDebugLogger(name) {
1161
+ let enabled = null;
1162
+ return (stage, data = {}) => {
1163
+ if (enabled === null) {
1164
+ try {
1165
+ enabled = localStorage.getItem(`hf-${name}-debug`) === "1";
1166
+ } catch {
1167
+ enabled = false;
1168
+ }
1169
+ }
1170
+ if (!enabled) return;
1171
+ const details = typeof data === "function" ? data() : data;
1172
+ if (!details) return;
1173
+ console.log(
1174
+ `[hf-${name}] ${JSON.stringify({ stage, t: Math.round(performance.now()), ...details })}`
1175
+ );
1176
+ };
1177
+ }
1178
+
1179
+ // src/utils/reloadDebug.ts
1180
+ var logReload = makeStudioDebugLogger("reload");
1181
+
1182
+ // src/player/lib/timelineViewportBudgets.ts
1183
+ var MEBIBYTE = 1024 * 1024;
1184
+ var DAY_MS = 24 * 60 * 60 * 1e3;
1185
+ var MAX_VISIBLE_THUMBNAIL_FRAMES = Math.ceil(3840 / (66 * (16 / 9)));
1186
+ var TIMELINE_VIEWPORT_BUDGETS = Object.freeze({
1187
+ directScrollSafetyPx: 8e6,
1188
+ rowOverscanPerSide: 2,
1189
+ timeOverscanViewportRatio: 0.25,
1190
+ maxMountedRows: 64,
1191
+ maxMountedClipRoots: 512,
1192
+ maxMountedClipRootsPerRow: 128,
1193
+ maxMountedTimelineDescendants: 5e3,
1194
+ posterMaxPhysicalWidth: 240,
1195
+ posterMaxPhysicalHeight: 135,
1196
+ posterDprCap: 1.5,
1197
+ richPreviewFrameCount: MAX_VISIBLE_THUMBNAIL_FRAMES,
1198
+ concurrentVideoDecodes: 2,
1199
+ concurrentMetadataJobs: 4,
1200
+ concurrentCompositionFetches: 2,
1201
+ concurrentServerPages: 1,
1202
+ thumbnailLoadTimeoutMs: 3e4,
1203
+ thumbnailCacheBytes: 64 * MEBIBYTE,
1204
+ sharedFrameCacheBytes: 32 * MEBIBYTE,
1205
+ thumbnailSourceIdleMs: 1e4,
1206
+ thumbnailCacheEntries: 256,
1207
+ thumbnailCacheEntriesPerProject: 96,
1208
+ metadataRegistryEntries: 512,
1209
+ metadataFailureTtlMs: 3e4,
1210
+ waveformCacheBytes: 16 * MEBIBYTE,
1211
+ waveformCacheEntries: 256,
1212
+ compositionDiskCacheBytes: 512 * MEBIBYTE,
1213
+ compositionDiskCacheMaxAgeMs: 14 * DAY_MS,
1214
+ interactionP95Ms: 50,
1215
+ frameIntervalP95Ms: 33.3,
1216
+ constrainedInteractionP95Ms: 75,
1217
+ constrainedFrameIntervalP95Ms: 75,
1218
+ ciVirtualizedInteractionP95Ms: 58.3,
1219
+ ciVirtualizedFrameIntervalP95Ms: 25,
1220
+ longTaskLimitMs: 50,
1221
+ constrainedLongTaskLimitMs: 300,
1222
+ memoryReturnToleranceRatio: 0.15,
1223
+ posterColdP95Ms: 750,
1224
+ posterCachedP95Ms: 250,
1225
+ constrainedPosterColdP95Ms: 1200,
1226
+ constrainedPosterCachedP95Ms: 400,
1227
+ posterCoverageRatio: 0.9,
1228
+ posterCoverageSettleMs: 1500,
1229
+ constrainedPosterCoverageSettleMs: 2500,
1230
+ richPreviewP95Ms: 750,
1231
+ constrainedRichPreviewP95Ms: 1200,
1232
+ supportedFixtureFallbackRatio: 0.02,
1233
+ scrollSamplesPerRun: 63,
1234
+ warmupRuns: 3,
1235
+ measuredRuns: 5,
1236
+ requiredPassingRuns: 4
1237
+ });
1238
+
1239
+ // src/player/lib/thumbnailScheduler.ts
1240
+ var PRIORITY_SCORE = {
1241
+ overscan: 0,
1242
+ visible: 1,
1243
+ interaction: 2
1244
+ };
1245
+ var EMPTY_SNAPSHOT = Object.freeze({ status: "idle" });
1246
+ function concurrencyBucket(kind) {
1247
+ if (kind === "video") return "video";
1248
+ if (kind === "composition") return "composition";
1249
+ return "general";
1250
+ }
1251
+ function errorFrom(reason) {
1252
+ return reason instanceof Error ? reason : new Error(String(reason));
1253
+ }
1254
+ function createThumbnailKey(parts) {
1255
+ return Object.entries(parts).filter((entry) => entry[1] !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`).join("&");
1256
+ }
1257
+ function createThumbnailRequestIdentity(request) {
1258
+ return createThumbnailKey({
1259
+ project: request.projectId,
1260
+ session: request.sessionEpoch,
1261
+ request: request.key,
1262
+ kind: request.kind,
1263
+ rich: request.rich ? 1 : 0
1264
+ });
1265
+ }
1266
+ var ThumbnailScheduler = class {
1267
+ entries = /* @__PURE__ */ new Map();
1268
+ budgets;
1269
+ nextLeaseId = 1;
1270
+ nextSequence = 1;
1271
+ scrolling = false;
1272
+ previewReloading = false;
1273
+ playbackActive = false;
1274
+ pageHidden = false;
1275
+ cacheBytes = 0;
1276
+ waveformCacheBytes = 0;
1277
+ activeByBucket = { video: 0, composition: 0, general: 0 };
1278
+ activeByKind = {
1279
+ video: 0,
1280
+ image: 0,
1281
+ composition: 0,
1282
+ waveform: 0
1283
+ };
1284
+ now;
1285
+ constructor(budgets = TIMELINE_VIEWPORT_BUDGETS, now = Date.now) {
1286
+ this.budgets = budgets;
1287
+ this.now = now;
1288
+ }
1289
+ acquire(request, listener) {
1290
+ const scopedKey = createThumbnailRequestIdentity(request);
1291
+ let entry = this.entries.get(scopedKey);
1292
+ if (entry?.state === "error" && entry.failedAt !== void 0 && this.now() - entry.failedAt >= this.budgets.metadataFailureTtlMs) {
1293
+ this.deleteEntry(scopedKey, entry);
1294
+ entry = this.entries.get(scopedKey);
1295
+ }
1296
+ if (!entry) {
1297
+ entry = {
1298
+ request,
1299
+ scopedKey,
1300
+ state: "queued",
1301
+ leases: /* @__PURE__ */ new Map(),
1302
+ listeners: /* @__PURE__ */ new Map(),
1303
+ controller: null,
1304
+ weight: 0,
1305
+ disposed: false,
1306
+ cached: false,
1307
+ lastAccess: this.nextSequence++,
1308
+ snapshot: Object.freeze({ status: "queued" }),
1309
+ preempted: false
1310
+ };
1311
+ this.entries.set(scopedKey, entry);
1312
+ }
1313
+ const leaseId = this.nextLeaseId++;
1314
+ entry.leases.set(leaseId, request.priority);
1315
+ entry.listeners.set(leaseId, listener);
1316
+ entry.lastAccess = this.nextSequence++;
1317
+ this.pump();
1318
+ let released = false;
1319
+ return {
1320
+ updatePriority: (priority) => {
1321
+ const current = this.entries.get(scopedKey);
1322
+ if (!current || !current.leases.has(leaseId)) return;
1323
+ current.leases.set(leaseId, priority);
1324
+ current.lastAccess = this.nextSequence++;
1325
+ this.pump();
1326
+ },
1327
+ release: () => {
1328
+ if (released) return;
1329
+ released = true;
1330
+ const current = this.entries.get(scopedKey);
1331
+ if (!current) return;
1332
+ current.leases.delete(leaseId);
1333
+ current.listeners.delete(leaseId);
1334
+ if (current.leases.size === 0) {
1335
+ if (current.state === "queued") {
1336
+ this.deleteEntry(scopedKey, current);
1337
+ } else if (current.state === "loading") {
1338
+ current.controller?.abort();
1339
+ this.deleteEntry(scopedKey, current);
1340
+ } else if (current.state === "ready" && !current.cached) {
1341
+ this.deleteEntry(scopedKey, current);
1342
+ }
1343
+ }
1344
+ this.evict();
1345
+ }
1346
+ };
1347
+ }
1348
+ getSnapshot(request) {
1349
+ const entry = this.entries.get(createThumbnailRequestIdentity(request));
1350
+ if (!entry) return EMPTY_SNAPSHOT;
1351
+ return entry.snapshot;
1352
+ }
1353
+ setScrolling(scrolling) {
1354
+ if (this.scrolling === scrolling) return;
1355
+ this.scrolling = scrolling;
1356
+ if (!scrolling) this.pump();
1357
+ }
1358
+ /** Holds composition renders while the preview loads: same server, and the preview is what the person awaits. */
1359
+ setPreviewReloading(reloading2) {
1360
+ if (this.previewReloading === reloading2) return;
1361
+ this.previewReloading = reloading2;
1362
+ if (!reloading2) {
1363
+ this.pump();
1364
+ return;
1365
+ }
1366
+ for (const entry of this.entries.values()) {
1367
+ if (entry.state !== "loading" || entry.request.kind !== "composition") continue;
1368
+ this.preempt(entry);
1369
+ }
1370
+ }
1371
+ setPlaybackActive(active) {
1372
+ if (this.playbackActive === active) return;
1373
+ this.playbackActive = active;
1374
+ if (!active) this.pump();
1375
+ }
1376
+ setPageHidden(hidden) {
1377
+ if (this.pageHidden === hidden) return;
1378
+ this.pageHidden = hidden;
1379
+ if (!hidden) {
1380
+ this.pump();
1381
+ return;
1382
+ }
1383
+ for (const entry of this.entries.values()) {
1384
+ if (entry.state === "loading") this.preempt(entry);
1385
+ }
1386
+ }
1387
+ preempt(entry) {
1388
+ entry.preempted = true;
1389
+ entry.controller?.abort();
1390
+ }
1391
+ /** Evict project cache entries that are no longer owned by mounted consumers. */
1392
+ invalidateProject(projectId) {
1393
+ for (const [key, entry] of this.entries) {
1394
+ if (entry.request.projectId !== projectId) continue;
1395
+ if (entry.leases.size > 0) continue;
1396
+ entry.controller?.abort();
1397
+ this.deleteEntry(key, entry);
1398
+ }
1399
+ }
1400
+ getDiagnostics() {
1401
+ let queued2 = 0;
1402
+ let active = 0;
1403
+ let leases = 0;
1404
+ let cacheEntries = 0;
1405
+ let waveformCacheEntries = 0;
1406
+ for (const entry of this.entries.values()) {
1407
+ if (entry.state === "queued") queued2++;
1408
+ if (entry.state === "loading") active++;
1409
+ if (entry.cached) {
1410
+ if (entry.request.kind === "waveform") waveformCacheEntries++;
1411
+ else cacheEntries++;
1412
+ }
1413
+ leases += entry.leases.size;
1414
+ }
1415
+ return {
1416
+ queued: queued2,
1417
+ active,
1418
+ leases,
1419
+ cacheEntries,
1420
+ cacheBytes: this.cacheBytes,
1421
+ waveformCacheEntries,
1422
+ waveformCacheBytes: this.waveformCacheBytes,
1423
+ activeByKind: { ...this.activeByKind }
1424
+ };
1425
+ }
1426
+ pump() {
1427
+ if (this.pageHidden) return;
1428
+ const queued2 = Array.from(this.entries.values()).filter((entry) => entry.state === "queued" && entry.leases.size > 0).sort((left, right) => {
1429
+ const priorityDelta = this.entryPriority(right) - this.entryPriority(left);
1430
+ return priorityDelta || left.lastAccess - right.lastAccess;
1431
+ });
1432
+ for (const entry of queued2) {
1433
+ if (this.isHeld(entry)) continue;
1434
+ const bucket = concurrencyBucket(entry.request.kind);
1435
+ if (this.activeByBucket[bucket] >= this.bucketLimit(bucket)) continue;
1436
+ this.start(entry, bucket);
1437
+ }
1438
+ }
1439
+ isHeld(entry) {
1440
+ const { kind, rich } = entry.request;
1441
+ if (this.scrolling && rich) return true;
1442
+ if (this.previewReloading && kind === "composition") return true;
1443
+ return this.playbackActive && kind === "video" && this.entryPriority(entry) < PRIORITY_SCORE.interaction;
1444
+ }
1445
+ start(entry, bucket) {
1446
+ entry.state = "loading";
1447
+ entry.snapshot = Object.freeze({ status: "loading" });
1448
+ const controller = new AbortController();
1449
+ entry.controller = controller;
1450
+ this.activeByBucket[bucket]++;
1451
+ this.activeByKind[entry.request.kind]++;
1452
+ let slotFree = false;
1453
+ const freeSlot = () => {
1454
+ if (slotFree) return;
1455
+ slotFree = true;
1456
+ this.activeByBucket[bucket]--;
1457
+ this.activeByKind[entry.request.kind]--;
1458
+ queueMicrotask(() => this.pump());
1459
+ };
1460
+ controller.signal.addEventListener("abort", freeSlot, { once: true });
1461
+ this.notify(entry);
1462
+ const pending = this.loadWithTimeout(entry, controller);
1463
+ void pending.then((result) => this.acceptResult(entry, controller, result)).catch((reason) => {
1464
+ if (this.entries.get(entry.scopedKey) !== entry) return;
1465
+ if (controller.signal.aborted && entry.leases.size === 0) {
1466
+ this.deleteEntry(entry.scopedKey, entry);
1467
+ return;
1468
+ }
1469
+ if (this.requeuePreempted(entry)) return;
1470
+ entry.state = "error";
1471
+ entry.error = errorFrom(reason);
1472
+ entry.failedAt = this.now();
1473
+ entry.snapshot = Object.freeze({ status: "error", error: entry.error });
1474
+ this.notify(entry);
1475
+ this.evictFailures();
1476
+ }).finally(() => {
1477
+ if (entry.controller === controller) entry.controller = null;
1478
+ freeSlot();
1479
+ this.pump();
1480
+ });
1481
+ }
1482
+ acceptResult(entry, controller, result) {
1483
+ if (controller.signal.aborted || this.entries.get(entry.scopedKey) !== entry) {
1484
+ this.safeDispose(result.dispose);
1485
+ this.requeuePreempted(entry);
1486
+ return;
1487
+ }
1488
+ this.validateResult(result);
1489
+ entry.state = "ready";
1490
+ entry.value = result.value;
1491
+ entry.weight = result.weight;
1492
+ entry.dispose = result.dispose;
1493
+ this.cacheResult(entry);
1494
+ entry.snapshot = Object.freeze({ status: "ready", value: result.value });
1495
+ this.notify(entry);
1496
+ this.evict();
1497
+ if (!entry.cached && entry.leases.size === 0) this.deleteEntry(entry.scopedKey, entry);
1498
+ }
1499
+ requeuePreempted(entry) {
1500
+ if (!entry.preempted || this.entries.get(entry.scopedKey) !== entry) return false;
1501
+ entry.preempted = false;
1502
+ entry.state = "queued";
1503
+ entry.snapshot = Object.freeze({ status: "queued" });
1504
+ this.notify(entry);
1505
+ return true;
1506
+ }
1507
+ validateResult(result) {
1508
+ if (Number.isFinite(result.weight) && result.weight >= 0) return;
1509
+ this.safeDispose(result.dispose);
1510
+ throw new RangeError("Thumbnail result weight must be finite and non-negative");
1511
+ }
1512
+ cacheResult(entry) {
1513
+ const isWaveform = entry.request.kind === "waveform";
1514
+ const byteBudget = isWaveform ? this.budgets.waveformCacheBytes : this.budgets.thumbnailCacheBytes;
1515
+ entry.cached = !entry.request.discardWhenReleased && entry.weight <= byteBudget;
1516
+ if (!entry.cached) return;
1517
+ if (isWaveform) this.waveformCacheBytes += entry.weight;
1518
+ else this.cacheBytes += entry.weight;
1519
+ }
1520
+ entryPriority(entry) {
1521
+ let score = -1;
1522
+ for (const priority of entry.leases.values()) {
1523
+ score = Math.max(score, PRIORITY_SCORE[priority]);
1524
+ }
1525
+ return score;
1526
+ }
1527
+ bucketLimit(bucket) {
1528
+ if (bucket === "video") return this.budgets.concurrentVideoDecodes;
1529
+ if (bucket === "composition") return this.budgets.concurrentCompositionFetches;
1530
+ return this.budgets.concurrentMetadataJobs;
1531
+ }
1532
+ evict() {
1533
+ this.evictPartition(false);
1534
+ this.evictPartition(true);
1535
+ }
1536
+ evictPartition(waveform) {
1537
+ const cached = Array.from(this.entries.values()).filter(
1538
+ (entry) => entry.cached && entry.request.kind === "waveform" === waveform
1539
+ );
1540
+ const perProject = /* @__PURE__ */ new Map();
1541
+ for (const entry of cached) {
1542
+ perProject.set(entry.request.projectId, (perProject.get(entry.request.projectId) ?? 0) + 1);
1543
+ }
1544
+ cached.sort((left, right) => left.lastAccess - right.lastAccess);
1545
+ let cacheEntries = cached.length;
1546
+ for (const entry of cached) {
1547
+ const projectEntries = perProject.get(entry.request.projectId) ?? 0;
1548
+ if (!this.isCacheOverBudget(waveform, cacheEntries, projectEntries)) continue;
1549
+ this.uncache(entry);
1550
+ cacheEntries--;
1551
+ perProject.set(entry.request.projectId, projectEntries - 1);
1552
+ if (entry.leases.size === 0) this.deleteEntry(entry.scopedKey, entry);
1553
+ }
1554
+ }
1555
+ isCacheOverBudget(waveform, cacheEntries, projectEntries) {
1556
+ const entryBudget = waveform ? this.budgets.waveformCacheEntries : this.budgets.thumbnailCacheEntries;
1557
+ const byteBudget = waveform ? this.budgets.waveformCacheBytes : this.budgets.thumbnailCacheBytes;
1558
+ const cacheBytes = waveform ? this.waveformCacheBytes : this.cacheBytes;
1559
+ const projectOverBudget = !waveform && projectEntries > this.budgets.thumbnailCacheEntriesPerProject;
1560
+ return cacheEntries > entryBudget || cacheBytes > byteBudget || projectOverBudget;
1561
+ }
1562
+ uncache(entry) {
1563
+ entry.cached = false;
1564
+ if (entry.request.kind === "waveform") this.waveformCacheBytes -= entry.weight;
1565
+ else this.cacheBytes -= entry.weight;
1566
+ }
1567
+ notify(entry) {
1568
+ for (const listener of new Set(entry.listeners.values())) listener();
1569
+ }
1570
+ loadWithTimeout(entry, controller) {
1571
+ let load;
1572
+ try {
1573
+ load = entry.request.load(controller.signal);
1574
+ } catch (reason) {
1575
+ load = Promise.reject(reason);
1576
+ }
1577
+ return new Promise((resolve, reject) => {
1578
+ let settled = false;
1579
+ const timeout = setTimeout(() => {
1580
+ if (settled) return;
1581
+ settled = true;
1582
+ const message = `Thumbnail load timed out after ${this.budgets.thumbnailLoadTimeoutMs}ms`;
1583
+ controller.abort(new DOMException(message, "TimeoutError"));
1584
+ reject(new Error(message));
1585
+ }, this.budgets.thumbnailLoadTimeoutMs);
1586
+ load.then(
1587
+ (result) => {
1588
+ if (settled) {
1589
+ this.safeDispose(result.dispose);
1590
+ return;
1591
+ }
1592
+ settled = true;
1593
+ clearTimeout(timeout);
1594
+ resolve(result);
1595
+ },
1596
+ (reason) => {
1597
+ if (settled) return;
1598
+ settled = true;
1599
+ clearTimeout(timeout);
1600
+ reject(reason);
1601
+ }
1602
+ );
1603
+ });
1604
+ }
1605
+ deleteEntry(key, entry) {
1606
+ if (this.entries.get(key) !== entry) return;
1607
+ this.entries.delete(key);
1608
+ entry.snapshot = EMPTY_SNAPSHOT;
1609
+ this.notify(entry);
1610
+ if (entry.cached) {
1611
+ entry.cached = false;
1612
+ if (entry.request.kind === "waveform") this.waveformCacheBytes -= entry.weight;
1613
+ else this.cacheBytes -= entry.weight;
1614
+ }
1615
+ if (!entry.disposed) {
1616
+ entry.disposed = true;
1617
+ this.safeDispose(entry.dispose);
1618
+ }
1619
+ entry.listeners.clear();
1620
+ entry.leases.clear();
1621
+ }
1622
+ evictFailures() {
1623
+ const failed = Array.from(this.entries.values()).filter((entry) => entry.state === "error" && entry.leases.size === 0).sort((left, right) => left.lastAccess - right.lastAccess);
1624
+ const overflow = failed.length - this.budgets.thumbnailCacheEntries;
1625
+ for (const entry of failed.slice(0, Math.max(0, overflow))) {
1626
+ this.deleteEntry(entry.scopedKey, entry);
1627
+ }
1628
+ }
1629
+ safeDispose(dispose) {
1630
+ try {
1631
+ dispose?.();
1632
+ } catch {
1633
+ }
1634
+ }
1635
+ };
1636
+ var thumbnailScheduler = new ThumbnailScheduler();
1637
+
1638
+ // src/player/previewReloading.ts
1639
+ var reloading = false;
1640
+ var reloadRequested = false;
1641
+ var scriptWrites = 0;
1642
+ var givenUp = false;
1643
+ var changing = () => reloading || reloadRequested || scriptWrites > 0;
1644
+ var noteIdle = () => {
1645
+ if (!changing()) givenUp = false;
1646
+ globalThis.document?.documentElement.toggleAttribute(
1647
+ "data-preview-changing",
1648
+ isPreviewChanging()
1649
+ );
1650
+ };
1651
+ function giveUpOnPreviewChange() {
1652
+ givenUp = changing();
1653
+ noteIdle();
1654
+ }
1655
+ function setPreviewReloading(next) {
1656
+ reloading = next;
1657
+ thumbnailScheduler.setPreviewReloading(next);
1658
+ noteIdle();
1659
+ }
1660
+ function requestPreviewReload() {
1661
+ reloadRequested = true;
1662
+ noteIdle();
1663
+ }
1664
+ function previewReloadBegun() {
1665
+ reloadRequested = false;
1666
+ noteIdle();
1667
+ }
1668
+ async function whileScriptWrites(write) {
1669
+ scriptWrites += 1;
1670
+ noteIdle();
1671
+ try {
1672
+ return await write();
1673
+ } finally {
1674
+ scriptWrites -= 1;
1675
+ noteIdle();
1676
+ }
1677
+ }
1678
+ function isPreviewChanging() {
1679
+ return changing() && !givenUp;
1680
+ }
1681
+
1106
1682
  // src/player/sceneSwap.ts
1107
1683
  var SCENES_SWAPPED = "hf-scenes-swapped";
1108
1684
  var SCENE_SWAP_MS = 5e3;
@@ -1154,6 +1730,25 @@ function markScenesStale(iframe, files) {
1154
1730
  meta.content = JSON.stringify(parts);
1155
1731
  }
1156
1732
  var supersededByNewerEdit = () => new DOMException("superseded by a newer edit", "AbortError");
1733
+ var SWAP_REFETCHES_BEFORE_THE_COPY_IN_HAND_WINS = 5;
1734
+ function swapFreshly(swap, url, isCurrent, cancel, reloadWholeFilm, attempt = 0) {
1735
+ const at = studioFileRevision();
1736
+ const fresh = () => studioFileRevision() === at;
1737
+ const again = () => {
1738
+ url.searchParams.set("_t", String(Date.now()));
1739
+ swapFreshly(swap, url, isCurrent, cancel, reloadWholeFilm, attempt + 1);
1740
+ };
1741
+ const retries = attempt < SWAP_REFETCHES_BEFORE_THE_COPY_IN_HAND_WINS;
1742
+ const gate = retries ? () => isCurrent() && fresh() : isCurrent;
1743
+ whileScriptWrites(() => swap(url.toString(), gate, cancel)).then(() => {
1744
+ if (isCurrent() && !fresh() && retries) again();
1745
+ }).catch((error) => {
1746
+ if (!isCurrent()) return;
1747
+ if (!fresh() && retries) return again();
1748
+ logReload("scene-swap-refused", { reason: String(error) });
1749
+ reloadWholeFilm(url.toString());
1750
+ });
1751
+ }
1157
1752
  function sceneSwapFor(iframe) {
1158
1753
  const win = iframe.contentWindow;
1159
1754
  const swap = win?.__hfSwapScenes;
@@ -1680,6 +2275,25 @@ export {
1680
2275
  usePlayerStore,
1681
2276
  isPreviewBooted,
1682
2277
  whenPreviewBooted,
2278
+ studioFileRevision,
2279
+ markStudioWriteToken,
2280
+ consumeStudioWriteToken,
2281
+ studioFileContentVersion,
2282
+ studioExpectedFileVersion,
2283
+ studioWriteHeaders,
2284
+ makeStudioDebugLogger,
2285
+ logReload,
2286
+ MAX_VISIBLE_THUMBNAIL_FRAMES,
2287
+ TIMELINE_VIEWPORT_BUDGETS,
2288
+ createThumbnailKey,
2289
+ createThumbnailRequestIdentity,
2290
+ thumbnailScheduler,
2291
+ giveUpOnPreviewChange,
2292
+ setPreviewReloading,
2293
+ requestPreviewReload,
2294
+ previewReloadBegun,
2295
+ whileScriptWrites,
2296
+ isPreviewChanging,
1683
2297
  announcePreviewDocumentLoaded,
1684
2298
  onPreviewDocumentLoaded,
1685
2299
  onPreviewContentReplaced,
@@ -1687,6 +2301,7 @@ export {
1687
2301
  onPreviewPromoted,
1688
2302
  markScenesStale,
1689
2303
  supersededByNewerEdit,
2304
+ swapFreshly,
1690
2305
  sceneSwapFor,
1691
2306
  Player
1692
2307
  };
package/dist/index.d.ts CHANGED
@@ -23,6 +23,23 @@ import '@base-ui/react/context-menu';
23
23
  import '@base-ui/react/menu';
24
24
  import '@base-ui/react/popover';
25
25
 
26
+ interface Combo {
27
+ mod: boolean;
28
+ meta: boolean;
29
+ ctrl: boolean;
30
+ shift: boolean;
31
+ alt: boolean;
32
+ key: string;
33
+ named: boolean;
34
+ }
35
+ /** "mod+shift+z", "Space", "b": mod is Cmd or Ctrl; Ctrl+Alt is refused because Windows sends AltGr as Ctrl+Alt. */
36
+ declare function parseCombo(text: string): Combo | null;
37
+ type ComboEvent = Pick<KeyboardEvent, "key" | "altKey" | "ctrlKey" | "metaKey" | "shiftKey"> & {
38
+ code?: string;
39
+ };
40
+ declare function matchCombo(e: ComboEvent, c: Combo): boolean;
41
+ declare function formatCombo(c: Combo): string;
42
+
26
43
  /** Every single-character bare key Studio answers, by action. */
27
44
  declare const DEFAULT_STUDIO_KEYS: {
28
45
  fullscreen: string;
@@ -90,6 +107,7 @@ declare const DEFAULT_STUDIO_KEYS: {
90
107
  };
91
108
  type StudioKeyAction = keyof typeof DEFAULT_STUDIO_KEYS;
92
109
  type StudioKeys = Readonly<Record<StudioKeyAction, string>>;
110
+ declare function studioKeyClash(action: StudioKeyAction, text: string, keys?: StudioKeys): StudioKeyAction | null;
93
111
  /** Replaces the host key map; a bad map is refused whole. null restores the defaults. */
94
112
  declare function setStudioKeys(overrides: Partial<Record<StudioKeyAction, string>> | null): void;
95
113
  declare const getStudioKeys: () => StudioKeys;
@@ -4450,4 +4468,4 @@ declare function buildStudioTools(depsRef: {
4450
4468
  readonly current: StudioAgentToolsDeps;
4451
4469
  }): ModelContextTool[];
4452
4470
 
4453
- export { type AgentModalAnchorPoint, type AgentPromptElementInfo, AskAgentModal, type AskAgentModalProps, AudioMeterStrip, type AudioMeterStripProps, AudioWaveform, type AudioWaveformProps, type BlockedTimelineEditIntent, type CanEditTimelineElement, ColorField, CompositionBreadcrumb, type CompositionDimensions, type CompositionLevel, CompositionThumbnail, ConnectedDomEditOverlay, type ConnectedDomEditOverlayProps, DEFAULT_SHORTCUT_SECTIONS, DEFAULT_STUDIO_KEYS, Dock, type DockController, type DomEditCapabilities, type DomEditCommitDeclineReason, type DomEditCommitOutcome, type DomEditGroupPathOffsetCommit, DomEditOverlay, type DomEditOverlayProps, DomEditProvider, type DomEditSelection, type DomEditZOrder, type DomGeometryCommits, type EditHistoryHandle, EditorShell, type EditorShellProps, type ExternalFileChangeBlockedState, type ExternalFileChangeCoordinatorHandle, ExternalFileConflictBanner, type FadeEdge, type FadeHandleBox, type FadeHandleClipBox, type FfmpegStatus, FileTree, GradientField, GridOverlay, ImageThumbnail, type ImageThumbnailProps, LayersPanel, type LayersPanelHost, type LinkShortcutCallbacks, type MarqueeGestures, type MarqueeGesturesDeps, MarqueeOverlay, type MarqueeOverlayProps, type Rect$1 as MarqueeRect, type ModelContextTool, NLEPreview, type PanelId, type PatchOperation, type PersistedRenderSettings, type PickedElement, type PlaybackHealth, PlayerControls, type PlayerHandle, type PlayerHandleElement, type PlayerHandleListener, type PlayerHandleTimeListener, type DomEditCompositionRect as PreviewCompositionRect, type PreviewCopies, type PreviewFacts, PreviewGuides, PreviewOverlayProvider, type PreviewOverlayProviderProps, type PreviewPromotion, type PreviewQualityChosenBy, PreviewReadOnlyProvider, type PreviewSnapPreferences, PropertyPanel, type RenderJob, RenderQueue, type RenderQueueProps, type ResolutionPreset, SNAP_THRESHOLD_PX, type ShortcutHint, type ShortcutSection, ShortcutsButton, type ShortcutsButtonProps, type SnapContext, type SnapEdge, type SnapGuide, SnapGuideOverlay, type SnapGuideOverlayProps, type SnapGuidesState, type Rect as SnapRect, type SnapResult, type SnapTarget, SnapToolbar, SourceEditor, type SpacingGuide, type StartRenderOptions, type StudioAgentToolsDeps, StudioApp, StudioFileConflictError, type StudioKeyAction, type StudioKeys, type StudioLookSnapshot, type StudioPendingEditsDrainResult, TRACK_H, type ThumbnailPriority, type ThumbnailStill, Timeline, TimelineClipMenu, type TimelineClipMenuItem, type TimelineClipRenderContext, type TimelineEditCallbacks, type TimelineEditOutcome, type TimelineEditPermission, TimelineEditPopover, TimelineEditProvider, type TimelineElement, TimelineEmptyStatePart, TimelineFrame, TimelineGapMenu, TimelineHistoryButtons, type TimelineHistoryButtonsProps, TimelineKeyframeMenu, TimelineLanes, TimelineOverlays, TimelinePane, type TimelinePaneProps, TimelinePlayhead, TimelineProvider, TimelineRazorGuide, TimelineRuler, TimelineShortcutHint, type TimelineTheme, type TimelineTimeRange$1 as TimelineTimeRange, TimelineToolbar, type TimelineToolbarProps, type TimelineTrackPadding, type TimelineZIndexReorderCommit, type ToolResult, type UseClipboardOptions, type UseDomEditSessionParams, type UseDomGeometryCommitOptions, type UseDomStyleCommitOptions, type UseEditHistoryActionsOptions, type UsePersistentEditHistoryOptions, type UsePreviewPersistenceParams, type UseProjectFileWriterOptions, type UseRenderClipContentOptions, type UseThumbnailStillOptions, type UseTimelineEditingOptions, VideoThumbnail, type ZOrderAction, announcePreviewDocumentLoaded, applyPatch, buildCompositionSnapTarget, buildGridSnapEdges, buildPickerAgentContextPreview, buildPickerAgentPrompt, buildShortcutSections, buildStudioTools, cancelNewestStudioWaitingPress, collectSnapContext, collectStudioLookScene, currentTimelineRange, dispatchLinkShortcut, displayTrackOrder, extractSnapTargets, fadeHandleBoxes, findElementBlock, flushStudioPendingEdits, formatTime, getPersistedRenderSettings, getStudioKeys, liveTime, mergeStyleIntoTag, openAudioGainDialog, parseStyleString, persistRenderSettings, resolveDomEditSelection, resolveEquidistanceGuides, resolveGuideLineRect, resolveIframe, resolveSnapAdjustment, resolveSourceFile, revertNewestStudioPendingEdit, setStudioKeys, snapEngagedForTravel, useAudioGainDialogStore, useAudioMetersVisible, useClipboard, useCompositionStack, useDockLayoutStore, useDomEditSelectionContext, useDomEditSession, useDomEditZOrder, useDomGeometryCommit, useDomStyleCommit, useEditHistoryActions, useElementPicker, useLivePreviewIframe, useMarqueeGestures, usePersistentEditHistory, usePlayerHandle, usePlayerStore, usePreviewCompositionRect, usePreviewGuidesStore, usePreviewIframeStore, usePreviewOverlayContext, usePreviewPersistence, useProjectFileWriter, useRenderClipContent, useRenderQueue, useStudioKeys, useThumbnailStill, useTimelineContext, useTimelineEditing, useTimelinePlayer, zoomTimelineToRange };
4471
+ export { type AgentModalAnchorPoint, type AgentPromptElementInfo, AskAgentModal, type AskAgentModalProps, AudioMeterStrip, type AudioMeterStripProps, AudioWaveform, type AudioWaveformProps, type BlockedTimelineEditIntent, type CanEditTimelineElement, ColorField, type Combo, CompositionBreadcrumb, type CompositionDimensions, type CompositionLevel, CompositionThumbnail, ConnectedDomEditOverlay, type ConnectedDomEditOverlayProps, DEFAULT_SHORTCUT_SECTIONS, DEFAULT_STUDIO_KEYS, Dock, type DockController, type DomEditCapabilities, type DomEditCommitDeclineReason, type DomEditCommitOutcome, type DomEditGroupPathOffsetCommit, DomEditOverlay, type DomEditOverlayProps, DomEditProvider, type DomEditSelection, type DomEditZOrder, type DomGeometryCommits, type EditHistoryHandle, EditorShell, type EditorShellProps, type ExternalFileChangeBlockedState, type ExternalFileChangeCoordinatorHandle, ExternalFileConflictBanner, type FadeEdge, type FadeHandleBox, type FadeHandleClipBox, type FfmpegStatus, FileTree, GradientField, GridOverlay, ImageThumbnail, type ImageThumbnailProps, LayersPanel, type LayersPanelHost, type LinkShortcutCallbacks, type MarqueeGestures, type MarqueeGesturesDeps, MarqueeOverlay, type MarqueeOverlayProps, type Rect$1 as MarqueeRect, type ModelContextTool, NLEPreview, type PanelId, type PatchOperation, type PersistedRenderSettings, type PickedElement, type PlaybackHealth, PlayerControls, type PlayerHandle, type PlayerHandleElement, type PlayerHandleListener, type PlayerHandleTimeListener, type DomEditCompositionRect as PreviewCompositionRect, type PreviewCopies, type PreviewFacts, PreviewGuides, PreviewOverlayProvider, type PreviewOverlayProviderProps, type PreviewPromotion, type PreviewQualityChosenBy, PreviewReadOnlyProvider, type PreviewSnapPreferences, PropertyPanel, type RenderJob, RenderQueue, type RenderQueueProps, type ResolutionPreset, SNAP_THRESHOLD_PX, type ShortcutHint, type ShortcutSection, ShortcutsButton, type ShortcutsButtonProps, type SnapContext, type SnapEdge, type SnapGuide, SnapGuideOverlay, type SnapGuideOverlayProps, type SnapGuidesState, type Rect as SnapRect, type SnapResult, type SnapTarget, SnapToolbar, SourceEditor, type SpacingGuide, type StartRenderOptions, type StudioAgentToolsDeps, StudioApp, StudioFileConflictError, type StudioKeyAction, type StudioKeys, type StudioLookSnapshot, type StudioPendingEditsDrainResult, TRACK_H, type ThumbnailPriority, type ThumbnailStill, Timeline, TimelineClipMenu, type TimelineClipMenuItem, type TimelineClipRenderContext, type TimelineEditCallbacks, type TimelineEditOutcome, type TimelineEditPermission, TimelineEditPopover, TimelineEditProvider, type TimelineElement, TimelineEmptyStatePart, TimelineFrame, TimelineGapMenu, TimelineHistoryButtons, type TimelineHistoryButtonsProps, TimelineKeyframeMenu, TimelineLanes, TimelineOverlays, TimelinePane, type TimelinePaneProps, TimelinePlayhead, TimelineProvider, TimelineRazorGuide, TimelineRuler, TimelineShortcutHint, type TimelineTheme, type TimelineTimeRange$1 as TimelineTimeRange, TimelineToolbar, type TimelineToolbarProps, type TimelineTrackPadding, type TimelineZIndexReorderCommit, type ToolResult, type UseClipboardOptions, type UseDomEditSessionParams, type UseDomGeometryCommitOptions, type UseDomStyleCommitOptions, type UseEditHistoryActionsOptions, type UsePersistentEditHistoryOptions, type UsePreviewPersistenceParams, type UseProjectFileWriterOptions, type UseRenderClipContentOptions, type UseThumbnailStillOptions, type UseTimelineEditingOptions, VideoThumbnail, type ZOrderAction, announcePreviewDocumentLoaded, applyPatch, buildCompositionSnapTarget, buildGridSnapEdges, buildPickerAgentContextPreview, buildPickerAgentPrompt, buildShortcutSections, buildStudioTools, cancelNewestStudioWaitingPress, collectSnapContext, collectStudioLookScene, currentTimelineRange, dispatchLinkShortcut, displayTrackOrder, extractSnapTargets, fadeHandleBoxes, findElementBlock, flushStudioPendingEdits, formatCombo, formatTime, getPersistedRenderSettings, getStudioKeys, liveTime, matchCombo, mergeStyleIntoTag, openAudioGainDialog, parseCombo, parseStyleString, persistRenderSettings, resolveDomEditSelection, resolveEquidistanceGuides, resolveGuideLineRect, resolveIframe, resolveSnapAdjustment, resolveSourceFile, revertNewestStudioPendingEdit, setStudioKeys, snapEngagedForTravel, studioKeyClash, useAudioGainDialogStore, useAudioMetersVisible, useClipboard, useCompositionStack, useDockLayoutStore, useDomEditSelectionContext, useDomEditSession, useDomEditZOrder, useDomGeometryCommit, useDomStyleCommit, useEditHistoryActions, useElementPicker, useLivePreviewIframe, useMarqueeGestures, usePersistentEditHistory, usePlayerHandle, usePlayerStore, usePreviewCompositionRect, usePreviewGuidesStore, usePreviewIframeStore, usePreviewOverlayContext, usePreviewPersistence, useProjectFileWriter, useRenderClipContent, useRenderQueue, useStudioKeys, useThumbnailStill, useTimelineContext, useTimelineEditing, useTimelinePlayer, zoomTimelineToRange };