Repository navigation
Expand file tree
/
Copy pathmod.ts
More file actions
443 lines (397 loc) · 14 KB
/
Copy pathmod.ts
File metadata and controls
443 lines (397 loc) · 14 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import {
extractToml,
extractYaml,
test as hasFrontMatter,
} from "@std/front-matter";
import { basename, extname, join, relative } from "@std/path";
import type { SiteConfig, StenoPlugin } from "@steno/steno";
/**
* Basic info about one page carried into a generated term page's
* `steno.globals.items` array — exactly what a Tau layout needs to render
* `{#each items as item}` (title, url, description, date).
*/
export interface TermPageInfo {
/** Page title (frontmatter `title`, or a humanized filename fallback). */
title: string;
/** Site-relative route, e.g. `/posts/hello-world`. */
url: string;
/** Page description, if set. */
description?: string;
/** Page date as an ISO-ish string, if set. */
date?: string;
}
/** One real content page as fed into {@link buildTermIndex}. */
export interface TaxonomyPageInput extends TermPageInfo {
/** Every value this page carries in the configured taxonomy field. */
terms: string[];
}
/** One distinct term and every page that carries it. */
export interface TermEntry {
/** Term exactly as it appears in frontmatter (e.g. `"Rust"`). */
term: string;
/** URL-safe slug derived from `term`, unique within the taxonomy. */
slug: string;
/** Pages carrying this term, in the order they were scanned. */
pages: TermPageInfo[];
}
/** Per-taxonomy configuration. */
export interface TaxonomyConfig {
/**
* Taxonomy identifier. Used as the route prefix (`content/<name>/`) and as
* the default frontmatter field read from each page. Must be a bare path
* segment: letters, digits, `-`, `_` only.
*/
name: string;
/** Frontmatter field read from each page. Defaults to `name`. Accepts a single value or an array. */
field?: string;
/**
* Whether term pages should be eligible for per-term feeds. See the
* README's "Feeds" section — this does **not** generate feed XML itself;
* it only stamps `steno.globals.term.feed` for a theme/layout to act on.
*/
feed?: boolean;
/** Splits a term's page listing into pages of this size. `undefined` disables pagination. */
paginateBy?: number;
/** Static per-term metadata (icon, color, description, ...), keyed by the exact term string. */
termMeta?: Record<string, Record<string, unknown>>;
/** Layout for a single term page. Defaults to `"taxonomy-term"`. */
layout?: string;
/** Layout for the taxonomy's listing page. Defaults to `"taxonomy-list"`. */
listLayout?: string;
}
/** Options accepted by this plugin. */
export interface PluginTaxonomyOptions {
/** One entry per taxonomy. Required, non-empty. */
taxonomies: TaxonomyConfig[];
/** Content root to scan and write into. Defaults to `config.contentDir` (`content/`). */
contentDir?: string;
}
const MARKER_COMMENT = "<!-- generated by plugin-taxonomy, do not edit -->";
const MARKER_FILENAME = ".plugin-taxonomy-generated";
const NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
/**
* Slugifies a taxonomy term into a URL-safe path segment: lowercased,
* diacritics stripped, anything that isn't `[a-z0-9]` collapsed to a single
* `-`, leading/trailing `-` trimmed. Falls back to `"term"` if nothing
* survives (e.g. a term that's entirely punctuation/emoji).
*/
export function slugifyTerm(term: string): string {
const slug = term
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
return slug || "term";
}
/**
* Builds a term → pages index from a flat list of scanned pages. Pure — no
* filesystem access, so it's directly unit-testable with plain objects.
*
* Terms are sorted alphabetically; slugs are assigned in that order, and a
* collision (two distinct terms slugifying to the same value, e.g. `"C++"`
* and `"C--"` both → `"c"`) is resolved by appending `-2`, `-3`, ... to
* whichever term loses the tie.
*/
export function buildTermIndex(pages: TaxonomyPageInput[]): TermEntry[] {
const byTerm = new Map<string, TermPageInfo[]>();
for (const page of pages) {
for (const raw of page.terms) {
const term = raw.trim();
if (!term) continue;
const list = byTerm.get(term) ?? [];
list.push({
title: page.title,
url: page.url,
description: page.description,
date: page.date,
});
byTerm.set(term, list);
}
}
const usedSlugs = new Set<string>();
const entries: TermEntry[] = [];
for (const term of [...byTerm.keys()].sort((a, b) => a.localeCompare(b))) {
const base = slugifyTerm(term);
let slug = base;
let suffix = 2;
while (usedSlugs.has(slug)) {
slug = `${base}-${suffix++}`;
}
usedSlugs.add(slug);
entries.push({ term, slug, pages: byTerm.get(term)! });
}
return entries;
}
// ---------------------------------------------------------------------------
// Content-scanning helpers (fs-touching, not exported as "pure" API surface,
// but kept as small standalone functions for readability).
// ---------------------------------------------------------------------------
function readFrontMatter(text: string): Record<string, unknown> {
if (!hasFrontMatter(text)) return {};
try {
if (text.startsWith("+++")) {
return extractToml<Record<string, unknown>>(text).attrs;
}
return extractYaml<Record<string, unknown>>(text).attrs;
} catch {
return {};
}
}
function humanize(stem: string): string {
const spaced = stem.replace(/[-_]+/g, " ").trim();
return spaced.replace(/\b\w/g, (letter) => letter.toUpperCase()) || stem;
}
function toRoute(relativePath: string, isIndex: boolean): string {
const withoutExt = relativePath.slice(0, -extname(relativePath).length);
const segments = withoutExt.split("/").filter(Boolean);
if (isIndex) segments.pop();
return "/" + segments.join("/") + (segments.length ? "/" : "");
}
function toIsoDate(value: unknown): string | undefined {
if (value instanceof Date) return value.toISOString().slice(0, 10);
if (typeof value === "string") return value;
return undefined;
}
function readTerms(attrs: Record<string, unknown>, field: string): string[] {
const value = attrs[field];
if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
if (typeof value === "string") return [value];
return [];
}
/** Recursively collects every real (non-generated) content page under `dir`. */
async function scanPages(
dir: string,
contentRoot: string,
excludeDirs: Set<string>,
field: string,
): Promise<TaxonomyPageInput[]> {
let entries: Deno.DirEntry[] = [];
try {
entries = [...Deno.readDirSync(dir)];
} catch {
return [];
}
const pages: TaxonomyPageInput[] = [];
for (const entry of entries) {
if (entry.name.startsWith(".")) continue; // .steno/, dotfiles, our own marker file
const fullPath = join(dir, entry.name);
if (entry.isDirectory) {
if (excludeDirs.has(fullPath)) continue; // a taxonomy's own generated output
pages.push(...await scanPages(fullPath, contentRoot, excludeDirs, field));
continue;
}
if (!entry.isFile || !entry.name.endsWith(".md")) continue;
const text = await Deno.readTextFile(fullPath);
const attrs = readFrontMatter(text);
if (attrs.draft === true) continue;
const relPath = relative(contentRoot, fullPath);
const stem = basename(entry.name, extname(entry.name));
const isIndex = stem === "index";
const title = typeof attrs.title === "string"
? attrs.title
: humanize(stem);
const description = typeof attrs.description === "string"
? attrs.description
: undefined;
pages.push({
title,
url: toRoute(relPath, isIndex),
description,
date: toIsoDate(attrs.date),
terms: readTerms(attrs, field),
});
}
return pages;
}
function frontmatterBlock(fields: Record<string, unknown>): string {
const lines = ["---"];
for (const [key, value] of Object.entries(fields)) {
if (value === undefined) continue;
// JSON is a valid subset of YAML flow syntax, so this sidesteps needing
// a YAML stringifier while still round-tripping cleanly through
// @std/front-matter's YAML parser (arrays/objects included).
lines.push(`${key}: ${JSON.stringify(value)}`);
}
lines.push("---", "");
return lines.join("\n");
}
async function writeGeneratedFile(
path: string,
fields: Record<string, unknown>,
): Promise<void> {
await Deno.mkdir(path.slice(0, path.lastIndexOf("/")), { recursive: true });
await Deno.writeTextFile(
path,
frontmatterBlock(fields) + MARKER_COMMENT + "\n",
);
}
/** Ensures `outputDir` is either absent or previously generated by this plugin, then empties it. */
async function resetGeneratedDir(
outputDir: string,
taxonomyName: string,
): Promise<void> {
let stat: Deno.FileInfo;
try {
stat = await Deno.stat(outputDir);
} catch {
return; // doesn't exist yet — nothing to reset
}
if (!stat.isDirectory) {
throw new Error(
`taxonomy: content/${taxonomyName} exists and is not a directory. Rename it or choose a different taxonomies[].name.`,
);
}
const markerPath = join(outputDir, MARKER_FILENAME);
const isOurs = await Deno.stat(markerPath).then(() => true).catch(() =>
false
);
if (!isOurs) {
throw new Error(
`taxonomy: refusing to overwrite content/${taxonomyName}/ — it already exists and wasn't generated by ` +
`plugin-taxonomy (no ${MARKER_FILENAME} marker found inside it). Rename or remove that folder, or pick ` +
`a different taxonomies[].name.`,
);
}
await Deno.remove(outputDir, { recursive: true });
}
function chunk<T>(items: T[], size: number): T[][] {
const chunks: T[][] = [];
for (let i = 0; i < items.length; i += size) {
chunks.push(items.slice(i, i + size));
}
return chunks;
}
async function generateTaxonomy(
contentRoot: string,
taxonomy: TaxonomyConfig,
allPages: TaxonomyPageInput[],
): Promise<void> {
if (!NAME_PATTERN.test(taxonomy.name)) {
throw new Error(
`taxonomy: invalid taxonomies[].name "${taxonomy.name}" — must match ${NAME_PATTERN} (used as a content/ path segment).`,
);
}
const outputDir = join(contentRoot, taxonomy.name);
await resetGeneratedDir(outputDir, taxonomy.name);
await Deno.mkdir(outputDir, { recursive: true });
await Deno.writeTextFile(
join(outputDir, MARKER_FILENAME),
MARKER_COMMENT + "\n",
);
const entries = buildTermIndex(allPages);
const listLayout = taxonomy.listLayout ?? "taxonomy-list";
const termLayout = taxonomy.layout ?? "taxonomy-term";
const perPage = taxonomy.paginateBy;
const listTerms = entries.map((entry) => ({
name: entry.term,
slug: entry.slug,
url: `/${taxonomy.name}/${entry.slug}/`,
count: entry.pages.length,
...taxonomy.termMeta?.[entry.term],
}));
await writeGeneratedFile(join(outputDir, "index.md"), {
title: humanize(taxonomy.name),
layout: listLayout,
steno: {
globals: {
taxonomy: taxonomy.name,
terms: listTerms,
},
},
});
for (const entry of entries) {
const pageChunks = perPage && perPage > 0
? chunk(entry.pages, perPage)
: [entry.pages];
const totalPages = pageChunks.length;
for (let i = 0; i < pageChunks.length; i++) {
const pageNum = i + 1;
const filePath = pageNum === 1
? join(outputDir, `${entry.slug}.md`)
: join(outputDir, entry.slug, "page", `${pageNum}.md`);
await writeGeneratedFile(filePath, {
title: entry.term,
layout: termLayout,
steno: {
globals: {
taxonomy: taxonomy.name,
term: {
name: entry.term,
slug: entry.slug,
count: entry.pages.length,
feed: taxonomy.feed ?? false,
...taxonomy.termMeta?.[entry.term],
},
items: pageChunks[i],
pagination: {
page: pageNum,
totalPages,
perPage: perPage ?? entry.pages.length,
},
},
},
});
}
}
}
/**
* Creates the plugin-taxonomy plugin.
*
* Steno's `StenoPlugin` contract has no hook for registering brand-new
* routes directly — `afterPage`/`afterBuild` only ever see pages Steno
* already rendered from real content files. This plugin uses the same
* technique as the official `@steno/plugin-docs` plugin: in `beforeBuild`,
* before Steno's own content discovery runs, it scans every real page under
* `contentDir`, groups them by the configured frontmatter field, and writes
* synthetic Markdown files into `contentDir/<name>/` — one per term plus a
* listing index. Steno then discovers and renders them completely normally,
* through the theme, with layouts, everything. See the README for the full
* rationale and the exact shape written to `steno.globals`.
*
* ```yaml
* plugins:
* - package: jsr:@you/plugin-taxonomy
* options:
* taxonomies:
* - name: tags
* feed: true
* paginateBy: 10
* - name: categories
* feed: true
* ```
*/
export default function pluginTaxonomy(
options: PluginTaxonomyOptions,
): StenoPlugin {
if (!options?.taxonomies || options.taxonomies.length === 0) {
throw new Error("taxonomy: options.taxonomies must be a non-empty array.");
}
for (const taxonomy of options.taxonomies) {
if (!NAME_PATTERN.test(taxonomy.name)) {
throw new Error(
`taxonomy: invalid taxonomies[].name "${taxonomy.name}" — must match ${NAME_PATTERN} (used as a content/ path segment).`,
);
}
}
return {
name: "plugin-taxonomy",
async beforeBuild(config: SiteConfig) {
const contentRoot = options.contentDir ?? config.contentDir ?? "content";
const excludeDirs = new Set(
options.taxonomies.map((t) => join(contentRoot, t.name)),
);
for (const taxonomy of options.taxonomies) {
const field = taxonomy.field ?? taxonomy.name;
const pages = await scanPages(
contentRoot,
contentRoot,
excludeDirs,
field,
);
await generateTaxonomy(contentRoot, taxonomy, pages);
}
},
};
}