Use the default Flutter service worker instead of our custom service worker (#5331)

diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md
index c6ba6a4..826f37a 100644
--- a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md
+++ b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md
@@ -6,7 +6,7 @@
 Dart & Flutter DevTools - A Suite of Performance Tools for Dart and Flutter
 
 ## General updates
-TODO: Remove this section if there are not any general updates.
+* Use the default Flutter service worker - [#5331](https://github.com/flutter/devtools/pull/5331)
 
 ## Inspector updates
 TODO: Remove this section if there are not any general updates.
diff --git a/packages/devtools_app/web/devtools_service_worker.js b/packages/devtools_app/web/devtools_service_worker.js
deleted file mode 100644
index 59f3164..0000000
--- a/packages/devtools_app/web/devtools_service_worker.js
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2021 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This service worker is not run in local development mode. As part of the 
-// release logic, it is moved to the build directory and renamed to 
-// service_worker.js. The renamed service worker is the one that is loaded
-// in index.html.
-
-'use strict';
-
-const CACHE_PREFIX = `dart-devtools-app-cache-`;
-
-const RESOURCES_TO_CACHE = [
-    '/main.dart.js',
-    '/assets/',
-];
-
-self.addEventListener('install', (event) => {
-    // Skip waiting to immediately stop any previously active service workers:
-    self.skipWaiting();
-    const resetCache = caches.keys()
-        .then((cacheKeys) => {
-            // Delete any older caches during installation of the new service worker:
-            return Promise.all(cacheKeys.map((key) => caches.delete(key)));
-        })
-        .then(() => caches.open(getCacheName(self.location)));
-    event.waitUntil(resetCache);
-});
-
-// The fetch handler redirects requests for RESOURCES_TO_CACHE to the service
-// worker cache.
-self.addEventListener('fetch', (event) => {
-    if (event.request.method !== 'GET' ||
-        isExternalRequest(event.request.url, self.location.origin) ||
-        !shouldCache(event.request.url)) {
-        // Signal that we don't want to cache the request and the browser should take over.
-        return;
-    }
-
-    event.respondWith(caches.open(getCacheName(self.location)).then((cache) => {
-        return cache.match(event.request).then((response) => {
-            // Either respond with the cached resource, or perform a fetch and
-            // lazily populate the cache.
-            return response || fetch(event.request).then((response) => {
-                cache.put(event.request, response.clone());
-                return response;
-            });
-        });
-    }));
-});
-
-function getCacheName(location) {
-    const version = location.search.replace('?v=', '');
-    return CACHE_PREFIX + version;
-}
-
-function isExternalRequest(requestUrl, originUrl) {
-    return !requestUrl.includes(originUrl);
-}
-
-function shouldCache(requestUrl) {
-    return RESOURCES_TO_CACHE.some((resourcePath) => requestUrl.includes(resourcePath));
-}
diff --git a/packages/devtools_app/web/index.html b/packages/devtools_app/web/index.html
index 249b0dd..f341dca 100644
--- a/packages/devtools_app/web/index.html
+++ b/packages/devtools_app/web/index.html
@@ -45,88 +45,79 @@
       window.location.href = '/unsupported-browser.html';
     }
   </script>
+
+  <script>
+    // The value below is injected by flutter build, do not touch.
+    var serviceWorkerVersion = null;
+  </script>
+  <!-- This script adds the flutter initialization JS code -->
+  <script src="flutter.js" defer></script> 
+
 </head>
 
 <body>
-  <!-- This script installs service_worker.js to provide PWA functionality to
-       application. For more information, see:
-       https://developers.google.com/web/fundamentals/primers/service-workers -->
+
   <script>
-    var version = '2.22.2';
-    var scriptLoaded = false;
-    function loadMainDartJs() {
-      if (scriptLoaded) {
-        return;
+    // Unregister the old custom DevTools service worker (if it exists). It was
+    // removed in: https://github.com/flutter/devtools/pull/5331
+    function unregisterDevToolsServiceWorker() {
+      if ('serviceWorker' in navigator) {
+        const DEVTOOLS_SW = 'service_worker.js';
+        const FLUTTER_SW = 'flutter_service_worker.js';
+        navigator.serviceWorker.getRegistrations().then(function(registrations) {
+            for (let registration of registrations) {
+                const activeWorker = registration.active;
+                if (activeWorker != null) {
+                    const url = activeWorker.scriptURL;
+                    if (url.includes(DEVTOOLS_SW) && !url.includes(FLUTTER_SW)) {
+                        registration.unregister();
+                    }
+                }
+            }
+        });
       }
-      scriptLoaded = true;
-      var scriptTag = document.createElement('script');
-      scriptTag.src = 'main.dart.js';
-      scriptTag.type = 'application/javascript';
-      document.body.append(scriptTag);
     }
 
-    if ('serviceWorker' in navigator) {
-      if (window.location.href.includes('index.ddc.html')) {
-        // If we are running DevTools locally, immediately load `main.dart.js` and
-        // unregister any service workers:
-        loadMainDartJs();
-        navigator.serviceWorker.getRegistrations().then(function (registrations) {
-          for (let registration of registrations) {
-            registration.unregister();
+    // Bootstrap app for 3P environments:
+    function bootstrapAppFor3P() {
+      window.addEventListener('load', function(ev) {
+        // Download main.dart.js
+        _flutter.loader.loadEntrypoint({
+          serviceWorker: {
+            serviceWorkerVersion: serviceWorkerVersion,
+          },
+          onEntrypointLoaded: function(engineInitializer) {
+            engineInitializer.initializeEngine({
+              renderer: 'canvaskit',
+              canvasKitBaseUrl: 'canvaskit/'
+            })
+            .then(function(appRunner) {
+              appRunner.runApp();
+            });
           }
         });
-      } else {
-        // Service workers are supported. Use them.
-        window.addEventListener('load', function () {
-          // Wait for registration to finish before dropping the <script> tag.
-          // Otherwise, the browser will load the script multiple times,
-          // potentially different versions.
-          var serviceWorkerUrl = 'service_worker.js?v=' + version;
-          navigator.serviceWorker.register(serviceWorkerUrl)
-            .then((reg) => {
-              function waitForActivation(serviceWorker) {
-                serviceWorker.addEventListener('statechange', () => {
-                  if (serviceWorker.state == 'activated') {
-                    loadMainDartJs();
-                  }
-                });
-              }
-              if (!reg.active && (reg.installing || reg.waiting)) {
-                // No active web worker and we have installed or are installing
-                // one for the first time. Simply wait for it to activate.
-                waitForActivation(reg.installing || reg.waiting);
-              } else if (!reg.active.scriptURL.endsWith(version)) {
-                // When the app updates the version changes, so we
-                // need to ask the service worker to update.
-                reg.update();
-                waitForActivation(reg.installing);
-              } else {
-                // Existing service worker is still good.
-                loadMainDartJs();
-              }
-            })
-            .catch((err) => {
-              console.warn(
-                ` Falling back to plain <script> tag. Error loading service worker: ${err}`);
-              loadMainDartJs();
-            });
-
-          // If service worker doesn't succeed in a reasonable amount of time,
-          // fallback to plain <script> tag.
-          setTimeout(() => {
-            if (!scriptLoaded) {
-              console.warn(
-                'Failed to load app from service worker. Falling back to plain <script> tag.',
-              );
-              loadMainDartJs();
-            }
-          }, 4000);
-        });
-      }
-    } else {
-      // Service workers not supported. Just drop the <script> tag.
-      loadMainDartJs();
+      });
     }
+
+    // Bootstrap app for 1P environments:
+    function bootstrapAppFor1P() {
+      window.addEventListener('load', function(ev) {
+        // Download main.dart.js
+        _flutter.loader.loadEntrypoint({
+          onEntrypointLoaded: function(engineInitializer) {
+            engineInitializer.initializeEngine({
+              renderer: 'canvaskit',
+            })
+            .then(function(appRunner) {
+              appRunner.runApp();
+            });
+          }
+        });
+      });
+    }
+
+    unregisterDevToolsServiceWorker();
+    bootstrapAppFor3P();
   </script>
 </body>
 
diff --git a/tool/build_release.sh b/tool/build_release.sh
index 3fd3585..f599cc3 100755
--- a/tool/build_release.sh
+++ b/tool/build_release.sh
@@ -52,22 +52,12 @@
 # as code size doesn't matter very much for us as minification makes some
 # crashes harder to debug. For example, https://github.com/flutter/devtools/issues/2125
 
-# TODO(https://github.com/flutter/devtools/issues/5148): remove the FLUTTER_WEB_CANVASKIT_URL
-# flag and set `canvasKitBaseUrl` in `initializeEngine` instead.
-# See https://docs.flutter.dev/development/platform-integration/web/initialization.
-
 flutter build web \
   --web-renderer canvaskit \
-  --pwa-strategy=none \
+  --pwa-strategy=offline-first \
   --release \
-  --dart-define=FLUTTER_WEB_CANVASKIT_URL=canvaskit/ \
   --no-tree-shake-icons
 
-# Delete the Flutter-generated service worker:
-rm build/web/flutter_service_worker.js
-# Rename the DevTools-specific service worker:
-mv build/web/devtools_service_worker.js build/web/service_worker.js
-
 # Ensure permissions are set correctly on canvaskit binaries.
 chmod 0755 build/web/canvaskit/canvaskit.*
 
diff --git a/tool/update_version.dart b/tool/update_version.dart
index 8b0d14e..e910e8e 100644
--- a/tool/update_version.dart
+++ b/tool/update_version.dart
@@ -56,10 +56,6 @@
     writeVersionToChangelog(File('CHANGELOG.md'), newVersion);
   }
 
-  print('Updating index.html to version $newVersion...');
-  writeVersionToIndexHtml(
-      File('packages/devtools_app/web/index.html'), currentVersion, newVersion);
-
   final process = await Process.start('./tool/pub_upgrade.sh', []);
   process.stdout.asBroadcastStream().listen((event) {
     print(utf8.decode(event));
@@ -209,32 +205,6 @@
   ].joinWithNewLine());
 }
 
-void writeVersionToIndexHtml(
-  File indexHtml,
-  String oldVersion,
-  String newVersion,
-) {
-  var updatedVersion = false;
-  final lines = indexHtml.readAsLinesSync();
-  final revisedLines = <String>[];
-  for (final line in lines) {
-    if (line.contains(oldVersion)) {
-      final versionStart = line.indexOf(oldVersion);
-      final lineSegmentBefore = line.substring(0, versionStart);
-      final lineSegmentAfter = line.substring(versionStart + oldVersion.length);
-      final newLine = '$lineSegmentBefore$newVersion$lineSegmentAfter';
-      revisedLines.add(newLine);
-      updatedVersion = true;
-    } else {
-      revisedLines.add(line);
-    }
-  }
-  if (!updatedVersion) {
-    throw Exception('Unable to update version in index.html');
-  }
-  indexHtml.writeAsStringSync(revisedLines.joinWithNewLine());
-}
-
 String incrementDevVersion(String currentVersion) {
   final alreadyHasDevVersion = isDevVersion(currentVersion);
   if (alreadyHasDevVersion) {