-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
63 lines (53 loc) · 1.9 KB
/
index.ts
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
import deepmerge from 'deepmerge';
import Metalsmith from 'metalsmith';
import readingTime, { Options as ReadingTimeOptions } from 'reading-time';
export interface Options {
pattern?: string;
stripHtml?: boolean;
replacements?: [string | RegExp, string][];
readingTime?: ReadingTimeOptions;
}
export default (options: Options = {}): Metalsmith.Plugin => {
const defaultedOptions = deepmerge(
{
pattern: '**/*',
stripHtml: true,
replacements: [],
readingTime: {},
} satisfies Options,
options || {},
);
return (files, metalsmith, done) => {
const debug = metalsmith.debug('metalsmith-reading time');
debug('running with options: %O', defaultedOptions);
// For each file that matches the given pattern
metalsmith.match(defaultedOptions.pattern, Object.keys(files)).forEach((filename) => {
debug('processing file: %s', filename);
let contents = files[filename].contents.toString();
if (defaultedOptions.stripHtml) {
contents = contents
// XML
.replace(/<\?xml[^>]+\?>/gs, ' ') // namespaces
.replace(/<!--.*?-->/gs, ' ') // comments
// HTML
.replace(/<[a-zA-Z0-9]+[^>]*>/gs, ' ') // start tag
.replace(/<\/[a-zA-Z0-9]+>/gs, ' ') // end tag
.trim();
}
if (defaultedOptions.replacements && defaultedOptions.replacements.length) {
defaultedOptions.replacements.forEach((replacement) => {
let pattern = replacement[0];
if (typeof pattern === 'string') {
const matches = pattern.match(/^\/(.+)\/([a-z]*)/);
if (matches) {
pattern = new RegExp(matches[1], matches[2]);
}
}
contents = contents.replace(pattern, replacement[1]);
});
}
files[filename].readingTime = readingTime(contents, defaultedOptions.readingTime).text;
});
done();
};
};