std/front_matter/yaml.ts
Michael Ekstrand 06d83831fb
feat(front-matter/unstable): add pass-through ParseOptions argument for YAML parser (#5748)
* add options to front_matter/yaml/extract

* fix lint error on type import

* add unstable overload, add example

---------

Co-authored-by: Yoshiya Hinosawa <stibium121@gmail.com>
2024-08-21 16:41:53 +10:00

74 lines
2.2 KiB
TypeScript

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { extractAndParse, type Parser } 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.
*
* @example Extract YAML front matter
* ```ts
* import { extract } from "@std/front-matter/yaml";
* import { assertEquals } from "@std/assert";
*
* const output = `---yaml
* title: Three dashes marks the spot
* ---
* Hello, world!`;
* const result = extract(output);
*
* assertEquals(result, {
* frontMatter: "title: Three dashes marks the spot",
* 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 YAML front matter from.
* @returns The extracted YAML front matter and body content.
*/
export function extract<T>(text: string): Extract<T>;
/**
* 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/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>;
export function extract<T>(text: string, options?: ParseOptions): Extract<T> {
return extractAndParse(
text,
EXTRACT_YAML_REGEXP,
((s) => parse(s, options)) as Parser,
);
}