forked from aymericbeaumet/metalsmith-redirect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (51 loc) · 1.76 KB
/
index.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
const _ = require('lodash');
const createRedirectionsFromArg = require('./lib/create-redirections-from-arg');
const createRedirectionsFromFrontmatters = require('./lib/create-redirections-from-frontmatters');
function escapeSingleQuotes(string) {
return string.replace(/'/g, '\\\'');
}
function escapeDoubleQuotes(string) {
return string.replace(/"/g, '\\"');
}
module.exports = (options = {}) => {
const noindex = (typeof options.noindex === 'undefined') ? true : Boolean(options.noindex);
const preserveHash = options.preserveHash ?
{
timeout: 1,
...(_.isObject(options.preserveHash) ? options.preserveHash : {})
} :
null;
return (files, _metalsmith, done) => {
const argRedirections = options.redirections ?
createRedirectionsFromArg(options.redirections, options) :
[];
const frontmattersRedirections = options.frontmatter ?
createRedirectionsFromFrontmatters(files, options) :
[];
for (const {normalizedSource, normalizedDestination} of [
...argRedirections,
...frontmattersRedirections
]) {
const contents = Buffer.from(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
${noindex ? '<meta name="robots" content="noindex">' : ''}
<meta http-equiv="refresh" content="${
preserveHash ? preserveHash.timeout : 0
};url=${escapeDoubleQuotes(normalizedDestination)}">
<link rel="canonical" href="${escapeDoubleQuotes(normalizedDestination)}">
<script>window.location.replace('${escapeSingleQuotes(
normalizedDestination
)}'${preserveHash ? ' + window.location.hash' : ''});</script>
</head>
<body>This page has been moved to <a href="${escapeDoubleQuotes(
normalizedDestination
)}">${normalizedDestination}</a></body>
</html>
`);
files[_.trimStart(normalizedSource, '/')] = {contents};
}
done();
};
};