Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 | 5x 19x 1x 10x 7x 7x 5x 5x 3x 4x 3x 3x 3x 3x 3x 2x 2x 2x 2x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Records the gameplay scene to a downloadable WebM Blob (VP9 / VP8 video, Opus audio).
*
* Two backends, picked at {@link GameplayRecorder.start}:
*
* - **WebCodecs + Mediabunny** (preferred; see `webcodecs-recorder.ts`). Frames and audio samples are stamped with the
* `AudioContext` clock the gameplay runs on, so picture and sound are in sync by construction, and the output is
* seekable as written.
* - **`MediaRecorder`** fallback for browsers without `VideoEncoder` / `AudioEncoder` / `AudioWorklet`, or without a
* WebM-compatible encoder. It records `canvas.captureStream` + a `MediaStreamAudioDestinationNode`; the browser
* stamps both on arrival, which leaves the picture a few tens of milliseconds ahead of the sound, and its output
* needs {@link makeWebMSeekable} before external players can seek in it.
*
* Both capture in real time, so the recording reflects what the player saw (frame skips and all) rather than an offline
* re-render.
*
* Usage:
*
* ```ts
* const recorder = new GameplayRecorder({ canvas, audioContext, audioOutput });
* recorder.start();
* // ... gameplay runs ...
* const result = await recorder.stop();
* downloadBlob(result.seekable ? result.blob : await makeWebMSeekable(result.blob), 'song.webm');
* ```
*
* Disposed instances throw on further calls; the host should construct a fresh recorder per recording session.
*/
import {
DEFAULT_RECORDING_FORMAT,
recorderMIMECandidates,
recordingFileExtension,
type RecordingFormat,
} from './recording-format.ts';
import { WebCodecsCapture, supportsWebCodecsRecording } from './webcodecs-recorder.ts';
export interface GameplayRecorderOptions {
/**
* The canvas to capture as the video track. Typically `host.app.canvas` from the `PixiSceneHost`. The recorder
* doesn't take ownership — disposing the recorder leaves the canvas alone.
*/
canvas: HTMLCanvasElement;
/**
* The play session's `AudioContext`. Used to allocate the `MediaStreamAudioDestinationNode` that taps the audio
* output for the audio track. The recorder doesn't close the context.
*/
audioContext: AudioContext;
/**
* Master output node to tap. The recorder calls `audioOutput.connect(mediaStreamDestination)` at start and
* disconnects on stop / dispose. Tapping this node — rather than `audioContext.destination` directly — is the only
* way Web Audio exposes the live output for capture.
*/
audioOutput: AudioNode;
/**
* Maximum frames per second to capture. Defaults to 60 to match the gameplay tick. Frames are taken as the scene
* paints them (one per animation frame, thinned to this rate), so a display faster than `fps` is sampled down and a
* lower value (e.g. 30) produces a smaller output at the cost of jerkier scrolling notes.
*/
fps?: number;
/**
* Bits-per-second target for the video track. Defaults to ~5 Mbps which gives reasonable quality for a 1280×720 LR2
* design space without bloating the file. Honored only when the picked codec / browser respects the hint.
*/
videoBitsPerSecond?: number;
/**
* Bits-per-second target for the audio track. Defaults to 192 kbps Opus — enough for stereo BMS keysound stacks
* without obvious artefacts.
*/
audioBitsPerSecond?: number;
/**
* Optional explicit mime-type override. Use this only for testing / forcing a specific codec; production callers
* should rely on the built-in negotiation that picks the best supported variant.
*/
mimeType?: string;
/**
* Largest video frame to encode, in pixels. Defaults to 1920×1080. A canvas larger than this (a high-DPR display in a
* big window easily reaches 3000×2000) is scaled down to fit before encoding — software VP9 cannot keep up with such
* frames in real time, so the encoder starts dropping frames and the video stutters out of step with the audio.
*/
maxVideoSize?: { width: number; height: number };
/**
* Registers a callback to run right after every scene render and returns its unregister function — typically
* `(cb) => { app.ticker.add(cb, undefined, UPDATE_PRIORITY.UTILITY); return () => app.ticker.remove(cb); }`, which
* runs after Pixi's own render. Frames are then read while the freshly drawn image is still in the canvas, stamped
* with the clock that drew it. Without it the recorder polls on its own `requestAnimationFrame`, which may run before
* the render and pick up the previous frame.
*/
subscribeFrame?: (onFrame: () => void) => () => void;
/**
* Which backend to use. `'auto'` (default) prefers WebCodecs and falls back to `MediaRecorder`; an explicit
* {@link mimeType} implies `'media-recorder'`.
*/
backend?: 'auto' | 'webcodecs' | 'media-recorder';
/**
* The container and video codec to record in. Defaults to {@link DEFAULT_RECORDING_FORMAT} (MP4 with H.264). When the
* browser cannot encode that codec the recorder takes the next one the container can carry, then any it can record.
*/
format?: RecordingFormat;
}
/**
* Output of a finished recording session. `mimeType` is the codec the browser actually used (matches the picked variant
* from the negotiation chain), useful for naming the downloaded file with the right extension. `blob` is the assembled
* video data.
*/
export interface GameplayRecorderResult {
blob: Blob;
mimeType: string;
durationMs: number;
/**
* Whether the file already carries its seek index (the WebCodecs backend, and MP4 from `MediaRecorder`); otherwise
* (WebM from `MediaRecorder`) run {@link makeWebMSeekable}.
*/
seekable: boolean;
}
/**
* Picks the first MIME type of `candidates` (by default the WebM chain: VP9 / VP8 with Opus, then without, then bare
* `video/webm`) that the runtime `MediaRecorder` claims to support. Returns `undefined` when no candidate is available (e.g. older Safari that lacks
* `MediaRecorder.isTypeSupported`); callers should treat that as "recording unavailable" rather than guessing.
*
* Exported for testing — production callers go through {@link GameplayRecorder.start} which calls this internally.
*/
export function pickRecorderMIMEType(
isSupported: (type: string) => boolean = (type) =>
typeof MediaRecorder !== 'undefined' &&
typeof MediaRecorder.isTypeSupported === 'function' &&
MediaRecorder.isTypeSupported(type),
candidates: readonly string[] = recorderMIMECandidates({ container: 'webm', videoCodec: 'vp9' }),
): string | undefined {
for (const candidate of candidates) {
if (isSupported(candidate)) return candidate;
}
return undefined;
}
/**
* Whether a frame-driven capture should take the frame painted at `nowMs`, given the last captured frame at `lastMs`
* (`undefined` before the first) and the target `fps`. At or above the display rate every painted frame is taken; below
* it frames are taken once their interval has (almost) elapsed — the small tolerance keeps a 30 fps target on 60 Hz
* from slipping to every third frame through rAF jitter.
*/
export function shouldCaptureFrame(nowMs: number, lastMs: number | undefined, fps: number): boolean {
if (lastMs === undefined || !Number.isFinite(fps) || fps <= 0) return true;
const interval = 1000 / fps;
return nowMs - lastMs >= interval - Math.min(4, interval * 0.25);
}
/**
* The encoded frame size for a `width`×`height` canvas: the canvas size itself when it fits inside `max`, otherwise the
* largest size of the same aspect ratio that does, rounded down to even dimensions (VP8 / VP9 encoders reject odd
* sizes).
*/
export function resolveCaptureSize(
width: number,
height: number,
max: { width: number; height: number },
): { width: number; height: number } {
const scale = Math.min(1, max.width / width, max.height / height);
if (scale >= 1) return { width, height };
return {
width: Math.max(2, Math.floor((width * scale) / 2) * 2),
height: Math.max(2, Math.floor((height * scale) / 2) * 2),
};
}
export class GameplayRecorder {
private readonly canvas: HTMLCanvasElement;
private readonly audioContext: AudioContext;
private readonly audioOutput: AudioNode;
private readonly fps: number;
private readonly videoBitsPerSecond: number;
private readonly audioBitsPerSecond: number;
private readonly explicitMIMEType: string | undefined;
private readonly maxVideoSize: { width: number; height: number };
private readonly subscribeFrame: ((onFrame: () => void) => () => void) | undefined;
private readonly backend: 'auto' | 'webcodecs' | 'media-recorder';
private readonly format: RecordingFormat;
/** The canvas frames are encoded from, and the copy that refreshes it (when the scene canvas is scaled down). */
private source: { canvas: HTMLCanvasElement; copy?: () => void } | undefined;
/** Active WebCodecs session, when that backend is in use. */
private capture: WebCodecsCapture | undefined;
private mediaRecorder: MediaRecorder | undefined;
private audioDestination: MediaStreamAudioDestinationNode | undefined;
/**
* The `MediaStream` returned by `canvas.captureStream`. Held so {@link stop} / {@link dispose} can release the
* stream's video tracks via `track.stop()`. `MediaRecorder.stop()` only ends the recording, not the underlying
* capture; the canvas' frame producer stays attached and burns CPU on every paint until each video track is
* explicitly stopped.
*/
private videoStream: MediaStream | undefined;
/** Unregisters the per-frame callback (see {@link startFrameLoop}). */
private stopFrames: (() => void) | undefined;
private chunks: Blob[] = [];
private startedAtMs = 0;
private recording = false;
private disposed = false;
public constructor(options: GameplayRecorderOptions) {
this.canvas = options.canvas;
this.audioContext = options.audioContext;
this.audioOutput = options.audioOutput;
this.fps = options.fps ?? 60;
this.videoBitsPerSecond = options.videoBitsPerSecond ?? 5_000_000;
this.audioBitsPerSecond = options.audioBitsPerSecond ?? 192_000;
this.explicitMIMEType = options.mimeType;
this.maxVideoSize = options.maxVideoSize ?? { width: 1920, height: 1080 };
this.subscribeFrame = options.subscribeFrame;
this.backend = options.mimeType !== undefined ? 'media-recorder' : (options.backend ?? 'auto');
this.format = options.format ?? DEFAULT_RECORDING_FORMAT;
}
public isActive(): boolean {
return this.recording;
}
/**
* Begins capture. Throws when:
*
* - Neither backend is available (no WebCodecs and no `MediaRecorder` / `canvas.captureStream` / supported MIME
* type). UI hosts should handle this gracefully (hide the record button, show a toast).
* - The recorder was previously stopped without a fresh instance (`disposed` flag) — recording is a one-shot per
* instance to keep the buffer lifecycle simple.
*
* The WebCodecs backend finishes its setup (codec probe, worklet load) asynchronously; capture begins once it is
* ready, a few tens of milliseconds in. If the setup fails the recorder switches to `MediaRecorder` on the spot.
*/
public start(): void {
if (this.disposed) {
throw new Error('GameplayRecorder.start: instance has already been disposed');
}
if (this.recording) {
throw new Error('GameplayRecorder.start: recording is already in progress');
}
const useWebCodecs =
this.backend === 'webcodecs' || (this.backend === 'auto' && supportsWebCodecsRecording(this.audioContext));
this.source = this.createCaptureSource();
if (useWebCodecs) {
this.startWebCodecs(this.source);
} else {
this.startMediaRecorder(this.source);
}
this.recording = true;
this.startedAtMs = performance.now();
}
/**
* Ends capture and resolves with the assembled video Blob plus the MIME type the browser used. Idempotent — calling
* on a non-active recorder resolves with `undefined`.
*
* Cleans up the audio tap regardless of state, so a `stop()` call also functions as a panic abort.
*/
public async stop(): Promise<GameplayRecorderResult | undefined> {
if (!this.recording) {
this.release();
return undefined;
}
this.recording = false;
this.stopFrameLoop();
const durationMs = performance.now() - this.startedAtMs;
const capture = this.capture;
if (capture) {
this.capture = undefined;
try {
const blob = await capture.finish();
return blob ? { blob, mimeType: blob.type, durationMs, seekable: true } : undefined;
} finally {
this.release();
}
}
const recorder = this.mediaRecorder;
if (!recorder || recorder.state === 'inactive') {
this.release();
return undefined;
}
const stopPromise = new Promise<void>((resolve) => {
recorder.addEventListener('stop', () => resolve(), { once: true });
});
recorder.stop();
await stopPromise;
const mimeType = recorder.mimeType || 'video/webm';
const blob = new Blob(this.chunks, { type: mimeType });
this.release();
return { blob, mimeType, durationMs, seekable: recordingFileExtension(mimeType) === 'mp4' };
}
/**
* Hard-stops without waiting for the final chunk. Discards any partially-collected data. Used by the gameplay view's
* `dispose` when the user ESCs out mid-recording — we don't want to dangle the audio tap and the user obviously isn't
* going to use the partial blob.
*/
public dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.recording = false;
this.capture?.dispose();
this.capture = undefined;
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
try {
this.mediaRecorder.stop();
} catch {
// Throws if state is already 'inactive' or never started. Both cases are fine — nothing more to do.
}
}
this.release();
}
private startWebCodecs(source: { canvas: HTMLCanvasElement; copy?: () => void }): void {
const capture = new WebCodecsCapture({
canvas: source.canvas,
audioContext: this.audioContext,
audioOutput: this.audioOutput,
fps: this.fps,
videoBitsPerSecond: this.videoBitsPerSecond,
audioBitsPerSecond: this.audioBitsPerSecond,
format: this.format,
});
this.capture = capture;
this.startFrameLoop(() => {
source.copy?.();
capture.captureFrame();
});
capture.prepare().catch((error: unknown) => {
if (this.capture !== capture) return;
// eslint-disable-next-line no-console
console.warn('[recorder] WebCodecs capture unavailable; falling back to MediaRecorder', error);
this.stopFrameLoop();
capture.dispose();
this.capture = undefined;
if (!this.recording) return;
try {
this.startMediaRecorder(source);
} catch (fallbackError) {
// eslint-disable-next-line no-console
console.warn('[recorder] MediaRecorder fallback failed too', fallbackError);
this.recording = false;
this.release();
}
});
}
private startMediaRecorder(source: { canvas: HTMLCanvasElement; copy?: () => void }): void {
const mimeType = this.explicitMIMEType ?? pickRecorderMIMEType(undefined, recorderMIMECandidates(this.format));
if (!mimeType) {
throw new Error('GameplayRecorder.start: browser exposes no supported MediaRecorder MIME type');
}
if (typeof source.canvas.captureStream !== 'function') {
throw new Error('GameplayRecorder.start: HTMLCanvasElement.captureStream is unavailable');
}
// Audio tap. The `MediaStreamAudioDestinationNode` is a dedicated sink — connecting `audioOutput` to it is
// additive, so live playback through `audioContext.destination` keeps working unchanged.
const audioDestination = this.audioContext.createMediaStreamDestination();
this.audioOutput.connect(audioDestination);
this.audioDestination = audioDestination;
// Frame-driven capture: `captureStream(fps)` samples the canvas on its own timer, which drifts against the render
// loop and drops frames (a 60 fps capture of a 60 fps render measured ~54 fps). Capturing with frame rate 0 and
// requesting a frame after every render takes exactly the frames the scene painted. Browsers without
// `requestFrame` fall back to the timer-driven capture.
const videoStream = source.canvas.captureStream(0);
const track = videoStream.getVideoTracks()[0] as CanvasCaptureMediaStreamTrack | undefined;
if (track && typeof track.requestFrame === 'function') {
this.videoStream = videoStream;
this.startFrameLoop(() => {
source.copy?.();
track.requestFrame();
});
} else {
for (const unused of videoStream.getTracks()) unused.stop();
this.videoStream = this.canvas.captureStream(this.fps);
}
// Combine canvas video + bus audio into a single stream so the recorder treats them as one timeline.
const combined = new MediaStream([
...this.videoStream.getVideoTracks(),
...audioDestination.stream.getAudioTracks(),
]);
const recorder = new MediaRecorder(combined, {
mimeType,
videoBitsPerSecond: this.videoBitsPerSecond,
audioBitsPerSecond: this.audioBitsPerSecond,
});
this.chunks = [];
recorder.ondataavailable = (event) => {
if (event.data.size > 0) {
this.chunks.push(event.data);
}
};
// 1-second chunk timeslice keeps memory bounded — without it the entire recording lives in a single Blob until
// stop(), which is fine for short sessions but punishes 5-minute LN grindfests.
recorder.start(1000);
this.mediaRecorder = recorder;
}
/**
* The canvas to capture: the scene canvas itself when it fits {@link maxVideoSize}, otherwise a smaller 2D canvas plus
* a `copy` that scales the current scene frame into it.
*/
private createCaptureSource(): { canvas: HTMLCanvasElement; copy?: () => void } {
const { width, height } = this.canvas;
const size = resolveCaptureSize(width, height, this.maxVideoSize);
if (size.width === width && size.height === height) return { canvas: this.canvas };
const target = document.createElement('canvas');
target.width = size.width;
target.height = size.height;
const context = target.getContext('2d', { alpha: false });
if (!context) return { canvas: this.canvas };
context.imageSmoothingQuality = 'high';
const copy = () => {
// The scene canvas can be resized mid-recording (window resize); stretch whatever it holds into the fixed frame.
context.drawImage(this.canvas, 0, 0, target.width, target.height);
};
copy();
return { canvas: target, copy };
}
/**
* Runs `onFrame` after every scene render (via {@link subscribeFrame}, else on each animation frame), thinned to
* {@link fps}, until {@link stopFrameLoop}.
*/
private startFrameLoop(onFrame: () => void): void {
this.stopFrameLoop();
let lastCapturedMs: number | undefined;
const tick = () => {
const nowMs = performance.now();
if (!shouldCaptureFrame(nowMs, lastCapturedMs, this.fps)) return;
lastCapturedMs = nowMs;
onFrame();
};
if (this.subscribeFrame) {
this.stopFrames = this.subscribeFrame(tick);
return;
}
let handle = 0;
const pump = () => {
tick();
handle = requestAnimationFrame(pump);
};
handle = requestAnimationFrame(pump);
this.stopFrames = () => cancelAnimationFrame(handle);
}
private stopFrameLoop(): void {
this.stopFrames?.();
this.stopFrames = undefined;
}
/** Releases every capture resource: frame loop, video tracks, audio tap and buffered chunks. Idempotent. */
private release(): void {
this.stopFrameLoop();
this.mediaRecorder = undefined;
this.chunks = [];
this.source = undefined;
this.releaseVideoStream();
this.detachAudioTap();
}
/**
* Stops every track on the captured `videoStream` and drops the reference. The browser keeps the capture pipeline
* alive (and burns CPU on every canvas paint) until `track.stop()` lands on each track, even after
* `MediaRecorder.stop()` returns. Idempotent — safe to call when the stream wasn't started or has already been
* released.
*/
private releaseVideoStream(): void {
const stream = this.videoStream;
if (!stream) return;
for (const track of stream.getTracks()) {
try {
track.stop();
} catch {
// Defensive — `track.stop()` throws on tracks that have already ended in some browser builds.
}
}
this.videoStream = undefined;
}
private detachAudioTap(): void {
if (!this.audioDestination) return;
try {
this.audioOutput.disconnect(this.audioDestination);
} catch {
// `disconnect(target)` throws when the edge isn't present. Defensive — `start` always connects before populating
// `audioDestination`, but the recorder can be torn down mid-construction if `start` itself threw after wiring.
}
this.audioDestination = undefined;
}
}
/**
* Rewrites a `MediaRecorder`-produced WebM blob so external video players can seek inside it.
*
* The problem: `MediaRecorder` writes a streaming WebM container with no `Duration` field on the EBML header and no
* `Cues` (seek index) at all — the spec doesn't require them for live captures. Most players (Chrome's <video>, Safari,
* VLC, QuickTime, Finder previews, Discord embeds) refuse to seek inside such a file: the scrub bar drags but the
* playhead snaps back to wherever the next cluster boundary happens to be. The user-visible symptom is exactly what was
* reported — the saved `.webm` plays, but you can't jump around inside it.
*
* The fix is to re-mux the file: Mediabunny reads the recorded packets and writes them into a fresh WebM, whose writer
* fills in `Duration`, `SeekHead` and `Cues`. Packets are copied as they are — never re-encoded (`copy.mode: 'forced'`)
* — and keep their timestamps (`trim.start: 0`), so picture, sound and sync stay exactly as recorded.
*
* Returns a fresh `Blob` of the same MIME type with seekable metadata. Falls back to the original blob (and logs a
* warning) when the input isn't a recognizable WebM container, a track could only be kept by re-encoding it, or the
* re-mux fails — better to hand the user the play-only file than to lose the recording outright.
*/
export async function makeWebMSeekable(blob: Blob): Promise<Blob> {
if (blob.size === 0) return blob;
// Loaded on demand (as in the WebCodecs backend) so Mediabunny stays out of the main bundle.
const { BlobSource, BufferTarget, Conversion, Input, MATROSKA, Output, WEBM, WebMOutputFormat } =
await import('mediabunny');
const input = new Input({ source: new BlobSource(blob), formats: [WEBM, MATROSKA] });
try {
const output = new Output({ format: new WebMOutputFormat(), target: new BufferTarget() });
const conversion = await Conversion.init({
input,
output,
copy: { mode: 'forced' },
trim: { start: 0 },
showWarnings: false,
});
Iif (!conversion.isValid || conversion.discardedTracks.length > 0) {
// eslint-disable-next-line no-console
console.warn('[recorder] cannot re-mux the recording without re-encoding; downloading raw blob');
return blob;
}
await conversion.execute();
const buffer = output.target.buffer;
return buffer ? new Blob([buffer], { type: blob.type }) : blob;
} catch (error) {
// eslint-disable-next-line no-console
console.warn('[recorder] failed to inject seekable metadata; downloading raw blob', error);
return blob;
} finally {
input.dispose();
}
}
/**
* Triggers a browser download of `blob` under `filename`. Pure convenience — the caller wires up the click handler.
*
* Revokes the temporary blob URL after the click has had a chance to register (next microtask) so the download still
* completes but the URL doesn't sit pinning the blob in memory.
*/
export function downloadBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
anchor.style.display = 'none';
document.body.appendChild(anchor);
anchor.click();
// Defer revoke to the next macrotask — Chrome / Firefox finalize the download synchronously after `click()` but
// Safari spreads the work across event-loop turns; revoking too eagerly there can cancel the in-flight download.
setTimeout(() => {
URL.revokeObjectURL(url);
anchor.remove();
}, 0);
}
|