@@ -85,6 +85,30 @@ const injectAssets = (metafile) => {
85
85
console . log ( `Injected ${ path . basename ( scriptFile ) } and ${ path . basename ( cssFile ) } into index.html.` )
86
86
}
87
87
88
+ /**
89
+ * Inject the ipfs-sw-first-hit.js into the ipfs-sw-first-hit.html file
90
+ *
91
+ * This was added when addressing an issue with redirects not preserving query parameters.
92
+ *
93
+ * The solution we're moving forward with is, instead of using 302 redirects with ipfs _redirects file, we are
94
+ * using 200 responses with the ipfs-sw-first-hit.html file. That file will include the ipfs-sw-first-hit.js script
95
+ * which will be injected into the index.html file, and handle the redirect logic for us.
96
+ *
97
+ * @see https://github.com/ipfs/service-worker-gateway/issues/628
98
+ *
99
+ * @param {esbuild.Metafile } metafile
100
+ */
101
+ const injectFirstHitJs = ( metafile ) => {
102
+ const htmlFilePath = path . resolve ( 'dist/ipfs-sw-first-hit.html' )
103
+
104
+ const scriptFile = Object . keys ( metafile . outputs ) . find ( file => file . endsWith ( '.js' ) && file . includes ( 'ipfs-sw-first-hit' ) )
105
+ const scriptTag = `<script src="/${ path . basename ( scriptFile ) } "></script>`
106
+ let htmlContent = fs . readFileSync ( htmlFilePath , 'utf8' )
107
+ htmlContent = htmlContent . replace ( / < % = G I T _ V E R S I O N % > / g, gitRevision ( ) )
108
+ htmlContent = htmlContent . replace ( '</body>' , `${ scriptTag } </body>` )
109
+ fs . writeFileSync ( htmlFilePath , htmlContent )
110
+ }
111
+
88
112
/**
89
113
* We need the service worker to have a consistent name
90
114
*
@@ -126,6 +150,7 @@ const modifyBuiltFiles = {
126
150
build . onEnd ( async ( result ) => {
127
151
copyPublicFiles ( )
128
152
injectAssets ( result . metafile )
153
+ injectFirstHitJs ( result . metafile )
129
154
} )
130
155
}
131
156
}
@@ -149,7 +174,7 @@ const excludeFilesPlugin = (extensions) => ({
149
174
* @type {esbuild.BuildOptions }
150
175
*/
151
176
export const buildOptions = {
152
- entryPoints : [ 'src/index.tsx' , 'src/sw.ts' ] ,
177
+ entryPoints : [ 'src/index.tsx' , 'src/sw.ts' , 'src/ipfs-sw-first-hit.ts' ] ,
153
178
bundle : true ,
154
179
outdir : 'dist' ,
155
180
loader : {
0 commit comments