11import { applyExperiment , getExperiment } from './lib/experiments.js' ;
2+ import {
3+ addPriorityHints ,
4+ getPriorityHintKey ,
5+ logPriorityHint ,
6+ } from './lib/performance.js' ;
27import { getRedirectPath } from './lib/redirects.js' ;
38import { matchesRoute } from './lib/router.js' ;
49
@@ -17,6 +22,18 @@ function getXIDFromCookie(cookie) {
1722 return cookie . match ( / (?: ^ | ; ) * x i d = ( \. \d + ) * (?: ; | $ ) / ) && RegExp . $1 ;
1823}
1924
25+ /**
26+ * Removes a trailing `index.content.html` from a URL path.
27+ * @param {string } path
28+ * @returns {string }
29+ */
30+ function normalizePath ( path ) {
31+ if ( path . endsWith ( 'index.content.html' ) ) {
32+ return path . slice ( 0 , - 18 ) ;
33+ }
34+ return path ;
35+ }
36+
2037/**
2138 * @param {Request } request
2239 * @param {Response } response
@@ -71,23 +88,31 @@ async function handleRequest({request, url, startTime, vars}) {
7188
7289 const experiment = getExperiment ( xid ) ;
7390
74- const response = await fetch ( url . href , {
75- body : request . body ,
76- headers : request . headers ,
77- method : request . method ,
78- redirect : request . redirect ,
79- cf : {
80- cacheEverything : vars . ENV === 'production' ,
81- cacheTtlByStatus : { '200-299' : 604800 , '400-599' : 0 } ,
82- } ,
83- } ) ;
91+ const [ response , priorityHintsSelector ] = await Promise . all ( [
92+ fetch ( url . href , {
93+ body : request . body ,
94+ headers : request . headers ,
95+ method : request . method ,
96+ redirect : request . redirect ,
97+ cf : {
98+ cacheEverything : vars . ENV === 'production' ,
99+ cacheTtlByStatus : { '200-299' : 604800 , '400-599' : 0 } ,
100+ } ,
101+ } ) ,
102+ vars . PRIORITY_HINTS . get (
103+ getPriorityHintKey ( request , normalizePath ( url . pathname ) )
104+ ) ,
105+ ] ) ;
84106
85107 const clone = new Response ( response . body , response ) ;
86108
87109 setXIDToCookie ( xid , clone ) ;
88110 addServerTimingHeaders ( clone , startTime ) ;
89111
90112 const rewriter = new HTMLRewriter ( ) ;
113+ if ( priorityHintsSelector ) {
114+ addPriorityHints ( rewriter , priorityHintsSelector ) ;
115+ }
91116 if ( experiment ) {
92117 applyExperiment ( experiment , rewriter ) ;
93118 }
@@ -104,6 +129,10 @@ export default {
104129 const startTime = Date . now ( ) ;
105130 const url = new URL ( request . url ) ;
106131
132+ if ( url . pathname === '/hint' && request . method === 'POST' ) {
133+ return logPriorityHint ( request , vars . PRIORITY_HINTS ) ;
134+ }
135+
107136 // Return early if no route matches.
108137 // Note: this should never happen in production.
109138 if ( ! matchesRoute ( { request, url} ) ) {
0 commit comments