All files / front_matter / any.ts

100.00% Branches 5/5
100.00% Lines 18/18
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
 
 
 
x2
x2
x2
 
x2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x24
x8
x8
x8
x10
x8
x9
x8
x10
x8
x9
x8
x8



















































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

import { extract as extractToml } from "./toml.ts";
import { extract as extractYaml } from "./yaml.ts";
import { extract as extractJson } from "./json.ts";
import type { Extract } from "./types.ts";
import { RECOGNIZE_REGEXP_MAP } from "./_formats.ts";

export type { Extract };

/**
 * Extracts and parses {@link https://yaml.org | YAML}, {@link https://toml.io |
 * TOML}, or {@link https://www.json.org/ | JSON} from the metadata of front
 * matter content, depending on the format.
 *
 * @example Usage
 * ```ts
 * import { extract } from "@std/front-matter/any";
 * import { assertEquals } from "@std/assert";
 *
 * const output = `---json
 * {
 *   "title": "Three dashes marks the spot"
 * }
 * ---
 * Hello, world!`;
 * const result = extract(output);
 * assertEquals(result, {
 *   frontMatter: '{\n  "title": "Three dashes marks the spot"\n}',
 *   body: "Hello, world!",
 *   attrs: { title: "Three dashes marks the spot" }
 * })
 * ```
 *
 * @typeParam T The type of the parsed front matter.
 * @param text The text to extract front matter from.
 * @returns The extracted front matter and body content.
 */
export function extract<T>(text: string): Extract<T> {
  const format = [...RECOGNIZE_REGEXP_MAP.entries()]
    .find(([_, regexp]) => regexp.test(text))?.[0];
  switch (format) {
    case "yaml":
      return extractYaml<T>(text);
    case "toml":
      return extractToml<T>(text);
    case "json":
      return extractJson<T>(text);
    default:
      throw new TypeError("Unsupported front matter format");
  }
}