forked from denoland/std
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunstable_yaml.ts
43 lines (40 loc) · 1.35 KB
/
unstable_yaml.ts
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
// Copyright 2018-2025 the Deno authors. MIT license.
import { extractFrontMatter } from "./_shared.ts";
import { parse, type ParseOptions } from "@std/yaml/parse";
import type { Extract } from "./types.ts";
import { EXTRACT_YAML_REGEXP } from "./_formats.ts";
export type { Extract };
/**
* Extracts and parses {@link https://yaml.org | YAML} from the metadata of
* front matter content.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @example Extract YAML front matter
* ```ts
* import { extract } from "@std/front-matter/unstable-yaml";
* import { assertEquals } from "@std/assert";
*
* const output = `---yaml
* date: 2022-01-01
* ---
* Hello, world!`;
* const result = extract(output, { schema: "json" });
*
* assertEquals(result, {
* frontMatter: "date: 2022-01-01",
* body: "Hello, world!",
* attrs: { date: "2022-01-01" },
* });
* ```
*
* @typeParam T The type of the parsed front matter.
* @param text The text to extract YAML front matter from.
* @param options The options to pass to `@std/yaml/parse`.
* @returns The extracted YAML front matter and body content.
*/
export function extract<T>(text: string, options?: ParseOptions): Extract<T> {
const { frontMatter, body } = extractFrontMatter(text, EXTRACT_YAML_REGEXP);
const attrs = parse(frontMatter, options) as T;
return { frontMatter, body, attrs };
}