2024-07-11 06:43:36 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
|
|
|
2024-08-08 21:02:08 +00:00
|
|
|
import { type Format, RECOGNIZE_REGEXP_MAP } from "./_formats.ts";
|
2024-07-11 06:43:36 +00:00
|
|
|
import type { Extract } from "./types.ts";
|
|
|
|
|
|
|
|
/** Parser function type */
|
|
|
|
export type Parser = <T = Record<string, unknown>>(str: string) => T;
|
|
|
|
|
|
|
|
export function extractAndParse<T>(
|
|
|
|
input: string,
|
|
|
|
extractRegExp: RegExp,
|
|
|
|
parse: Parser,
|
|
|
|
): Extract<T> {
|
|
|
|
const match = extractRegExp.exec(input);
|
|
|
|
if (!match || match.index !== 0) {
|
|
|
|
throw new TypeError("Unexpected end of input");
|
|
|
|
}
|
refactor(archive,async,cli,csv,dotenv,encoding,expect,fmt,front-matter,fs,http,internal,log,net,path,semver,testing,text,webgpu,yaml): enable `"exactOptionalPropertyTypes"` option (#5892)
2024-09-04 05:15:01 +00:00
|
|
|
const frontMatter = match.at(-1)?.replace(/^\s+|\s+$/g, "") ?? "";
|
2024-07-11 06:43:36 +00:00
|
|
|
const attrs = parse(frontMatter) as T;
|
|
|
|
const body = input.replace(match[0], "");
|
|
|
|
return { frontMatter, body, attrs };
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Recognizes the format of the front matter in a string.
|
|
|
|
* Supports {@link https://yaml.org | YAML}, {@link https://toml.io | TOML} and
|
|
|
|
* {@link https://www.json.org/ | JSON}.
|
|
|
|
*
|
|
|
|
* @param str String to recognize.
|
|
|
|
* @param formats A list of formats to recognize. Defaults to all supported formats.
|
|
|
|
*/
|
|
|
|
export function recognize(
|
|
|
|
str: string,
|
|
|
|
formats: Format[],
|
|
|
|
): Format {
|
|
|
|
const [firstLine] = str.split(/(\r?\n)/) as [string];
|
|
|
|
|
|
|
|
for (const format of formats) {
|
|
|
|
if (RECOGNIZE_REGEXP_MAP.get(format)?.test(firstLine)) return format;
|
|
|
|
}
|
|
|
|
|
2024-08-21 05:42:02 +00:00
|
|
|
throw new TypeError("Unsupported front matter format");
|
2024-07-11 06:43:36 +00:00
|
|
|
}
|