DEV: Ensure service-worker sourcemap logic works with brotli/gzip (#16718)

The logic in 06893380 only works for `.js` files. It breaks down for `.br.js` and `.gz.js` files. This commit makes things more robust by extracting only the base_url from the service-worker JS, and taking the map filename from the original `sourceMappingURL` comment.
This commit is contained in:
David Taylor 2022-05-11 13:42:34 +01:00 committed by GitHub
parent 67b23c0e22
commit 9a5acc5cbc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 5 deletions

View File

@ -204,9 +204,11 @@ class StaticController < ApplicationController
response.headers["Last-Modified"] = File.ctime(path).httpdate response.headers["Last-Modified"] = File.ctime(path).httpdate
end end
content = Rails.application.assets_manifest.find_sources('service-worker.js').first content = Rails.application.assets_manifest.find_sources('service-worker.js').first
base_url = File.dirname(helpers.script_asset_path('service-worker'))
content = content.sub( content = content.sub(
/^\/\/# sourceMappingURL=(service-worker-.+\.map)$/ /^\/\/# sourceMappingURL=(service-worker-.+\.map)$/
) { "//# sourceMappingURL=#{helpers.script_asset_path('service-worker')}.map" } ) { "//# sourceMappingURL=#{base_url}/#{Regexp.last_match(1)}" }
render( render(
plain: content, plain: content,
content_type: 'application/javascript' content_type: 'application/javascript'

View File

@ -417,10 +417,22 @@ describe StaticController do
JS JS
]) ])
get "/service-worker.js" {
expect(response.status).to eq(200) '/assets/service-worker.js' => '/assets/service-worker-abcde.js.map',
expect(response.content_type).to start_with("application/javascript") '/assets/service-worker.js.br' => '/assets/service-worker-abcde.js.map',
expect(response.body).to include("sourceMappingURL=/assets/service-worker.js.map\n") '/assets/service-worker.br.js' => '/assets/service-worker-abcde.js.map',
'/assets/service-worker.js.gz' => '/assets/service-worker-abcde.js.map',
'/assets/service-worker.gz.js' => '/assets/service-worker-abcde.js.map',
'https://example.com/assets/service-worker.js' => 'https://example.com/assets/service-worker-abcde.js.map',
'https://example.com/subfolder/assets/service-worker.js' => 'https://example.com/subfolder/assets/service-worker-abcde.js.map',
}.each do |asset_path, expected_map_url|
ActionController::Base.helpers.stubs(:asset_path).with("service-worker.js").returns(asset_path)
get "/service-worker.js"
expect(response.status).to eq(200)
expect(response.content_type).to start_with("application/javascript")
expect(response.body).to include("sourceMappingURL=#{expected_map_url}\n")
end
end end
end end
end end