|
| 1 | +type Validation = { |
| 2 | + message: string; |
| 3 | + validate: (t: string) => boolean; |
| 4 | +}; |
| 5 | + |
| 6 | +const validations: Validation[] = [ |
| 7 | + { |
| 8 | + message: "should start with a title", |
| 9 | + validate: (t) => !!t.match(/^#\s.+/), |
| 10 | + }, |
| 11 | + { |
| 12 | + message: "should not have multiple `#` headers", |
| 13 | + validate: (t) => !t.match(/[\n\r]#\s/), |
| 14 | + }, |
| 15 | + { |
| 16 | + message: "should have a summary description under the title", |
| 17 | + validate: (t) => { |
| 18 | + const [summary] = t.split(/[\n\r]##/) || [""]; |
| 19 | + const description = summary |
| 20 | + .split(/\n/) |
| 21 | + .slice(1) |
| 22 | + .filter((l) => l.length); |
| 23 | + return !!description.length; |
| 24 | + }, |
| 25 | + }, |
| 26 | + { |
| 27 | + message: "should have a level `##` with a format of `L[0-9]+`", |
| 28 | + validate: (t) => { |
| 29 | + const headers = t.match(/^#{2}\s(.+)$/gm) || []; |
| 30 | + console.log("level headers", headers); |
| 31 | + for (const header of headers) { |
| 32 | + if (!header.match(/^#{2}\s(L\d+)\s(.+)$/)) { |
| 33 | + return false; |
| 34 | + } |
| 35 | + } |
| 36 | + return true; |
| 37 | + }, |
| 38 | + }, |
| 39 | + { |
| 40 | + message: "should have a step `###` with a format of `L[0-9]+S[0-9]+`", |
| 41 | + validate: (t) => { |
| 42 | + const headers = t.match(/^#{3}\s(.+)$/gm) || []; |
| 43 | + console.log("step headers", headers); |
| 44 | + for (const header of headers) { |
| 45 | + if (!header.match(/^#{3}\s(L\d+)S\d+/)) { |
| 46 | + return false; |
| 47 | + } |
| 48 | + } |
| 49 | + return true; |
| 50 | + }, |
| 51 | + }, |
| 52 | +]; |
| 53 | + |
| 54 | +const codeBlockRegex = /```[a-z]*\n[\s\S]*?\n```/gm; |
| 55 | + |
1 | 56 | export function validateMarkdown(md: string): boolean {
|
2 |
| - // validate title (#) |
3 |
| - // validate description |
4 |
| - // validate level |
5 |
| - // validate steps |
6 |
| - // validate codeblock formats |
| 57 | + // remove codeblocks which might contain any valid combinations |
| 58 | + const text = md.replace(codeBlockRegex, ""); |
| 59 | + |
| 60 | + let valid = true; |
| 61 | + |
| 62 | + for (const v of validations) { |
| 63 | + if (!v.validate(text)) { |
| 64 | + valid = false; |
| 65 | + // if (process.env.NODE_ENV !== "test") { |
| 66 | + console.warn(v.message); |
| 67 | + // } |
| 68 | + } |
| 69 | + } |
7 | 70 |
|
8 |
| - return false; |
| 71 | + return valid; |
9 | 72 | }
|
0 commit comments