-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathposts.ts
More file actions
269 lines (244 loc) · 7.81 KB
/
Copy pathposts.ts
File metadata and controls
269 lines (244 loc) · 7.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import fs from "node:fs";
import path from "node:path";
import { load as parseYaml } from "js-yaml";
import { parse as parseToml } from "toml";
const POSTS_DIR = path.join(process.cwd(), "content", "posts");
const BLOG_INDEX_FILE = path.join(POSTS_DIR, "_index.md");
export const FALLBACK_IMAGE = "/images/HI60000_GetInvolvedBanner_V1.jpg";
export interface PostAuthor {
name?: string;
title?: string;
organization?: string;
link?: string;
image?: string;
}
export interface PostMeta {
slug: string;
title: string;
date: string;
abstract?: string;
featuredImage: string;
duration?: string;
authors: PostAuthor[];
categories: string[];
tags: string[];
}
export interface PostFull extends PostMeta {
contentMarkdown: string;
}
export interface BlogIndexMeta {
title: string;
subtitle: string;
listTitle: string;
}
export interface SimplePageContent {
title: string;
description: string;
contentMarkdown: string;
}
interface SimplePageDefaults {
title: string;
description: string;
}
function safeParseToml(input: string): object {
let s = input.replace(/\r/g, "");
// Convert bare dates (TOML 1.0 local dates) to datetime for TOML 0.4 compat
s = s.replace(/^(\s*\w+\s*=\s*)(\d{4}-\d{2}-\d{2})\s*$/gm, "$1$2T00:00:00Z");
if (!s.endsWith("\n")) s += "\n";
return parseToml(s);
}
interface FrontmatterResult {
data: Record<string, unknown>;
content: string;
}
function parseStructuredData(input: unknown): Record<string, unknown> {
if (!input || typeof input !== "object" || Array.isArray(input)) {
return {};
}
return input as Record<string, unknown>;
}
function extractFrontmatter(raw: string, delimiter: "+++" | "---") {
const normalized = raw.replace(/\r\n/g, "\n").replace(/^\uFEFF/, "");
const escaped = delimiter === "+++" ? "\\+\\+\\+" : "---";
const matcher = new RegExp(
`^[^\\S\\n]*${escaped}[^\\S\\n]*\\n([\\s\\S]*?)\\n?[^\\S\\n]*${escaped}[^\\S\\n]*(?:\\n|$)`,
);
const match = normalized.match(matcher);
if (!match) {
return null;
}
return {
frontmatter: match[1],
content: normalized.slice(match[0].length),
};
}
function parseTomlFrontmatter(raw: string): FrontmatterResult {
const extracted = extractFrontmatter(raw, "+++");
if (!extracted) {
return { data: {}, content: raw };
}
return {
data: parseStructuredData(safeParseToml(extracted.frontmatter)),
content: extracted.content,
};
}
function parseYamlFrontmatter(raw: string): FrontmatterResult {
const extracted = extractFrontmatter(raw, "---");
if (!extracted) {
return { data: {}, content: raw };
}
return {
data: parseStructuredData(parseYaml(extracted.frontmatter)),
content: extracted.content,
};
}
function cleanContent(content: string): string {
return content
.replace(/\{\{<[^>]*>\}\}/g, "")
.replace(/\{\{%[^%]*%\}\}/g, "")
.trim();
}
function parseDate(raw: unknown): string {
if (!raw) return new Date(0).toISOString();
if (raw instanceof Date) return raw.toISOString();
return new Date(String(raw)).toISOString();
}
function sanitizeSlug(raw: string): string {
// Normalize whitespace and case.
let slug = raw.trim().toLowerCase();
// Remove any characters that could break out of the path or introduce HTML/JS context.
slug = slug.replace(/["'<>\\]/g, "");
// Replace spaces and consecutive separators with single hyphens.
slug = slug.replace(/[\s_]+/g, "-");
// Remove URL‑unsafe characters except for word chars, hyphens, and forward slashes.
slug = slug.replace(/[^a-z0-9/-]+/g, "");
// Prevent path traversal and schemes like "javascript:" by removing leading dots and colons.
slug = slug.replace(/^[.:]+/, "");
// Collapse multiple slashes.
slug = slug.replace(/\/{2,}/g, "/");
// Trim leading/trailing slashes.
slug = slug.replace(/^\/+|\/+$/g, "");
return slug;
}
function deriveSlug(data: Record<string, unknown>, filename: string): string {
if (typeof data.slug === "string" && data.slug.trim()) {
return sanitizeSlug(data.slug);
}
const base = filename.replace(/\.md$/, "");
return sanitizeSlug(base);
}
function buildMeta(data: Record<string, unknown>, filename: string): PostMeta {
return {
slug: deriveSlug(data, filename),
title: String(data.title ?? ""),
date: parseDate(data.date),
abstract: data.abstract
? String(data.abstract)
: data.description
? String(data.description)
: undefined,
featuredImage: data.featured_image
? String(data.featured_image)
: FALLBACK_IMAGE,
duration: data.duration ? String(data.duration) : undefined,
authors: Array.isArray(data.authors)
? data.authors.map((a: Record<string, unknown>) => ({
name: a.name ? String(a.name) : undefined,
title: a.title ? String(a.title) : undefined,
organization: a.organization ? String(a.organization) : undefined,
link: a.link ? String(a.link) : undefined,
image: a.image ? String(a.image) : undefined,
}))
: [],
categories: Array.isArray(data.categories)
? data.categories.map(String)
: [],
tags: Array.isArray(data.tags) ? data.tags.map(String) : [],
};
}
export function getAllPosts(): PostMeta[] {
if (!fs.existsSync(POSTS_DIR)) return [];
const files = fs
.readdirSync(POSTS_DIR)
.filter(f => f.endsWith(".md") && f !== "_index.md");
const posts: PostMeta[] = [];
for (const file of files) {
try {
const raw = fs.readFileSync(path.join(POSTS_DIR, file), "utf8");
const { data } = parseTomlFrontmatter(raw);
if (data.draft === true) continue;
posts.push(buildMeta(data, file));
} catch {
/* skip */
}
}
posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
return posts;
}
export function getPostBySlug(slug: string): PostFull | null {
if (!fs.existsSync(POSTS_DIR)) return null;
const files = fs
.readdirSync(POSTS_DIR)
.filter(f => f.endsWith(".md") && f !== "_index.md");
for (const file of files) {
try {
const raw = fs.readFileSync(path.join(POSTS_DIR, file), "utf8");
const { data, content } = parseTomlFrontmatter(raw);
if (data.draft === true) continue;
if (deriveSlug(data, file) !== slug) continue;
return {
...buildMeta(data, file),
contentMarkdown: cleanContent(content),
};
} catch {
/* skip */
}
}
return null;
}
export function getBlogIndexMeta(): BlogIndexMeta {
const fallback: BlogIndexMeta = {
title: "Hiero Blog",
subtitle: "Stay up to date with our latest news and announcements.",
listTitle: "Recent Articles",
};
if (!fs.existsSync(BLOG_INDEX_FILE)) return fallback;
try {
const raw = fs.readFileSync(BLOG_INDEX_FILE, "utf8");
const { data } = parseTomlFrontmatter(raw);
return {
title: String(data.title ?? fallback.title),
subtitle: String(data.subtitle ?? fallback.subtitle),
listTitle: String(data.list_title ?? fallback.listTitle),
};
} catch {
return fallback;
}
}
/** Parse a simple content markdown file (e.g. hacktoberfest, heroes). */
export function getSimplePage(contentPath: string): SimplePageContent | null {
const filePath = path.join(process.cwd(), contentPath);
if (!fs.existsSync(filePath)) return null;
try {
const raw = fs.readFileSync(filePath, "utf8");
const { data, content } = parseYamlFrontmatter(raw);
return {
title: String(data.title ?? ""),
description: String(data.description ?? ""),
contentMarkdown: cleanContent(content),
};
} catch {
return null;
}
}
export function getSimplePageWithDefaults(
contentPath: string,
fallback: SimplePageDefaults,
): SimplePageContent {
const page = getSimplePage(contentPath);
return {
title: page?.title ?? fallback.title,
description: page?.description ?? fallback.description,
contentMarkdown: page?.contentMarkdown ?? "",
};
}