From 9a5acc5cbcb3fb0b62d9a60c79376458233b4e4a Mon Sep 17 00:00:00 2001 From: David Taylor Date: Wed, 11 May 2022 13:42:34 +0100 Subject: [PATCH] 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. --- app/controllers/static_controller.rb | 4 +++- spec/requests/static_controller_spec.rb | 20 ++++++++++++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/app/controllers/static_controller.rb b/app/controllers/static_controller.rb index c1e18eed909..b93bde227d3 100644 --- a/app/controllers/static_controller.rb +++ b/app/controllers/static_controller.rb @@ -204,9 +204,11 @@ class StaticController < ApplicationController response.headers["Last-Modified"] = File.ctime(path).httpdate end content = Rails.application.assets_manifest.find_sources('service-worker.js').first + + base_url = File.dirname(helpers.script_asset_path('service-worker')) content = content.sub( /^\/\/# sourceMappingURL=(service-worker-.+\.map)$/ - ) { "//# sourceMappingURL=#{helpers.script_asset_path('service-worker')}.map" } + ) { "//# sourceMappingURL=#{base_url}/#{Regexp.last_match(1)}" } render( plain: content, content_type: 'application/javascript' diff --git a/spec/requests/static_controller_spec.rb b/spec/requests/static_controller_spec.rb index cbebd9f35fa..e03357f1e8e 100644 --- a/spec/requests/static_controller_spec.rb +++ b/spec/requests/static_controller_spec.rb @@ -417,10 +417,22 @@ describe StaticController do JS ]) - 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=/assets/service-worker.js.map\n") + { + '/assets/service-worker.js' => '/assets/service-worker-abcde.js.map', + '/assets/service-worker.js.br' => '/assets/service-worker-abcde.js.map', + '/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