Skip to content

Commit

Permalink
$mol_offline: fixed cors
Browse files Browse the repository at this point in the history
  • Loading branch information
jin committed Jan 3, 2025
1 parent 5a2c887 commit 6979257
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions offline/offline.web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ namespace $ {
self.addEventListener( 'fetch' , ( event : any )=> {

const request = event.request as Request
// console.log( 'FETCH', request.mode, request.cache, request.url )

if( blacklist.has( request.url.replace( /^https?:/, '' ) ) ) {
return event.respondWith(
Expand All @@ -47,20 +48,9 @@ namespace $ {
if( /\?/.test( request.url ) ) return
if( request.cache === 'no-store' ) return

const fetch_data = () => fetch( request ).then( response => {
const fetch_data = () => fetch( new Request( request, { credentials: 'omit' } ) ).then( response => {
if (response.status !== 200) return response

const headers = new Headers( response.headers )
headers.set( "Cross-Origin-Embedder-Policy", "require-corp" )
headers.set( "Cross-Origin-Opener-Policy", "same-origin" )
headers.set( "$mol_offline", "" )

response = new Response( response.body, {
status: response.status,
statusText: response.statusText,
headers,
});

event.waitUntil(
caches.open( '$mol_offline' ).then(
cache => cache.put( request , response )
Expand All @@ -70,9 +60,28 @@ namespace $ {
return response.clone()
} )

const enrich = ( response: Response )=> {

// console.log( 'ENRICH', response.status, response.url )
if( !response.status ) return response

const headers = new Headers( response.headers )
headers.set( "$mol_offline", "" )
headers.set( "Cross-Origin-Embedder-Policy", "credentialless" )
headers.set( "Cross-Origin-Resource-Policy", "cross-origin" )
headers.set( "Cross-Origin-Opener-Policy", "same-origin" )

return new Response( response.body, {
status: response.status,
statusText: response.statusText,
headers,
});

}

const fresh = request.cache === 'force-cache' ? null : fetch_data()

if (fresh) event.waitUntil( fresh )
if (fresh) event.waitUntil( fresh.then( enrich ) )

event.respondWith(
caches.match( request ).then(
Expand All @@ -92,10 +101,10 @@ namespace $ {
cloned.headers.set( '$mol_offline_remote_status', message )
return cloned
})
: fresh
: fresh!
)
: ( cached || fresh || fetch_data() )
)
).then( enrich )
)

})
Expand Down

0 comments on commit 6979257

Please sign in to comment.