-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathstatic-redirects.ts
More file actions
224 lines (189 loc) · 7.18 KB
/
static-redirects.ts
File metadata and controls
224 lines (189 loc) · 7.18 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
import url from "node:url";
import type { AstroConfig, AstroIntegrationLogger } from "astro";
import path from "node:path";
import fs from "node:fs/promises";
import { globby } from "globby";
import matter from "gray-matter";
const redirectMap = new Map<string, string>();
export async function configurePlugin(hookOptions: any) {
const buildOutput: string = hookOptions.buildOutput;
const config: AstroConfig = hookOptions.config;
const logger: AstroIntegrationLogger = hookOptions.logger;
if (buildOutput !== "static") {
logger.warn(
`Skip generating static redirects: not compatible with '${buildOutput}' builds, only 'static' is supported.`,
);
return;
}
// Find redirects
const redirects = config.redirects;
if (!Object.keys(redirects).length) {
logger.warn("Skip generating static redirects: no redirects found.");
return;
}
// Build redirect map
logger.info("Generating static redirects file...");
for (const [from, redirect] of Object.entries(redirects)) {
const destination =
typeof redirect === "string" ? redirect : redirect.destination;
// Normalize: strip trailing slash from source for consistent matching
const normalizedFrom = from.endsWith("/") ? from.slice(0, -1) : from;
// Ensure destination has trailing slash
const normalizedTo = destination.endsWith("/")
? destination
: destination + "/";
redirectMap.set(normalizedFrom, normalizedTo);
}
const contentDir = path.join(
url.fileURLToPath(config.srcDir),
"content",
"docs",
);
// Detect duplicate redirect_from entries across content files.
// We cannot detect duplicates from config.redirects alone: astro-redirect-from
// builds a plain JS object from frontmatter, so when two files declare the same
// redirect_from path, the second silently overwrites the first before our hook
// ever runs. Scanning frontmatter directly is the only way to catch these.
await detectDuplicateRedirects(logger, contentDir);
}
/**
* Reads a file in chunks until the closing `---` of the YAML frontmatter block
* is found, then returns only those bytes. This avoids loading the full file
* body. The loop keeps reading until the delimiter is seen or EOF is reached.
*/
async function extractFrontmatterBlock(filePath: string): Promise<string> {
const CHUNK_SIZE = 4096;
const handle = await fs.open(filePath, "r");
try {
let accumulated = "";
let offset = 0;
let firstChunk = true;
// searchFrom tracks how far we've already scanned for the closing delimiter
// so each chunk addition only rescans the newly added bytes.
let searchFrom = 0;
while (true) {
const buf = Buffer.alloc(CHUNK_SIZE);
const { bytesRead } = await handle.read(buf, 0, CHUNK_SIZE, offset);
if (bytesRead === 0) break;
const chunk = buf.toString("utf-8", 0, bytesRead);
accumulated += chunk;
offset += bytesRead;
// After reading the first chunk, bail out early for files without frontmatter
if (firstChunk) {
firstChunk = false;
if (!accumulated.startsWith("---")) return "";
// Skip past the opening --- line before searching for the closing one
searchFrom = accumulated.indexOf("\n") + 1;
}
// Search for the closing --- delimiter starting where we left off
const closingIdx = accumulated.indexOf("\n---", searchFrom);
if (closingIdx !== -1) {
// Include the closing delimiter line in the returned block
const endIdx = accumulated.indexOf("\n", closingIdx + 1);
return endIdx === -1
? accumulated.slice(0, closingIdx + 4)
: accumulated.slice(0, endIdx + 1);
}
// Advance searchFrom so the next iteration only scans the new chunk,
// minus a small overlap to avoid splitting a \n--- across chunk boundaries.
searchFrom = Math.max(searchFrom, accumulated.length - 4);
if (bytesRead < CHUNK_SIZE) break; // reached EOF before closing delimiter
}
// No closing --- found. gray-matter returns empty data for malformed
// frontmatter, so the caller's redirect_from check will safely skip this file.
return accumulated;
} finally {
await handle.close();
}
}
async function detectDuplicateRedirects(
logger: AstroIntegrationLogger,
contentDir: string,
) {
const files = await globby("./**/*.{md,mdx}", {
cwd: contentDir,
gitignore: true,
});
// Map each redirect source path to the list of files that claim it
const sourceToFiles = new Map<string, string[]>();
for (const file of files) {
const filePath = path.join(contentDir, file);
// Read only the frontmatter block, scanning until the closing --- delimiter
// regardless of how large the frontmatter may be.
const frontmatterBlock = await extractFrontmatterBlock(filePath);
if (!frontmatterBlock.includes("redirect_from")) continue;
const { data: frontmatter } = matter(frontmatterBlock);
if (!frontmatter?.redirect_from) continue;
const redirectFrom: string[] = Array.isArray(frontmatter.redirect_from)
? frontmatter.redirect_from
: [frontmatter.redirect_from];
const normalizeRedirectSource = (source: string) => {
const trimmed = source.trim();
if (trimmed !== source) {
logger.warn(
`Trimmed whitespace from redirect_from entry in ${file}: ${JSON.stringify(source)} -> ${JSON.stringify(trimmed)}`,
);
}
return trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
};
for (const source of redirectFrom) {
const normalized = normalizeRedirectSource(source);
const existing = sourceToFiles.get(normalized);
if (existing) {
existing.push(file);
} else {
sourceToFiles.set(normalized, [file]);
}
}
}
let duplicateCount = 0;
for (const [source, claimingFiles] of sourceToFiles) {
if (claimingFiles.length > 1) {
if (duplicateCount === 0) {
logger.error("Duplicate redirect_from entries detected:");
}
duplicateCount++;
logger.error(
` "${source}" is claimed by ${claimingFiles.length} files: ${claimingFiles.join(", ")}`,
);
}
}
if (duplicateCount > 0) {
throw new Error(
`Build failed: ${duplicateCount} duplicate redirect_from source(s) detected. See log above for details.`,
);
}
}
export async function writeToOutput(hookOptions: any) {
const outDir: string = hookOptions.dir;
const logger: AstroIntegrationLogger = hookOptions.logger;
if (redirectMap.size === 0) {
logger.warn(
`Skip generating static redirects file: no redirects were generated.`,
);
return;
}
const jsonDestinationPath = path.join(
url.fileURLToPath(outDir),
"redirects.json",
);
await fs.writeFile(
jsonDestinationPath,
JSON.stringify(Object.fromEntries(redirectMap), null, 2),
"utf-8",
);
logger.info(
`Generated ${redirectMap.size} redirects: ${jsonDestinationPath}`,
);
}
export default function staticRedirects() {
return {
name: "static-redirects",
hooks: {
"astro:config:done": async (hookOptions: any) =>
await configurePlugin(hookOptions),
"astro:build:done": async (hookOptions: any) =>
await writeToOutput(hookOptions),
},
};
}