All files / media_types / get_charset.ts

100.00% Branches 12/12
100.00% Lines 19/19
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
 
 
 
x10
 
x10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x10
x72
x72
x72
x74
x74
x131
x72
x139
x139
x193
x241
x241
x72
 
x92
x97
x72











































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

import { parseMediaType } from "./parse_media_type.ts";
import type { DBEntry } from "./_util.ts";
import { db, type KeyOfDb } from "./_db.ts";

/**
 * Given a media type or header value, identify the encoding charset. If the
 * charset cannot be determined, the function returns `undefined`.
 *
 * @param type The media type or header value to get the charset for.
 *
 * @returns The charset for the given media type or header value, or `undefined`
 * if the charset cannot be determined.
 *
 * @example Usage
 * ```ts
 * import { getCharset } from "@std/media-types/get-charset";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(getCharset("text/plain"), "UTF-8");
 * assertEquals(getCharset("application/foo"), undefined);
 * assertEquals(getCharset("application/news-checkgroups"), "US-ASCII");
 * assertEquals(getCharset("application/news-checkgroups; charset=UTF-8"), "UTF-8");
 * ```
 */
export function getCharset(type: string): string | undefined {
  try {
    const [mediaType, params] = parseMediaType(type);
    if (params?.charset) {
      return params.charset;
    }
    const entry = db[mediaType as KeyOfDb] as DBEntry;
    if (entry?.charset) {
      return entry.charset;
    }
    if (mediaType.startsWith("text/")) {
      return "UTF-8";
    }
  } catch {
    // just swallow errors, returning undefined
  }
  return undefined;
}