Accept Header Negotiation With Quality Values

Parse Accept headers with q-values and wildcards, then pick the best supported media type while honoring q=0 exclusions and server order.

JavascriptData Fetching

Code

snippet
export function parseAcceptHeader(header) {
  if (typeof header !== "string" || header.trim() === "") {
    return [{ type: "*", subtype: "*", q: 1, params: {}, order: 0 }];
  }
  const ranges = [];
  for (const [order, part] of header.split(",").entries()) {
    const segments = part.split(";").map((segment) => segment.trim());
    const mediaRange = segments.shift();
    if (!mediaRange) continue;
    const slash = mediaRange.indexOf("/");
    if (slash <= 0 || slash === mediaRange.length - 1) {
      throw new SyntaxError("invalid media range: " + mediaRange);
    }
    const type = mediaRange.slice(0, slash).toLowerCase();
    const subtype = mediaRange.slice(slash + 1).toLowerCase();
    const params = {};
    let q = 1;
    for (const segment of segments) {
      if (!segment) continue;
      const equals = segment.indexOf("=");
      if (equals <= 0) throw new SyntaxError("invalid parameter: " + segment);
      const name = segment.slice(0, equals).trim().toLowerCase();
      const raw = segment.slice(equals + 1).trim().replace(/^"|"$/g, "");
      if (name === "q") {
        q = Number(raw);
        if (!Number.isFinite(q) || q < 0 || q > 1) {
          throw new RangeError("invalid q value: " + raw);
        }
      } else {
        params[name] = raw;
      }
    }
    ranges.push({ type, subtype, q, params, order });
  }
  if (ranges.length === 0) throw new SyntaxError("Accept header has no media ranges");
  return ranges;
}

export function negotiateContentType(header, supported) {
  if (!Array.isArray(supported) || supported.length === 0) {
    throw new TypeError("supported must be a non-empty array");
  }
  const ranges = parseAcceptHeader(header);
  const candidates = [];
  for (const [order, mediaType] of supported.entries()) {
    const slash = mediaType.indexOf("/");
    if (slash <= 0) throw new TypeError("invalid supported media type: " + mediaType);
    const type = mediaType.slice(0, slash).toLowerCase();
    const subtype = mediaType.slice(slash + 1).toLowerCase();
    let best;
    for (const range of ranges) {
      const typeMatches = range.type === "*" || range.type === type;
      const subtypeMatches = range.subtype === "*" || range.subtype === subtype;
      if (!typeMatches || !subtypeMatches) continue;
      const specificity = (range.type === "*" ? 0 : 1) + (range.subtype === "*" ? 0 : 1);
      if (!best || specificity > best.specificity ||
        (specificity === best.specificity && range.order < best.order)) {
        best = { q: range.q, specificity, order: range.order };
      }
    }
    if (best && best.q > 0) {
      candidates.push({ mediaType, q: best.q, specificity: best.specificity, order });
    }
  }
  candidates.sort((a, b) => b.q - a.q || b.specificity - a.specificity || a.order - b.order);
  return candidates.length > 0 ? candidates[0].mediaType : null;
}