Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

finalManifest.ts

342 lines9.7 KB

1import {
2 buildManifest,
3 resolveTransformAssetsConfig,
4 transformManifestAssets,
5} from './transformAssetUrls'
6import { getStaticInlineCss, resolveInlineCssForRequest } from './inlineCss'
7import type { ServerManifest } from '@tanstack/router-core'
8import type { HandlerInlineCssOption } from './inlineCss'
9import type {
10 CreateTransformAssetsContext,
11 TransformAssets,
12 TransformAssetsFn,
13} from './transformAssetUrls'
14​
15export type { HandlerInlineCssOption, TransformAssets }
16​
17export interface FinalManifestOptions {
18 /**
19 * Controls whether Start inlines build-collected CSS by default at runtime.
20 *
21 * This only has an effect when the build was created with
22 * `server.build.inlineCss` enabled. Pass a callback to decide per request.
23 * `handler(request, { inlineCss })` overrides this value for that request.
24 *
25 * @default true
26 */
27 inlineCss?: HandlerInlineCssOption
28 /**
29 * Transform manifest-managed asset URLs and attributes at runtime, e.g. to
30 * prepend a CDN prefix.
31 *
32 * This covers JS preloads, manifest script tags, CSS links, and URLs inside
33 * build-collected inline CSS. Asset imports used directly in
34 * components should be handled by the bundler instead.
35 */
36 transformAssets?: TransformAssets
38​
39type FinalManifestCacheKey = 'inline-css' | 'linked-css'
40// An entry holds the pending manifest, then the manifest itself once it
41// resolves, so later requests read it without waiting.
42type FinalManifestCache = Map<
43 FinalManifestCacheKey,
44 ServerManifest | Promise<ServerManifest>
46export type GetBaseManifest = () => Promise<ServerManifest>
47​
48export interface FinalManifestRequestOptions {
49 request: Request
50 requestInlineCss: boolean | undefined
51 getBaseManifest: GetBaseManifest
53​
54interface FinalManifestTransformResolver {
55 cache: boolean
56 warmup: boolean
57 getTransformFn: (
58 ctx: CreateTransformAssetsContext,
59 ) => Promise<TransformAssetsFn | undefined>
60 clearCachedCreateTransform: () => void
62​
63export interface FinalManifestResolver {
64 warmup: (opts: {
65 getBaseManifest: GetBaseManifest
66 }) => Promise<ServerManifest> | undefined
67 resolveCached: (
68 opts: FinalManifestRequestOptions,
69 ) => ServerManifest | Promise<ServerManifest>
70 resolveUncached: (
71 opts: FinalManifestRequestOptions,
72 ) => Promise<ServerManifest>
74​
75export function createCachedBaseManifestLoader(
76 loadBaseManifest: GetBaseManifest,
77): GetBaseManifest {
78 let baseManifestPromise: Promise<ServerManifest> | undefined
79​
80 return () => {
81 if (!baseManifestPromise) {
82 baseManifestPromise = loadBaseManifest().catch((error) => {
83 baseManifestPromise = undefined
84 throw error
85 })
86 }
87​
88 return baseManifestPromise
89 }
91​
92function createFinalManifestTransformResolver(
93 transformAssets: TransformAssets | undefined,
94 opts: { cacheCreateTransform: boolean },
95): FinalManifestTransformResolver {
96 const transformConfig =
97 transformAssets !== undefined
98 ? resolveTransformAssetsConfig(transformAssets)
99 : undefined
100 const cache = transformConfig ? transformConfig.cache : true
101 const warmup =
102 !!transformAssets &&
103 typeof transformAssets === 'object' &&
104 'warmup' in transformAssets &&
105 transformAssets.warmup === true
106​
107 let cachedCreateTransformPromise: Promise<TransformAssetsFn> | undefined
108​
109 const clearCachedCreateTransform = () => {
110 cachedCreateTransformPromise = undefined
111 }
112​
113 return {
114 cache,
115 warmup,
116 clearCachedCreateTransform,
117 getTransformFn: async (ctx) => {
118 if (!transformConfig) return undefined
119​
120 if (transformConfig.type !== 'createTransform') {
121 return transformConfig.transformFn
122 }
123​
124 if (!cache || !opts.cacheCreateTransform) {
125 return transformConfig.createTransform(ctx)
126 }
127​
128 if (!cachedCreateTransformPromise) {
129 cachedCreateTransformPromise = Promise.resolve(
130 transformConfig.createTransform(ctx),
131 ).catch((error) => {
132 clearCachedCreateTransform()
133 throw error
134 })
135 }
136​
137 return cachedCreateTransformPromise
138 },
139 }
141​
142export function createFinalManifestResolver(
143 opts: FinalManifestOptions & { cacheCreateTransform: boolean },
144): FinalManifestResolver {
145 const finalManifestCache: FinalManifestCache = new Map()
146 const transformResolver = createFinalManifestTransformResolver(
147 opts.transformAssets,
148 { cacheCreateTransform: opts.cacheCreateTransform },
149 )
150 const handlerDefaultInlineCss = getStaticInlineCss(undefined, opts.inlineCss)
151​
152 const getRequestManifestOptions = async (
153 requestOpts: FinalManifestRequestOptions,
154 ) => {
155 const transformFn = await transformResolver.getTransformFn({
156 warmup: false,
157 request: requestOpts.request,
158 })
159 const inlineCss = await resolveInlineCssForRequest({
160 request: requestOpts.request,
161 handlerInlineCss: opts.inlineCss,
162 requestInlineCss: requestOpts.requestInlineCss,
163 })
164​
165 return {
166 getBaseManifest: requestOpts.getBaseManifest,
167 transformFn,
168 cache: transformResolver.cache,
169 inlineCss,
170 }
171 }
172​
173 const resolveRequest = async (
174 requestOpts: FinalManifestRequestOptions,
175 cache: FinalManifestCache | undefined,
176 ) => {
177 return resolveFinalManifest({
178 ...(await getRequestManifestOptions(requestOpts)),
179 finalManifestCache: cache,
180 })
181 }
182​
183 return {
184 warmup: ({ getBaseManifest }) =>
185 warmupFinalManifest({
186 enabled: transformResolver.warmup,
187 handlerDefaultInlineCss,
188 cache: transformResolver.cache,
189 finalManifestCache,
190 getBaseManifest,
191 getTransformFn: () =>
192 transformResolver.getTransformFn({ warmup: true }),
193 onError: transformResolver.clearCachedCreateTransform,
194 }),
195 resolveCached: (requestOpts) => {
196 // With a cached transform, the entry for the request's inline-CSS choice
197 // is the manifest resolveRequest would produce, unless a handler
198 // callback still has to make that choice.
199 const inlineCss = getStaticInlineCss(
200 requestOpts.requestInlineCss,
201 opts.inlineCss,
202 )
203 if (transformResolver.cache && inlineCss !== undefined) {
204 const cached = finalManifestCache.get(
205 getFinalManifestCacheKey(inlineCss),
206 )
207 if (cached) {
208 return cached
209 }
210 }
211 return resolveRequest(requestOpts, finalManifestCache)
212 },
213 resolveUncached: (requestOpts) => resolveRequest(requestOpts, undefined),
214 }
216​
217function getFinalManifestCacheKey(inlineCss: boolean): FinalManifestCacheKey {
218 return inlineCss ? 'inline-css' : 'linked-css'
220​
221function cacheFinalManifestPromise(
222 finalManifestCache: FinalManifestCache,
223 cacheKey: FinalManifestCacheKey,
224 promise: Promise<ServerManifest>,
225): Promise<ServerManifest> {
226 const cachedPromise = promise.then(
227 (manifest) => {
228 if (finalManifestCache.get(cacheKey) === cachedPromise) {
229 finalManifestCache.set(cacheKey, manifest)
230 }
231 return manifest
232 },
233 (error) => {
234 if (finalManifestCache.get(cacheKey) === cachedPromise) {
235 finalManifestCache.delete(cacheKey)
236 }
237 throw error
238 },
239 )
240​
241 finalManifestCache.set(cacheKey, cachedPromise)
242 return cachedPromise
244​
245function getOrCreateCachedFinalManifest(
246 finalManifestCache: FinalManifestCache,
247 cacheKey: FinalManifestCacheKey,
248 computeFinalManifest: () => Promise<ServerManifest>,
249): ServerManifest | Promise<ServerManifest> {
250 const cached = finalManifestCache.get(cacheKey)
251 if (cached) {
252 return cached
253 }
254​
255 return cacheFinalManifestPromise(
256 finalManifestCache,
257 cacheKey,
258 Promise.resolve().then(computeFinalManifest),
259 )
261​
262async function buildFinalManifest(opts: {
263 base: ServerManifest
264 transformFn: TransformAssetsFn | undefined
265 inlineCss: boolean
266}): Promise<ServerManifest> {
267 return opts.transformFn
268 ? await transformManifestAssets(opts.base, opts.transformFn, {
269 inlineCss: opts.inlineCss,
270 })
271 : buildManifest(opts.base, { inlineCss: opts.inlineCss })
273​
274async function resolveFinalManifest(opts: {
275 getBaseManifest: () => Promise<ServerManifest>
276 transformFn: TransformAssetsFn | undefined
277 cache: boolean
278 inlineCss: boolean
279 finalManifestCache?: FinalManifestCache
280}): Promise<ServerManifest> {
281 const computeFinalManifest = async () => {
282 return buildFinalManifest({
283 base: await opts.getBaseManifest(),
284 transformFn: opts.transformFn,
285 inlineCss: opts.inlineCss,
286 })
287 }
288​
289 if (opts.finalManifestCache && (!opts.transformFn || opts.cache)) {
290 return getOrCreateCachedFinalManifest(
291 opts.finalManifestCache,
292 getFinalManifestCacheKey(opts.inlineCss),
293 computeFinalManifest,
294 )
295 }
296​
297 return computeFinalManifest()
299​
300function warmupFinalManifest(opts: {
301 enabled: boolean
302 handlerDefaultInlineCss: boolean | undefined
303 cache: boolean
304 finalManifestCache: FinalManifestCache
305 getBaseManifest: () => Promise<ServerManifest>
306 getTransformFn: () => Promise<TransformAssetsFn | undefined>
307 onError?: () => void
308}): Promise<ServerManifest> | undefined {
309 if (
310 !opts.enabled ||
311 opts.handlerDefaultInlineCss === undefined ||
312 !opts.cache
313 ) {
314 return undefined
315 }
316​
317 // Warmup runs when the handler is created, before any request fills the
318 // cache.
319 const inlineCss = opts.handlerDefaultInlineCss
320 const warmupPromise = cacheFinalManifestPromise(
321 opts.finalManifestCache,
322 getFinalManifestCacheKey(inlineCss),
323 Promise.resolve().then(async () => {
324 const [base, transformFn] = await Promise.all([
325 opts.getBaseManifest(),
326 opts.getTransformFn(),
327 ])
328​
329 return buildFinalManifest({
330 base,
331 transformFn,
332 inlineCss,
333 })
334 }),
335 )
336​
337 if (opts.onError) {
338 void warmupPromise.catch(opts.onError)
339 }
340​
341 return warmupPromise