Files
Tom Moor 110c332727 fix: Byte range handling for media in Safari (#13695)
* fix: Byte range handling for media in Safari

Safari loads video and audio with byte range requests. Several forms of
Range header were mishandled by files.get: a suffix range fell through to
a full 200 response, a single byte request served the whole file, a range
past the end of the file produced an invalid Content-Range and a truncated
body, and a range starting past the end returned 400 rather than 416.

Also stop the service worker intercepting these requests. Partial
responses cannot be stored by the Cache API, so the route only produced
failed writes, and serving media through a service worker prevents
playback in Safari.

* Refactor to ByteRangeHelper
2026-09-07 20:18:36 -04:00

68 lines
1.8 KiB
TypeScript

/** A resolved byte range, inclusive at both ends. */
export interface ByteRange {
start: number;
end: number;
}
export class ByteRangeHelper {
/** Returned when the requested range lies entirely outside of the file. */
static readonly unsatisfiable: unique symbol = Symbol("unsatisfiable");
/**
* Parses a single byte range from a Range header, resolved against the size
* of the file being requested.
*
* @param header The value of the Range header, if any.
* @param size The size of the file in bytes.
* @returns The range to serve, `unsatisfiable` if it lies outside of the
* file, or undefined if the entire file should be served.
*/
static parse(
header: string | undefined,
size: number
): ByteRange | typeof ByteRangeHelper.unsatisfiable | undefined {
if (!header) {
return;
}
// Only a single range is supported, requests for multiple ranges are
// served in full instead.
const match = header.trim().match(/^bytes=(\d*)-(\d*)$/);
if (!match) {
return;
}
const [, first, last] = match;
if (size === 0) {
return this.unsatisfiable;
}
// A range with no start requests the final N bytes of the file.
if (first === "") {
const suffixLength = parseInt(last, 10);
if (isNaN(suffixLength)) {
return;
}
if (suffixLength === 0) {
return this.unsatisfiable;
}
return { start: Math.max(size - suffixLength, 0), end: size - 1 };
}
const start = parseInt(first, 10);
if (start >= size) {
return this.unsatisfiable;
}
// A range with no end, or one that runs past the file, ends at the last
// byte.
const end = last === "" ? size - 1 : Math.min(parseInt(last, 10), size - 1);
if (end < start) {
return this.unsatisfiable;
}
return { start, end };
}
}