|
| 1 | +import { getDeployStore } from '@netlify/blobs' |
| 2 | +import { NetlifyPluginConstants } from '@netlify/build' |
| 3 | +import { globby } from 'globby' |
| 4 | +import { readFile } from 'node:fs/promises' |
| 5 | +import { cpus } from 'os' |
| 6 | +import pLimit from 'p-limit' |
| 7 | +import { parse, ParsedPath } from 'path' |
| 8 | +import { BUILD_DIR } from '../constants.js' |
| 9 | + |
| 10 | +type CacheEntry = { |
| 11 | + key: string |
| 12 | + value: { |
| 13 | + lastModified: number |
| 14 | + value: PageCacheValue | RouteCacheValue | FetchCacheValue |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +type PageCacheValue = { |
| 19 | + kind: 'PAGE' |
| 20 | + html: string |
| 21 | + pageData: string |
| 22 | + headers?: { [k: string]: string } |
| 23 | + status?: number |
| 24 | +} |
| 25 | + |
| 26 | +type RouteCacheValue = { |
| 27 | + kind: 'ROUTE' |
| 28 | + body: string |
| 29 | + headers?: { [k: string]: string } |
| 30 | + status?: number |
| 31 | +} |
| 32 | + |
| 33 | +type FetchCacheValue = { |
| 34 | + kind: 'FETCH' |
| 35 | + data: { |
| 36 | + headers: { [k: string]: string } |
| 37 | + body: string |
| 38 | + url: string |
| 39 | + status?: number |
| 40 | + tags?: string[] |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// static prerendered pages content with JSON data |
| 45 | +const isPage = ({ dir, name, ext }: ParsedPath, paths: string[]) => { |
| 46 | + return dir.startsWith('server/pages') && ext === '.html' && paths.includes(`${dir}/${name}.json`) |
| 47 | +} |
| 48 | +// static prerendered app content with RSC data |
| 49 | +const isApp = ({ dir, ext }: ParsedPath) => { |
| 50 | + return dir.startsWith('server/app') && ext === '.html' |
| 51 | +} |
| 52 | +// static prerendered app route handler |
| 53 | +const isRoute = ({ dir, ext }: ParsedPath) => { |
| 54 | + return dir.startsWith('server/app') && ext === '.body' |
| 55 | +} |
| 56 | +// fetch cache data |
| 57 | +const isFetch = ({ dir }: ParsedPath) => { |
| 58 | + return dir.startsWith('cache/fetch-cache') |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Transform content file paths into cache entries for the blob store |
| 63 | + */ |
| 64 | +const buildPrerenderedContentEntries = async (cwd: string): Promise<Promise<CacheEntry>[]> => { |
| 65 | + const paths = await globby( |
| 66 | + [`cache/fetch-cache/*`, `server/+(app|pages)/**/*.+(html|body|json)`], |
| 67 | + { |
| 68 | + cwd, |
| 69 | + extglob: true, |
| 70 | + }, |
| 71 | + ) |
| 72 | + |
| 73 | + return paths |
| 74 | + .map(parse) |
| 75 | + .filter((path: ParsedPath) => { |
| 76 | + return isPage(path, paths) || isApp(path) || isRoute(path) || isFetch(path) |
| 77 | + }) |
| 78 | + .map(async (path: ParsedPath): Promise<CacheEntry> => { |
| 79 | + const { dir, name, ext } = path |
| 80 | + const key = `${dir}/${name}` |
| 81 | + let value |
| 82 | + |
| 83 | + if (isPage(path, paths)) { |
| 84 | + value = { |
| 85 | + kind: 'PAGE', |
| 86 | + html: await readFile(`${cwd}/${key}.html`, 'utf-8'), |
| 87 | + pageData: JSON.parse(await readFile(`${cwd}/${key}.json`, 'utf-8')), |
| 88 | + } satisfies PageCacheValue |
| 89 | + } |
| 90 | + |
| 91 | + if (isApp(path)) { |
| 92 | + value = { |
| 93 | + kind: 'PAGE', |
| 94 | + html: await readFile(`${cwd}/${key}.html`, 'utf-8'), |
| 95 | + pageData: await readFile(`${cwd}/${key}.rsc`, 'utf-8'), |
| 96 | + ...JSON.parse(await readFile(`${cwd}/${key}.meta`, 'utf-8')), |
| 97 | + } satisfies PageCacheValue |
| 98 | + } |
| 99 | + |
| 100 | + if (isRoute(path)) { |
| 101 | + value = { |
| 102 | + kind: 'ROUTE', |
| 103 | + body: await readFile(`${cwd}/${key}.body`, 'utf-8'), |
| 104 | + ...JSON.parse(await readFile(`${cwd}/${key}.meta`, 'utf-8')), |
| 105 | + } satisfies RouteCacheValue |
| 106 | + } |
| 107 | + |
| 108 | + if (isFetch(path)) { |
| 109 | + value = { |
| 110 | + kind: 'FETCH', |
| 111 | + data: JSON.parse(await readFile(`${cwd}/${key}`, 'utf-8')), |
| 112 | + } satisfies FetchCacheValue |
| 113 | + } |
| 114 | + |
| 115 | + return { |
| 116 | + key, |
| 117 | + value: { |
| 118 | + lastModified: Date.now(), |
| 119 | + value, |
| 120 | + }, |
| 121 | + } |
| 122 | + }) |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * Upload prerendered content to the blob store and remove it from the bundle |
| 127 | + */ |
| 128 | +export const uploadPrerenderedContent = async ({ |
| 129 | + NETLIFY_API_TOKEN, |
| 130 | + NETLIFY_API_HOST, |
| 131 | + SITE_ID, |
| 132 | +}: NetlifyPluginConstants) => { |
| 133 | + // initialize the blob store |
| 134 | + const blob = getDeployStore({ |
| 135 | + deployID: process.env.DEPLOY_ID, |
| 136 | + siteID: SITE_ID, |
| 137 | + token: NETLIFY_API_TOKEN, |
| 138 | + apiURL: `https://${NETLIFY_API_HOST}`, |
| 139 | + }) |
| 140 | + // limit concurrent uploads to 2x the number of CPUs |
| 141 | + const limit = pLimit(Math.max(2, cpus().length)) |
| 142 | + |
| 143 | + // read prerendered content and build JSON key/values for the blob store |
| 144 | + const entries = await Promise.allSettled( |
| 145 | + await buildPrerenderedContentEntries(`${BUILD_DIR}/.next/standalone/.next`), |
| 146 | + ) |
| 147 | + entries.forEach((result) => { |
| 148 | + if (result.status === 'rejected') { |
| 149 | + console.error(`Unable to read prerendered content: ${result.reason.message}`) |
| 150 | + } |
| 151 | + }) |
| 152 | + |
| 153 | + // upload JSON content data to the blob store |
| 154 | + const uploads = await Promise.allSettled( |
| 155 | + entries |
| 156 | + .filter((entry) => entry.status === 'fulfilled') |
| 157 | + .map((entry: PromiseSettledResult<CacheEntry>) => { |
| 158 | + const result = entry as PromiseFulfilledResult<CacheEntry> |
| 159 | + const { key, value } = result.value |
| 160 | + return limit(() => blob.setJSON(key, value)) |
| 161 | + }), |
| 162 | + ) |
| 163 | + uploads.forEach((upload, index) => { |
| 164 | + if (upload.status === 'rejected') { |
| 165 | + const result = entries[index] as PromiseFulfilledResult<CacheEntry> |
| 166 | + console.error(`Unable to store ${result.value.key}: ${upload.reason.message}`) |
| 167 | + } |
| 168 | + }) |
| 169 | +} |
0 commit comments