diff --git a/packages/flutter_tools/lib/src/isolated/devfs_web.dart b/packages/flutter_tools/lib/src/isolated/devfs_web.dart index 0ba4d51530..c3d06240b1 100644 --- a/packages/flutter_tools/lib/src/isolated/devfs_web.dart +++ b/packages/flutter_tools/lib/src/isolated/devfs_web.dart @@ -146,9 +146,19 @@ class WebAssetServer implements AssetReader { final Map _modules; final Map _digests; + // The generation number that maps to the number of hot restarts. This is used + // to suffix a query to source paths in order to cache-bust. + int _hotRestartGeneration = 0; + int get selectedPort => _httpServer.port; - void performRestart(List modules) { + /// Given a list of [modules] that need to be loaded, compute module names and + /// digests. + /// + /// If [writeRestartScripts] is true, writes a list of sources mapped to their + /// ids to the file system that can then be consumed by the hot restart + /// callback. + void performRestart(List modules, {required bool writeRestartScripts}) { for (final String module in modules) { // We skip computing the digest by using the hashCode of the underlying buffer. // Whenever a file is updated, the corresponding Uint8List.view it corresponds @@ -159,6 +169,14 @@ class WebAssetServer implements AssetReader { _modules[name] = path; _digests[name] = _webMemoryFS.files[moduleName].hashCode.toString(); } + if (writeRestartScripts && _hotRestartGeneration > 0) { + final List> srcIdsList = >[]; + for (final String src in modules) { + srcIdsList.add({'src': '$src?gen=$_hotRestartGeneration', 'id': src}); + } + writeFile('main.dart.js.restartScripts', json.encode(srcIdsList)); + } + _hotRestartGeneration++; } @visibleForTesting @@ -241,8 +259,8 @@ class WebAssetServer implements AssetReader { } final PackageConfig packageConfig = buildInfo.packageConfig; - final Map digests = {}; final Map modules = {}; + final Map digests = {}; final WebAssetServer server = WebAssetServer( httpServer, packageConfig, @@ -784,6 +802,7 @@ class WebDevFS implements DevFS { required this.isWasm, required this.useLocalCanvasKit, required this.rootDirectory, + required this.isWindows, this.testMode = false, }) : _port = port { // TODO(srujzs): Remove this assertion when the library bundle format is @@ -818,6 +837,7 @@ class WebDevFS implements DevFS { final WebRendererMode webRenderer; final bool isWasm; final bool useLocalCanvasKit; + final bool isWindows; late WebAssetServer webAssetServer; @@ -1014,6 +1034,7 @@ class WebDevFS implements DevFS { ddcModuleLoaderUrl: 'ddc_module_loader.js', mapperUrl: 'stack_trace_mapper.js', generateLoadingIndicator: enableDwds, + isWindows: isWindows, ) : generateBootstrapScript( requireUrl: 'require.js', @@ -1101,7 +1122,8 @@ class WebDevFS implements DevFS { } on FileSystemException catch (err) { throwToolExit('Failed to load recompiled sources:\n$err'); } - webAssetServer.performRestart(modules); + + webAssetServer.performRestart(modules, writeRestartScripts: ddcModuleSystem); return UpdateFSReport( success: true, syncedBytes: codeFile.lengthSync(), diff --git a/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart b/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart index 6d8371531b..4bfc34190a 100644 --- a/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart +++ b/packages/flutter_tools/lib/src/isolated/resident_web_runner.dart @@ -319,6 +319,7 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive). isWasm: debuggingOptions.webUseWasm, useLocalCanvasKit: debuggingOptions.buildInfo.useLocalCanvasKit, rootDirectory: fileSystem.directory(projectRootPath), + isWindows: globals.platform.isWindows, ); Uri url = await device!.devFS!.create(); if (debuggingOptions.tlsCertKeyPath != null && debuggingOptions.tlsCertPath != null) { diff --git a/packages/flutter_tools/lib/src/web/bootstrap.dart b/packages/flutter_tools/lib/src/web/bootstrap.dart index 4de9cf9031..63e43fcd1c 100644 --- a/packages/flutter_tools/lib/src/web/bootstrap.dart +++ b/packages/flutter_tools/lib/src/web/bootstrap.dart @@ -145,23 +145,24 @@ String generateDDCLibraryBundleBootstrapScript({ required String ddcModuleLoaderUrl, required String mapperUrl, required bool generateLoadingIndicator, - String appRootDirectory = '/', + required bool isWindows, }) { return ''' ${generateLoadingIndicator ? _generateLoadingIndicator() : ""} -// TODO(markzipan): This is safe if Flutter app roots are always equal to the -// host root '/'. Validate if this is true. -var _currentDirectory = "$appRootDirectory"; +// Save the current directory so we can access it in a closure. +var _currentDirectory = (function () { + var _url = document.currentScript.src; + var lastSlash = _url.lastIndexOf('/'); + if (lastSlash == -1) return _url; + var currentDirectory = _url.substring(0, lastSlash + 1); + return currentDirectory; +})(); $_simpleLoaderScript -// A map containing the URLs for the bootstrap scripts in debug. -let _scriptUrls = { - "mapper": "$mapperUrl", - "moduleLoader": "$ddcModuleLoaderUrl" -}; - (function() { + let appName = "org-dartlang-app:/$entrypoint"; + // Load pre-requisite DDC scripts. We intentionally use invalid names to avoid // namespace clashes. let prerequisiteScripts = [ @@ -182,6 +183,17 @@ let _scriptUrls = { } Promise.all(prerequisiteLoads).then((_) => afterPrerequisiteLogic()); + // Save the current script so we can access it in a closure. + var _currentScript = document.currentScript; + + // Create a policy if needed to load the files during a hot restart. + let policy = { + createScriptURL: function(src) {return src;} + }; + if (self.trustedTypes && self.trustedTypes.createPolicy) { + policy = self.trustedTypes.createPolicy('dartDdcModuleUrl', policy); + } + var afterPrerequisiteLogic = function() { window.\$dartLoader.rootDirectories.push(_currentDirectory); let scripts = [ @@ -196,6 +208,8 @@ let _scriptUrls = { ]; let loadConfig = new window.\$dartLoader.LoadConfiguration(); + // TODO(srujzs): Verify this is sufficient for Windows. + loadConfig.isWindows = $isWindows; loadConfig.bootstrapScript = scripts[scripts.length - 1]; loadConfig.loadScriptFn = function(loader) { @@ -216,11 +230,82 @@ let _scriptUrls = { window.\$dartLoader.loadConfig = loadConfig; window.\$dartLoader.loader = loader; - // TODO(srujzs): Support hot restart. - // Begin loading libraries loader.nextAttempt(); - } + + // Set up stack trace mapper. + if (window.\$dartStackTraceUtility && + !window.\$dartStackTraceUtility.ready) { + window.\$dartStackTraceUtility.ready = true; + window.\$dartStackTraceUtility.setSourceMapProvider(function(url) { + var baseUrl = window.location.protocol + '//' + window.location.host; + url = url.replace(baseUrl + '/', ''); + if (url == 'dart_sdk.js') { + return dartDevEmbedder.debugger.getSourceMap('dart_sdk'); + } + url = url.replace(".lib.js", ""); + return dartDevEmbedder.debugger.getSourceMap(url); + }); + } + + let currentUri = _currentScript.src; + // We should have written a file containing all the scripts that need to be + // reloaded into the page. This is then read when a hot restart is triggered + // in DDC via the `\$dartReloadModifiedModules` callback. + let restartScripts = currentUri + '.restartScripts'; + + if (!window.\$dartReloadModifiedModules) { + window.\$dartReloadModifiedModules = (function(appName, callback) { + var xhttp = new XMLHttpRequest(); + xhttp.withCredentials = true; + xhttp.onreadystatechange = function() { + // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState + if (this.readyState == 4 && this.status == 200 || this.status == 304) { + var scripts = JSON.parse(this.responseText); + var numToLoad = 0; + var numLoaded = 0; + for (var i = 0; i < scripts.length; i++) { + var script = scripts[i]; + if (script.id == null) continue; + var src = _currentDirectory + script.src.toString(); + var oldSrc = window.\$dartLoader.moduleIdToUrl.get(script.id); + // Only compare the search parameters which contain the cache + // busting portion of the uri. The path might be different if the + // script is loaded from a different application on the page. + if (window.\$dartLoader.moduleIdToUrl.has(script.id) && + new URL(oldSrc).search == new URL(src).search) continue; + + // We might actually load from a different uri, delete the old one + // just to be sure. + window.\$dartLoader.urlToModuleId.delete(oldSrc); + + window.\$dartLoader.moduleIdToUrl.set(script.id, src); + window.\$dartLoader.urlToModuleId.set(src, script.id); + + numToLoad++; + + var el = document.getElementById(script.id); + if (el) el.remove(); + el = window.\$dartCreateScript(); + el.src = policy.createScriptURL(src); + el.async = false; + el.defer = true; + el.id = script.id; + el.onload = function() { + numLoaded++; + if (numToLoad == numLoaded) callback(); + }; + document.head.appendChild(el); + } + // Call `callback` right away if we found no updated scripts. + if (numToLoad == 0) callback(); + } + }; + xhttp.open("GET", restartScripts, true); + xhttp.send(); + }); + } + }; })(); '''; } diff --git a/packages/flutter_tools/test/general.shard/web/bootstrap_test.dart b/packages/flutter_tools/test/general.shard/web/bootstrap_test.dart index 53b9957b32..eb839738c8 100644 --- a/packages/flutter_tools/test/general.shard/web/bootstrap_test.dart +++ b/packages/flutter_tools/test/general.shard/web/bootstrap_test.dart @@ -196,12 +196,11 @@ void main() { ddcModuleLoaderUrl: 'ddc_module_loader.js', mapperUrl: 'mapper.js', generateLoadingIndicator: true, + isWindows: false, ); // ddc module loader js source is interpolated correctly. - expect(result, contains('"moduleLoader": "ddc_module_loader.js"')); expect(result, contains('"src": "ddc_module_loader.js"')); // stack trace mapper source is interpolated correctly. - expect(result, contains('"mapper": "mapper.js"')); expect(result, contains('"src": "mapper.js"')); // data-main is set to correct bootstrap module. expect(result, contains('"src": "main_module.bootstrap.js"')); @@ -214,6 +213,7 @@ void main() { ddcModuleLoaderUrl: 'ddc_module_loader.js', mapperUrl: 'mapper.js', generateLoadingIndicator: true, + isWindows: false, ); // LoadConfiguration and DDCLoader objects must be constructed. expect(result, contains(r'new window.$dartLoader.LoadConfiguration(')); @@ -234,6 +234,7 @@ void main() { ddcModuleLoaderUrl: 'ddc_module_loader.js', mapperUrl: 'mapper.js', generateLoadingIndicator: true, + isWindows: false, ); expect(result, contains('"flutter-loader"')); expect(result, contains('"indeterminate"')); @@ -245,6 +246,7 @@ void main() { ddcModuleLoaderUrl: 'ddc_module_loader.js', mapperUrl: 'mapper.js', generateLoadingIndicator: false, + isWindows: false, ); expect(result, isNot(contains('"flutter-loader"'))); expect(result, isNot(contains('"indeterminate"'))); @@ -257,6 +259,7 @@ void main() { ddcModuleLoaderUrl: 'ddc_module_loader.js', mapperUrl: 'mapper.js', generateLoadingIndicator: true, + isWindows: false, ); // See: https://regexr.com/6q0ft diff --git a/packages/flutter_tools/test/general.shard/web/devfs_web_ddc_modules_test.dart b/packages/flutter_tools/test/general.shard/web/devfs_web_ddc_modules_test.dart index cecd1ad062..e8dc55adb5 100644 --- a/packages/flutter_tools/test/general.shard/web/devfs_web_ddc_modules_test.dart +++ b/packages/flutter_tools/test/general.shard/web/devfs_web_ddc_modules_test.dart @@ -817,6 +817,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.ddcModuleLoaderJS.createSync(recursive: true); webDevFS.flutterJs.createSync(recursive: true); @@ -944,6 +945,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.ddcModuleLoaderJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1019,6 +1021,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.ddcModuleLoaderJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1069,6 +1072,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.ddcModuleLoaderJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1120,6 +1124,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.ddcModuleLoaderJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1171,6 +1176,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.ddcModuleLoaderJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1335,6 +1341,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.ddcModuleLoaderJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); diff --git a/packages/flutter_tools/test/general.shard/web/devfs_web_test.dart b/packages/flutter_tools/test/general.shard/web/devfs_web_test.dart index cc6f6724bf..c780e6b63b 100644 --- a/packages/flutter_tools/test/general.shard/web/devfs_web_test.dart +++ b/packages/flutter_tools/test/general.shard/web/devfs_web_test.dart @@ -995,6 +995,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.flutterJs.createSync(recursive: true); @@ -1114,6 +1115,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.flutterJs.createSync(recursive: true); @@ -1239,6 +1241,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1317,6 +1320,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1370,6 +1374,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1424,6 +1429,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1478,6 +1484,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); @@ -1652,6 +1659,7 @@ void main() { isWasm: false, useLocalCanvasKit: false, rootDirectory: globals.fs.currentDirectory, + isWindows: false, ); webDevFS.requireJS.createSync(recursive: true); webDevFS.stackTraceMapper.createSync(recursive: true); diff --git a/packages/flutter_tools/test/integration.shard/test_data/project.dart b/packages/flutter_tools/test/integration.shard/test_data/project.dart index 6358abe712..34e1389b97 100644 --- a/packages/flutter_tools/test/integration.shard/test_data/project.dart +++ b/packages/flutter_tools/test/integration.shard/test_data/project.dart @@ -10,6 +10,7 @@ import 'deferred_components_config.dart'; const String _kDefaultHtml = ''' + Hello, World diff --git a/packages/flutter_tools/test/web.shard/hot_restart_web_amd_test.dart b/packages/flutter_tools/test/web.shard/hot_restart_web_amd_test.dart new file mode 100644 index 0000000000..b148ae7129 --- /dev/null +++ b/packages/flutter_tools/test/web.shard/hot_restart_web_amd_test.dart @@ -0,0 +1,14 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +@Tags(['flutter-test-driver']) +library; + +import '../src/common.dart'; + +import 'test_data/hot_restart_web_utils.dart'; + +void main() async { + await testAll(useDDCLibraryBundleFormat: false); +} diff --git a/packages/flutter_tools/test/web.shard/hot_restart_web_ddc_library_bundle_test.dart b/packages/flutter_tools/test/web.shard/hot_restart_web_ddc_library_bundle_test.dart new file mode 100644 index 0000000000..5799596e58 --- /dev/null +++ b/packages/flutter_tools/test/web.shard/hot_restart_web_ddc_library_bundle_test.dart @@ -0,0 +1,14 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +@Tags(['flutter-test-driver']) +library; + +import '../src/common.dart'; + +import 'test_data/hot_restart_web_utils.dart'; + +void main() async { + await testAll(useDDCLibraryBundleFormat: true); +} diff --git a/packages/flutter_tools/test/web.shard/hot_reload_web_test.dart b/packages/flutter_tools/test/web.shard/test_data/hot_restart_web_utils.dart similarity index 56% rename from packages/flutter_tools/test/web.shard/hot_reload_web_test.dart rename to packages/flutter_tools/test/web.shard/test_data/hot_restart_web_utils.dart index aafead8430..7e43de0139 100644 --- a/packages/flutter_tools/test/web.shard/hot_reload_web_test.dart +++ b/packages/flutter_tools/test/web.shard/test_data/hot_restart_web_utils.dart @@ -2,61 +2,84 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@Tags(['flutter-test-driver']) -library; - import 'dart:async'; import 'package:file/file.dart'; -import '../integration.shard/test_data/hot_reload_project.dart'; -import '../integration.shard/test_driver.dart'; -import '../integration.shard/test_utils.dart'; -import '../src/common.dart'; +import '../../integration.shard/test_data/hot_reload_project.dart'; +import '../../integration.shard/test_driver.dart'; +import '../../integration.shard/test_utils.dart'; +import '../../src/common.dart'; -import 'test_data/hot_reload_index_html_samples.dart'; +import 'hot_reload_index_html_samples.dart'; void main() async { - await _testProject(HotReloadProject()); // default + await testAll(useDDCLibraryBundleFormat: false); +} + +Future testAll({required bool useDDCLibraryBundleFormat}) async { + await _testProject( + HotReloadProject(), + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, + ); // default await _testProject( HotReloadProject(constApp: true), name: 'Default) (with `const MyApp()`)', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, ); // runApp(const MyApp()); await _testProject( HotReloadProject(indexHtml: indexHtmlFlutterJsCallback), name: 'flutter.js (callback)', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, ); await _testProject( HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesFull), name: 'flutter.js (promises)', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, ); await _testProject( HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesShort), name: 'flutter.js (promises, short)', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, ); await _testProject( HotReloadProject(indexHtml: indexHtmlFlutterJsLoad), name: 'flutter.js (load)', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, + ); + await _testProject( + HotReloadProject(indexHtml: indexHtmlNoFlutterJs), + name: 'No flutter.js', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, ); - await _testProject(HotReloadProject(indexHtml: indexHtmlNoFlutterJs), name: 'No flutter.js'); await _testProject( HotReloadProject(indexHtml: indexHtmlWithFlutterBootstrapScriptTag), name: 'Using flutter_bootstrap.js script tag', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, ); await _testProject( HotReloadProject(indexHtml: indexHtmlWithInlinedFlutterBootstrapScript), name: 'Using inlined flutter_bootstrap.js', + useDDCLibraryBundleFormat: useDDCLibraryBundleFormat, ); } -Future _testProject(HotReloadProject project, {String name = 'Default'}) async { +Future _testProject( + HotReloadProject project, { + String name = 'Default', + required bool useDDCLibraryBundleFormat, +}) async { late Directory tempDir; late FlutterRunTestDriver flutter; - final String testName = 'Hot reload (index.html: $name)'; + final String testName = 'Hot restart (index.html: $name)'; + final List additionalCommandArgs = + useDDCLibraryBundleFormat + ? ['--extra-front-end-options=--dartdevc-canary,--dartdevc-module-format=ddc'] + : []; setUp(() async { - tempDir = createResolvedTempDirectorySync('hot_reload_test.'); + tempDir = createResolvedTempDirectorySync('hot_restart_test.'); await project.setUpIn(tempDir); flutter = FlutterRunTestDriver(tempDir); }); @@ -69,7 +92,10 @@ Future _testProject(HotReloadProject project, {String name = 'Default'}) a testWithoutContext('$testName: hot restart works without error', () async { flutter.stdout.listen(printOnFailure); - await flutter.run(chrome: true, additionalCommandArgs: ['--verbose']); + await flutter.run( + chrome: true, + additionalCommandArgs: ['--verbose', ...additionalCommandArgs], + ); await flutter.hotRestart(); }); @@ -83,7 +109,10 @@ Future _testProject(HotReloadProject project, {String name = 'Default'}) a completer.complete(); } }); - await flutter.run(chrome: true, additionalCommandArgs: ['--verbose']); + await flutter.run( + chrome: true, + additionalCommandArgs: ['--verbose', ...additionalCommandArgs], + ); project.uncommentHotReloadPrint(); try { await flutter.hotRestart();