2021-09-02 05:15:31 -04:00
|
|
|
/*
|
2023-03-26 06:30:16 -04:00
|
|
|
* SPDX-FileCopyrightText: 2023 The HedgeDoc developers (see AUTHORS file)
|
2021-09-02 05:15:31 -04:00
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
2023-03-26 06:30:16 -04:00
|
|
|
import type { FrontmatterExtractionResult } from './types.js'
|
2021-09-02 05:15:31 -04:00
|
|
|
|
|
|
|
const FRONTMATTER_BEGIN_REGEX = /^-{3,}$/
|
|
|
|
const FRONTMATTER_END_REGEX = /^(?:-{3,}|\.{3,})$/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Extracts a frontmatter block from a given multiline string.
|
|
|
|
* A valid frontmatter block requires the content to start with a line containing at least three dashes.
|
|
|
|
* The block is terminated by a line containing the same amount of dashes or dots as the first line.
|
2021-12-14 04:16:25 -05:00
|
|
|
* @param lines The lines from which the frontmatter should be extracted.
|
2021-10-04 06:50:39 -04:00
|
|
|
* @return { isPresent } false if no frontmatter block could be found, true if a block was found.
|
2021-09-02 05:15:31 -04:00
|
|
|
* { rawFrontmatterText } if a block was found, this property contains the extracted text without the fencing.
|
|
|
|
* { frontmatterLines } if a block was found, this property contains the number of lines to skip from the
|
|
|
|
* given multiline string for retrieving the non-frontmatter content.
|
|
|
|
*/
|
2023-03-26 06:30:16 -04:00
|
|
|
export const extractFrontmatter = (
|
|
|
|
lines: string[]
|
2023-05-19 13:41:25 -04:00
|
|
|
): FrontmatterExtractionResult | undefined => {
|
2021-09-02 05:15:31 -04:00
|
|
|
if (lines.length < 2 || !FRONTMATTER_BEGIN_REGEX.test(lines[0])) {
|
2023-05-19 13:41:25 -04:00
|
|
|
return undefined
|
2021-09-02 05:15:31 -04:00
|
|
|
}
|
|
|
|
for (let i = 1; i < lines.length; i++) {
|
2023-03-26 06:30:16 -04:00
|
|
|
if (
|
|
|
|
lines[i].length === lines[0].length &&
|
|
|
|
FRONTMATTER_END_REGEX.test(lines[i])
|
|
|
|
) {
|
2021-09-02 05:15:31 -04:00
|
|
|
return {
|
2021-10-04 06:50:39 -04:00
|
|
|
rawText: lines.slice(1, i).join('\n'),
|
|
|
|
lineOffset: i + 1
|
2021-09-02 05:15:31 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-05-19 13:41:25 -04:00
|
|
|
return undefined
|
2021-09-02 05:15:31 -04:00
|
|
|
}
|