1 |
|
2 |
|
3 | const yaml = require("js-yaml");
|
4 |
|
5 | const isValidMeta = meta => {
|
6 | if (
|
7 | meta == null ||
|
8 | typeof meta !== "object" ||
|
9 | Object.prototype.toString.call(meta) !== "[object Object]"
|
10 | ) {
|
11 | return false;
|
12 | }
|
13 | const keys = Object.keys(meta);
|
14 | for (const k of ["id", "tags"]) {
|
15 | if (keys.includes(k)) {
|
16 | return true;
|
17 | }
|
18 | }
|
19 | return false;
|
20 | };
|
21 |
|
22 | const toPost = text => {
|
23 | const lines = text.split(/\r?\n/);
|
24 | if (lines.length === 0) {
|
25 | return { meta: {}, body: text };
|
26 | }
|
27 | const firstLine = lines[0];
|
28 | if (firstLine !== "---") {
|
29 | return { meta: {}, body: text };
|
30 | }
|
31 |
|
32 | const headerLines = [];
|
33 | const len = lines.length;
|
34 | let found = false;
|
35 | let i = 1;
|
36 | for (; i < len; i++) {
|
37 | const line = lines[i];
|
38 | if (line === "---") {
|
39 | found = true;
|
40 | break;
|
41 | }
|
42 | headerLines.push(line);
|
43 | }
|
44 | if (!found) {
|
45 | return { meta: {}, body: text };
|
46 | }
|
47 |
|
48 | const headerText = headerLines.join("\n");
|
49 | const meta = yaml.load(headerText);
|
50 | if (!isValidMeta(meta)) {
|
51 | return { meta: {}, body: text };
|
52 | }
|
53 |
|
54 | const restLines = [];
|
55 | let checkEmpty = true;
|
56 | for (let j = i + 1; j < len; j++) {
|
57 | const line = lines[j];
|
58 | if (checkEmpty) {
|
59 | if (line === "") {
|
60 | continue;
|
61 | }
|
62 | checkEmpty = false;
|
63 | }
|
64 | restLines.push(line);
|
65 | }
|
66 | return { meta, body: restLines.join("\n") };
|
67 | };
|
68 |
|
69 | const toText = post => {
|
70 | const { meta, body } = post;
|
71 | if (!isValidMeta(meta)) {
|
72 | return body;
|
73 | }
|
74 | const h = yaml.safeDump(meta);
|
75 | return `---
|
76 | ${h}---
|
77 |
|
78 | ${body}
|
79 | `;
|
80 | };
|
81 |
|
82 | module.exports = { toPost, toText };
|