import { existsSync, statSync } from 'node:fs'
import { readdir, readFile } from 'node:fs/promises'
import path from 'node:path'
const LINK_TAG = /]*>/gu
const META_TAG = /]*>/gu
const ATTRIBUTE = /(?[\w:-]+)="(?[^"]*)"/gu
const SITEMAP_LOCATION = /(?[^<]+)<\/loc>/gu
export interface DeploymentCheckOptions {
/** The directory of the build / 构建产物所在的目录 */
dist: string
/** The base path the build is served at / 部署使用的基础路径 */
base: string
/** The origin serving the build, without the base path / 部署使用的源站,不含基础路径 */
hostname: string
/** The origin of the production site, the canonical one / 生产站点的源站,即首选地址 */
canonicalHostname: string
/** Whether search engines may index the build / 构建是否允许搜索引擎索引 */
indexable: boolean
}
interface Context {
dist: string
base: string
siteUrl: string
canonicalHostname: string
basePattern: string
indexable: boolean
}
const getAttributes = (tag: string): Record => {
const attributes: Record = {}
for (const { groups } of tag.matchAll(ATTRIBUTE))
if (groups) attributes[groups.name] = groups.value
return attributes
}
const walk = async (dir: string): Promise => {
const entries = await readdir(dir, { withFileTypes: true })
const files = await Promise.all(
entries.map(async (entry) => {
const file = path.join(dir, entry.name)
return entry.isDirectory() ? walk(file) : [file]
}),
)
return files.flat()
}
// the page path a built file is served at, where `dir/index.html` is `dir/`
const toPagePath = (dist: string, file: string): string => {
const relative = path.relative(dist, file).split(path.sep).join('/')
if (relative === 'index.html') return '/'
return relative.endsWith('/index.html')
? `/${relative.slice(0, -'index.html'.length)}`
: `/${relative}`
}
// whether a URL repeats the base path, which happens when the origin already
// contains it: the plugins join the origin, the base and the page path
const repeatsBase = (context: Context, url: string): boolean =>
context.base !== '/' &&
new URL(url, context.siteUrl).pathname.startsWith(context.basePattern)
const toFile = (context: Context, urlPath: string): string => {
const [pathname = ''] = urlPath.split(/[?#]/u)
const local = pathname.startsWith(context.base)
? pathname.slice(context.base.length)
: pathname
if (local.endsWith('/')) return path.join(context.dist, `${local}index.html`)
const file = path.join(context.dist, local)
return existsSync(file) && statSync(file).isDirectory()
? path.join(file, 'index.html')
: file
}
const checkHtmlLinks = (
context: Context,
errors: string[],
file: string,
html: string,
): boolean => {
const name = path.relative(context.dist, file)
const canonical = `${context.canonicalHostname}${toPagePath(context.dist, file)}`
let hasCanonical = false
for (const [tag] of html.matchAll(LINK_TAG)) {
const { href, hreflang, rel } = getAttributes(tag)
if (!href) continue
// Icons and the manifest are copied from the `public` directory as they
// are, so VuePress never prefixes them with the base.
if (
rel === 'icon' ||
rel === 'apple-touch-icon' ||
rel === 'mask-icon' ||
rel === 'manifest'
) {
if (!href.startsWith(context.base)) {
errors.push(
`${name}: "${href}" is not served under the base "${context.base}"`,
)
} else if (!existsSync(toFile(context, href))) {
errors.push(`${name}: "${href}" misses its file in the build`)
}
continue
}
// every page of every deployment points search engines at the production
// site, which owns the content
if (rel === 'canonical') {
hasCanonical = true
if (href !== canonical) {
errors.push(
`${name}: "${href}" is not the canonical URL "${canonical}"`,
)
}
continue
}
// Absolute URLs are built by joining the origin, the base and the page
// path, so a doubled base means one of them already contains the other.
if (rel === 'alternate' && hreflang) {
if (!href.startsWith(context.siteUrl)) {
errors.push(
`${name}: "${href}" is not an absolute URL of ${context.siteUrl}`,
)
} else if (repeatsBase(context, href)) {
errors.push(`${name}: "${href}" repeats the base path`)
}
}
}
return hasCanonical
}
const checkHtmlMeta = (
context: Context,
errors: string[],
file: string,
html: string,
): boolean => {
const name = path.relative(context.dist, file)
let hasNoindex = false
for (const [tag] of html.matchAll(META_TAG)) {
const { content, name: metaName, property } = getAttributes(tag)
if (!content) continue
if (metaName === 'robots' && content.includes('noindex')) hasNoindex = true
if (property !== 'og:url') continue
if (!content.startsWith(context.siteUrl)) {
errors.push(
`${name}: "og:url" of "${content}" is not under ${context.siteUrl}`,
)
} else if (repeatsBase(context, content)) {
errors.push(`${name}: "og:url" of "${content}" repeats the base path`)
}
}
return hasNoindex
}
const checkHtml = (
context: Context,
errors: string[],
file: string,
html: string,
): void => {
const name = path.relative(context.dist, file)
const canonical = `${context.canonicalHostname}${toPagePath(context.dist, file)}`
const hasNoindex = checkHtmlMeta(context, errors, file, html)
if (!checkHtmlLinks(context, errors, file, html))
errors.push(`${name}: misses its canonical URL "${canonical}"`)
// the mirror copies the production site, so only the production site may be
// indexed, and a page must say so either way
if (context.indexable && hasNoindex)
errors.push(`${name}: is marked "noindex" although it is indexable`)
if (!context.indexable && !hasNoindex)
errors.push(`${name}: is not marked "noindex" although it is a copy`)
}
const checkSitemap = async (
context: Context,
errors: string[],
file: string,
): Promise => {
const name = path.relative(context.dist, file)
for (const { groups } of (await readFile(file, 'utf8')).matchAll(
SITEMAP_LOCATION,
)) {
const loc = groups?.loc
if (!loc) continue
if (!loc.startsWith(context.siteUrl))
errors.push(`${name}: "${loc}" is not under ${context.siteUrl}`)
else if (repeatsBase(context, loc))
errors.push(`${name}: "${loc}" repeats the base path`)
else if (!existsSync(toFile(context, new URL(loc).pathname)))
errors.push(`${name}: "${loc}" misses its page in the build`)
}
}
const checkRobots = async (
context: Context,
errors: string[],
file: string,
hasSitemap: boolean,
): Promise => {
const name = path.relative(context.dist, file)
const content = await readFile(file, 'utf8')
const expected = `Sitemap: ${context.siteUrl}sitemap.xml`
// a sitemap advertises pages to search engines, which contradicts a build
// that must not be indexed
if (hasSitemap && !content.includes(expected))
errors.push(`${name}: "${expected}" is missing`)
else if (!hasSitemap && content.includes('Sitemap:'))
errors.push(`${name}: advertises a sitemap the build does not have`)
}
const checkManifest = async (
context: Context,
errors: string[],
file: string,
href: string,
): Promise => {
const name = path.relative(context.dist, file)
const { icons, start_url: startUrl } = JSON.parse(
await readFile(file, 'utf8'),
) as { icons?: { src: string }[]; start_url?: string }
// Browsers resolve the URLs of a manifest against the manifest itself, so a
// manifest inside a sub path must use relative URLs instead of a hard coded
// base. Any other URL there breaks the PWA of the mirror.
const url = new URL(href, context.siteUrl)
for (const target of [startUrl, ...(icons ?? []).map((icon) => icon.src)]) {
if (target === undefined) {
errors.push(`${name}: "start_url" is missing`)
continue
}
const resolved = new URL(target, url)
const pathname = `${resolved.pathname}${resolved.search}`
if (!resolved.href.startsWith(context.siteUrl))
errors.push(`${name}: "${target}" resolves to "${resolved.href}"`)
if (!existsSync(toFile(context, pathname)))
errors.push(`${name}: "${target}" misses its file in the build`)
}
}
/**
* Check a docs build for deployment regressions.
*
* The docs are published twice: the production site is served by
* `ecosystem.vuejs.press` at `/`, while the GitHub Pages mirror is served by
* the `vuepress.github.io` origin at `/ecosystem/`. A build is only deployable
* when every site-local URL of the HTML, the sitemap and the web app manifest
* lives under the base of that deployment, when every absolute URL either
* points at the origin serving it or at the canonical production site, and when
* a build that search engines must not index says so.
*
* @param options - The directory, base path, origin and indexing policy of the
* build / 构建产物所在的目录、基础路径、源站与索引策略
* @returns The deployment problems, empty when the build is deployable /
* 部署问题列表,构建可部署时为空
*/
export const checkDeployment = async ({
base,
canonicalHostname,
dist,
hostname,
indexable,
}: DeploymentCheckOptions): Promise => {
if (!existsSync(dist)) return [`"${dist}" is missing, build the docs first`]
const context: Context = {
base,
canonicalHostname,
dist,
basePattern: `${base}${base.slice(1)}`,
indexable,
siteUrl: `${hostname}${base}`,
}
const errors: string[] = []
const files = await walk(dist)
const pages = await Promise.all(
files
.filter((file) => path.relative(dist, file).endsWith('.html'))
.map(async (file) => ({ file, html: await readFile(file, 'utf8') })),
)
const sitemap = files.find(
(file) => path.relative(dist, file) === 'sitemap.xml',
)
const robots = files.find(
(file) => path.relative(dist, file) === 'robots.txt',
)
const manifests = new Set()
for (const { file, html } of pages) {
checkHtml(context, errors, file, html)
for (const [tag] of html.matchAll(LINK_TAG)) {
const { href, rel } = getAttributes(tag)
if (rel === 'manifest' && href) manifests.add(href)
}
}
await Promise.all([
...(sitemap ? [checkSitemap(context, errors, sitemap)] : []),
...(robots ? [checkRobots(context, errors, robots, Boolean(sitemap))] : []),
...[...manifests].map(async (href) =>
checkManifest(context, errors, toFile(context, href), href),
),
])
return errors
}