-
Notifications
You must be signed in to change notification settings - Fork 0
/
documentize.preprocessor.js
104 lines (82 loc) · 2.51 KB
/
documentize.preprocessor.js
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
// @ts-check
/// <reference lib="esnext" />
import { readFile, stat } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
/**
* Documentize Svelte components by inserting markdown content from adjacent files.
*
* @returns {import('svelte/compiler').PreprocessorGroup}
*/
export default function documentize() {
return {
name: 'documentize-preprocessor',
async markup(context) {
const { content, filename = '' } = context;
if (!filename.endsWith('.svelte')) {
return;
}
const newCode = await resolveMarkdownDoc(filename, content);
return {
code: newCode,
};
},
};
}
/**
* Process the component and its markup.
*
* @param {string} filename
* @param {string} markup
*/
async function resolveMarkdownDoc(filename, markup) {
const documentizeIdentifier = /<!-- @component -->/g;
if (!documentizeIdentifier.test(markup)) {
return markup;
}
const markdownFilename = filename.replace(/\.svelte$/, '.md');
const markdownExists = await stat(markdownFilename)
.then((stats) => stats.isFile())
.catch(() => false);
if (!markdownExists) {
console.error(`File '${filename}' is missing its documentation file at '${markdownFilename}'.`);
return markup;
}
const markdownContent = await readFile(markdownFilename, {
encoding: 'utf-8',
});
const processedMarkdown = await resolveIncludes(markdownFilename, markdownContent);
const newMarkup = markup.replaceAll(
documentizeIdentifier,
`<!--\n@component\n\n${processedMarkdown}\n-->`,
);
return newMarkup;
}
/**
* Process the includes in the file.
*
* @param {string} filename
* @param {string} markup
*/
async function resolveIncludes(filename, markup) {
const matches = markup.matchAll(/<!-- @include\((?<file>[0-9a-zA-Z/._-]+)\) -->/g);
for (const match of matches) {
const includeFilename = match.groups?.file;
if (!includeFilename) {
continue;
}
const filePath = resolve(dirname(filename), includeFilename);
const exists = await stat(filePath)
.then((stats) => stats.isFile())
.catch(() => false);
if (!exists) {
console.error(`File '${filename}' is missing its include file at '${filePath}'.`);
continue;
}
const includeContent = await readFile(filePath, {
encoding: 'utf-8',
});
const patchedContent = await resolveIncludes(filePath, includeContent.trim());
markup = markup.replaceAll(`<!-- @include(${includeFilename}) -->`, patchedContent);
}
return markup;
}