Skip to content
Myr

plugins.ts

This file

Path

src/helper/ssg/plugins.ts

72 lines · 1.9 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–72why, one step back
1import { html } from '../html'
2import type { SSGPlugin } from './ssg'34/**5 * The default plugin that defines the recommended behavior.6 *7 * @experimental8 * `defaultPlugin` is an experimental feature.9 * The API might be changed.10 */11export const defaultPlugin = (): SSGPlugin => {12 return {13 afterResponseHook: (res) => {14 if (res.status !== 200) {15 return false16 }17 return res18 },19 }20}2122const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308])2324const generateRedirectHtml = (location: string) => {25 // prettier-ignore26 const content = html`<!DOCTYPE html>27<title>Redirecting to: ${location}</title>28<meta http-equiv="refresh" content="0;url=${location}" />29<meta name="robots" content="noindex" />30<link rel="canonical" href="${location}" />31<body>32<a href="${location}">Redirecting to <code>${location}</code></a>33</body>34`35 return content.toString().replace(/\n/g, '')36}3738/**39 * The redirect plugin that generates HTML redirect pages for HTTP redirect responses for status codes 301, 302, 303, 307 and 308.40 *41 * When used with `defaultPlugin`, place `redirectPlugin` before it, because `defaultPlugin` skips non-200 responses.42 *43 * ```ts44 * // ✅ Will work as expected45 * toSSG(app, fs, { plugins: [redirectPlugin(), defaultPlugin()] })46 *47 * // ❌ Will not work as expected48 * toSSG(app, fs, { plugins: [defaultPlugin(), redirectPlugin()] })49 * ```50 *51 * @experimental52 * `redirectPlugin` is an experimental feature.53 * The API might be changed.54 */55export const redirectPlugin = (): SSGPlugin => {56 return {57 afterResponseHook: (res) => {58 if (REDIRECT_STATUS_CODES.has(res.status)) {59 const location = res.headers.get('Location')60 if (!location) {61 return false62 }63 const htmlBody = generateRedirectHtml(location)64 return new Response(htmlBody, {65 status: 200,66 headers: { 'Content-Type': 'text/html; charset=utf-8' },67 })68 }69 return res70 },71 }72}