Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add prerender:route hook #213

Merged
merged 4 commits into from
May 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions src/prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { joinURL, parseURL } from 'ufo'
import chalk from 'chalk'
import { createNitro } from './nitro'
import { build } from './build'
import type { Nitro } from './types'
import type { Nitro, PrerenderRoute } from './types'
import { writeFile } from './utils'

const allowedExtensions = new Set(['', '.json'])
Expand Down Expand Up @@ -41,32 +41,48 @@ export async function prerender (nitro: Nitro) {
}

const generateRoute = async (route: string) => {
const start = Date.now()

// Check if we should render routee
if (!canPrerender(route)) { return }
generatedRoutes.add(route)
routes.delete(route)

// Create result object
const _route: PrerenderRoute = { route }

// Fetch the route
const res = await (localFetch(joinURL(nitro.options.baseURL, route), { headers: { 'X-Nitro-Prerender': route } }) as ReturnType<typeof fetch>)
const contents = await res.text()
_route.contents = await res.text()
if (res.status !== 200) {
throw new Error(`[${res.status}] ${res.statusText}`)
_route.error = new Error(`[${res.status}] ${res.statusText}`) as any
_route.error.statusCode = res.status
_route.error.statusMessage = res.statusText
}

// Write to the file
const isImplicitHTML = !route.endsWith('.html') && (res.headers.get('content-type') || '').includes('html')
const routeWithIndex = route.endsWith('/') ? route + 'index' : route
const fileName = isImplicitHTML ? route + '/index.html' : routeWithIndex
const filePath = join(nitro.options.output.publicDir, fileName)
await writeFile(filePath, contents)
// Crawl Links
_route.fileName = isImplicitHTML ? route + '/index.html' : routeWithIndex
const filePath = join(nitro.options.output.publicDir, _route.fileName)
await writeFile(filePath, _route.contents)

// Crawl route links
if (
!_route.error &&
nitro.options.prerender.crawlLinks &&
isImplicitHTML
) {
const crawledRoutes = extractLinks(contents, route, res)
const crawledRoutes = extractLinks(_route.contents, route, res)
for (const crawledRoute of crawledRoutes) {
if (canPrerender(crawledRoute)) {
routes.add(crawledRoute)
}
}
}

_route.generateTimeMS = Date.now() - start
return _route
}

nitro.logger.info(nitro.options.prerender.crawlLinks
Expand All @@ -75,10 +91,13 @@ export async function prerender (nitro: Nitro) {
)
for (let i = 0; i < 100 && routes.size; i++) {
for (const route of Array.from(routes)) {
const start = Date.now()
const error = await generateRoute(route).catch(err => err)
const end = Date.now()
nitro.logger.log(chalk.gray(` β”œβ”€ ${route} (${end - start}ms) ${error ? `(${error})` : ''}`))
const _route = await generateRoute(route).catch(error => ({ route, error } as PrerenderRoute))

// Skipped (not allowed or duplicate)
if (!_route) { continue }

await nitro.hooks.callHook('prerender:route', _route)
nitro.logger.log(chalk[_route.error ? 'yellow' : 'gray'](` β”œβ”€ ${_route.route} (${_route.generateTimeMS}ms) ${_route.error ? `(${_route.error})` : ''}`))
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/types/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,21 @@ export interface Nitro {
close: () => Promise<void>
}

export interface PrerenderRoute {
route: string
contents?: string
fileName?: string
error?: Error & { statusCode: number, statusMessage: string }
generateTimeMS?: number
}

type HookResult = void | Promise<void>
export interface NitroHooks {
'rollup:before': (nitro: Nitro) => HookResult
'compiled': (nitro: Nitro) => HookResult
'dev:reload': () => HookResult
'close': () => HookResult
'prerender:route': (route: PrerenderRoute) => HookResult
}

export interface StorageMounts {
Expand Down