web.dart 18.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:crypto/crypto.dart';
6
import 'package:package_config/package_config.dart';
7

8 9 10 11 12
import '../../artifacts.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../build_info.dart';
import '../../dart/package_map.dart';
13
import '../../globals.dart' as globals;
14
import '../build_system.dart';
15
import '../depfile.dart';
16
import 'assets.dart';
17
import 'common.dart';
18
import 'localizations.dart';
19 20 21 22 23 24 25 26 27 28 29 30

/// Whether web builds should call the platform initialization logic.
const String kInitializePlatform = 'InitializePlatform';

/// Whether the application has web plugins.
const String kHasWebPlugins = 'HasWebPlugins';

/// An override for the dart2js build mode.
///
/// Valid values are O1 (lowest, profile default) to O4 (highest, release default).
const String kDart2jsOptimization = 'Dart2jsOptimization';

31 32 33
/// Whether to disable dynamic generation code to satisfy csp policies.
const String kCspMode = 'cspMode';

34
/// Generates an entry point for a web target.
Dan Field's avatar
Dan Field committed
35
// Keep this in sync with build_runner/resident_web_runner.dart
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
class WebEntrypointTarget extends Target {
  const WebEntrypointTarget();

  @override
  String get name => 'web_entrypoint';

  @override
  List<Target> get dependencies => const <Target>[];

  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/web.dart'),
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{BUILD_DIR}/main.dart'),
  ];

  @override
  Future<void> build(Environment environment) async {
    final String targetFile = environment.defines[kTargetFile];
    final bool shouldInitializePlatform = environment.defines[kInitializePlatform] == 'true';
    final bool hasPlugins = environment.defines[kHasWebPlugins] == 'true';
60
    final Uri importUri = environment.fileSystem.file(targetFile).absolute.uri;
61
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(
62 63
      environment.projectDir.childFile('.packages'),
      logger: environment.logger,
64
    );
65

66
    // Use the PackageConfig to find the correct package-scheme import path
67 68 69 70 71 72
    // for the user application. If the application has a mix of package-scheme
    // and relative imports for a library, then importing the entrypoint as a
    // file-scheme will cause said library to be recognized as two distinct
    // libraries. This can cause surprising behavior as types from that library
    // will be considered distinct from each other.
    // By construction, this will only be null if the .packages file does not
73 74
    // have an entry for the user's application or if the main file is
    // outside of the lib/ directory.
75 76
    final String mainImport = packageConfig.toPackageUri(importUri)?.toString()
      ?? importUri.toString();
77 78 79

    String contents;
    if (hasPlugins) {
80
      final Uri generatedUri = environment.projectDir
81 82
        .childDirectory('lib')
        .childFile('generated_plugin_registrant.dart')
83 84 85 86
        .absolute
        .uri;
      final String generatedImport = packageConfig.toPackageUri(generatedUri)?.toString()
        ?? generatedUri.toString();
87 88 89 90 91
      contents = '''
import 'dart:ui' as ui;

import 'package:flutter_web_plugins/flutter_web_plugins.dart';

92 93
import '$generatedImport';
import '$mainImport' as entrypoint;
94 95 96 97 98 99 100 101 102 103 104 105 106

Future<void> main() async {
  registerPlugins(webPluginRegistry);
  if ($shouldInitializePlatform) {
    await ui.webOnlyInitializePlatform();
  }
  entrypoint.main();
}
''';
    } else {
      contents = '''
import 'dart:ui' as ui;

107
import '$mainImport' as entrypoint;
108 109 110 111 112 113 114 115 116 117

Future<void> main() async {
  if ($shouldInitializePlatform) {
    await ui.webOnlyInitializePlatform();
  }
  entrypoint.main();
}
''';
    }
    environment.buildDir.childFile('main.dart')
118
      .writeAsStringSync(contents);
119 120 121
  }
}

122
/// Compiles a web entry point with dart2js.
123 124 125 126 127 128 129 130
class Dart2JSTarget extends Target {
  const Dart2JSTarget();

  @override
  String get name => 'dart2js';

  @override
  List<Target> get dependencies => const <Target>[
131 132
    WebEntrypointTarget(),
    GenerateLocalizationsTarget(),
133 134 135 136 137 138 139 140 141 142 143 144
  ];

  @override
  List<Source> get inputs => const <Source>[
    Source.artifact(Artifact.flutterWebSdk),
    Source.artifact(Artifact.dart2jsSnapshot),
    Source.artifact(Artifact.engineDartBinary),
    Source.pattern('{BUILD_DIR}/main.dart'),
    Source.pattern('{PROJECT_DIR}/.packages'),
  ];

  @override
145 146 147 148 149
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => const <String>[
    'dart2js.d',
150 151 152 153 154
  ];

  @override
  Future<void> build(Environment environment) async {
    final String dart2jsOptimization = environment.defines[kDart2jsOptimization];
155
    final bool csp = environment.defines[kCspMode] == 'true';
156
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
157 158
    final String specPath = globals.fs.path.join(
      globals.artifacts.getArtifactPath(Artifact.flutterWebSdk), 'libraries.json');
159
    final String packageFile = globalPackagesPath;
160
    final File outputKernel = environment.buildDir.childFile('app.dill');
161
    final File outputFile = environment.buildDir.childFile('main.dart.js');
162 163
    final List<String> dartDefines = decodeDartDefines(environment.defines, kDartDefines);
    final List<String> extraFrontEndOptions = decodeDartDefines(environment.defines, kExtraFrontEndOptions);
164

165 166 167 168
    // Run the dart2js compilation in two stages, so that icon tree shaking can
    // parse the kernel file for web builds.
    final ProcessResult kernelResult = await globals.processManager.run(<String>[
      globals.artifacts.getArtifactPath(Artifact.engineDartBinary),
169
      '--disable-dart-dev',
170 171
      globals.artifacts.getArtifactPath(Artifact.dart2jsSnapshot),
      '--libraries-spec=$specPath',
172
      ...?extraFrontEndOptions,
173 174
      '-o',
      outputKernel.path,
175 176 177 178 179
      '--packages=$packageFile',
      if (buildMode == BuildMode.profile)
        '-Ddart.vm.profile=true'
      else
        '-Ddart.vm.product=true',
180 181
      for (final String dartDefine in dartDefines)
        '-D$dartDefine',
182 183 184 185 186 187 188
      '--cfe-only',
      environment.buildDir.childFile('main.dart').path,
    ]);
    if (kernelResult.exitCode != 0) {
      throw Exception(kernelResult.stdout + kernelResult.stderr);
    }
    final ProcessResult javaScriptResult = await globals.processManager.run(<String>[
189
      globals.artifacts.getArtifactPath(Artifact.engineDartBinary),
190
      '--disable-dart-dev',
191
      globals.artifacts.getArtifactPath(Artifact.dart2jsSnapshot),
192
      '--libraries-spec=$specPath',
193
      ...?extraFrontEndOptions,
194 195 196 197
      if (dart2jsOptimization != null)
        '-$dart2jsOptimization'
      else
        '-O4',
198 199 200 201
      if (buildMode == BuildMode.profile)
        '-Ddart.vm.profile=true'
      else
        '-Ddart.vm.product=true',
202 203 204 205
      for (final String dartDefine in dartDefines)
        '-D$dartDefine',
      if (buildMode == BuildMode.profile)
        '--no-minify',
206 207
      if (csp)
        '--csp',
208 209 210
      '-o',
      outputFile.path,
      environment.buildDir.childFile('app.dill').path,
211
    ]);
212 213
    if (javaScriptResult.exitCode != 0) {
      throw Exception(javaScriptResult.stdout + javaScriptResult.stderr);
214
    }
215
    final File dart2jsDeps = environment.buildDir
216
      .childFile('app.dill.deps');
217
    if (!dart2jsDeps.existsSync()) {
218
      globals.printError('Warning: dart2js did not produced expected deps list at '
219 220 221
        '${dart2jsDeps.path}');
      return;
    }
222 223 224 225 226
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    final Depfile depfile = depfileService.parseDart2js(
227
      environment.buildDir.childFile('app.dill.deps'),
228 229
      outputFile,
    );
230 231 232 233
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('dart2js.d'),
    );
234 235 236
  }
}

237
/// Unpacks the dart2js compilation and resources to a given output directory
238 239 240 241 242 243 244 245 246 247 248 249 250 251
class WebReleaseBundle extends Target {
  const WebReleaseBundle();

  @override
  String get name => 'web_release_bundle';

  @override
  List<Target> get dependencies => const <Target>[
    Dart2JSTarget(),
  ];

  @override
  List<Source> get inputs => const <Source>[
    Source.pattern('{BUILD_DIR}/main.dart.js'),
252
    Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
253 254 255 256 257
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{OUTPUT_DIR}/main.dart.js'),
258 259 260 261 262
  ];

  @override
  List<String> get depfiles => const <String>[
    'dart2js.d',
263 264
    'flutter_assets.d',
    'web_resources.d',
265 266 267 268
  ];

  @override
  Future<void> build(Environment environment) async {
269
    for (final File outputFile in environment.buildDir.listSync(recursive: true).whereType<File>()) {
270 271 272 273 274 275
      final String basename = globals.fs.path.basename(outputFile.path);
      if (!basename.contains('main.dart.js')) {
        continue;
      }
      // Do not copy the deps file.
      if (basename.endsWith('.deps')) {
276 277 278
        continue;
      }
      outputFile.copySync(
279
        environment.outputDir.childFile(globals.fs.path.basename(outputFile.path)).path
280 281
      );
    }
282 283 284
    final Directory outputDirectory = environment.outputDir.childDirectory('assets');
    outputDirectory.createSync(recursive: true);
    final Depfile depfile = await copyAssets(environment, environment.outputDir.childDirectory('assets'));
285 286 287 288 289 290 291 292
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

    final Directory webResources = environment.projectDir
      .childDirectory('web');
    final List<File> inputResourceFiles = webResources
      .listSync(recursive: true)
      .whereType<File>()
      .toList();

    // Copy other resource files out of web/ directory.
    final List<File> outputResourcesFiles = <File>[];
    for (final File inputFile in inputResourceFiles) {
      final File outputFile = globals.fs.file(globals.fs.path.join(
        environment.outputDir.path,
        globals.fs.path.relative(inputFile.path, from: webResources.path)));
      if (!outputFile.parent.existsSync()) {
        outputFile.parent.createSync(recursive: true);
      }
      inputFile.copySync(outputFile.path);
      outputResourcesFiles.add(outputFile);
    }
    final Depfile resourceFile = Depfile(inputResourceFiles, outputResourcesFiles);
314 315 316 317
    depfileService.writeToFile(
      resourceFile,
      environment.buildDir.childFile('web_resources.d'),
    );
318 319
  }
}
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

/// Generate a service worker for a web target.
class WebServiceWorker extends Target {
  const WebServiceWorker();

  @override
  String get name => 'web_service_worker';

  @override
  List<Target> get dependencies => const <Target>[
    Dart2JSTarget(),
    WebReleaseBundle(),
  ];

  @override
  List<String> get depfiles => const <String>[
    'service_worker.d',
  ];

  @override
  List<Source> get inputs => const <Source>[];

  @override
  List<Source> get outputs => const <Source>[];

  @override
  Future<void> build(Environment environment) async {
    final List<File> contents = environment.outputDir
      .listSync(recursive: true)
      .whereType<File>()
      .where((File file) => !file.path.endsWith('flutter_service_worker.js')
        && !globals.fs.path.basename(file.path).startsWith('.'))
      .toList();
353 354 355 356

    final Map<String, String> urlToHash = <String, String>{};
    for (final File file in contents) {
      // Do not force caching of source maps.
357 358
      if (file.path.endsWith('main.dart.js.map') ||
        file.path.endsWith('.part.js.map')) {
359 360 361 362 363 364 365 366 367
        continue;
      }
      final String url = globals.fs.path.toUri(
        globals.fs.path.relative(
          file.path,
          from: environment.outputDir.path),
        ).toString();
      final String hash = md5.convert(await file.readAsBytes()).toString();
      urlToHash[url] = hash;
368 369 370 371
      // Add an additional entry for the base URL.
      if (globals.fs.path.basename(url) == 'index.html') {
        urlToHash['/'] = hash;
      }
372 373
    }

374 375 376
    final File serviceWorkerFile = environment.outputDir
      .childFile('flutter_service_worker.js');
    final Depfile depfile = Depfile(contents, <File>[serviceWorkerFile]);
377 378
    final String serviceWorker = generateServiceWorker(urlToHash, <String>[
      '/',
379
      'main.dart.js',
380 381
      'index.html',
      'assets/LICENSE',
382 383
      if (urlToHash.containsKey('assets/AssetManifest.json'))
        'assets/AssetManifest.json',
384 385 386
      if (urlToHash.containsKey('assets/FontManifest.json'))
        'assets/FontManifest.json',
    ]);
387 388
    serviceWorkerFile
      .writeAsStringSync(serviceWorker);
389 390 391 392 393 394 395 396
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('service_worker.d'),
    );
397 398 399 400 401 402
  }
}

/// Generate a service worker with an app-specific cache name a map of
/// resource files.
///
403
/// The tool embeds file hashes directly into the worker so that the byte for byte
404 405
/// invalidation will automatically reactivate workers whenever a new
/// version is deployed.
406
String generateServiceWorker(Map<String, String> resources, List<String> coreBundle) {
407 408
  return '''
'use strict';
409 410
const MANIFEST = 'flutter-app-manifest';
const TEMP = 'flutter-temp-cache';
411 412 413 414 415
const CACHE_NAME = 'flutter-app-cache';
const RESOURCES = {
  ${resources.entries.map((MapEntry<String, String> entry) => '"${entry.key}": "${entry.value}"').join(",\n")}
};

416 417 418 419 420 421 422 423 424
// The application shell files that are downloaded before a service worker can
// start.
const CORE = [
  ${coreBundle.map((String file) => '"$file"').join(',\n')}];

// During install, the TEMP cache is populated with the application shell files.
self.addEventListener("install", (event) => {
  return event.waitUntil(
    caches.open(TEMP).then((cache) => {
425 426
      // Provide a no-cache param to ensure the latest version is downloaded.
      return cache.addAll(CORE.map((value) => new Request(value, {'cache': 'no-cache'})));
427 428 429 430
    })
  );
});

431 432 433 434 435 436 437 438 439 440 441 442 443 444
// During activate, the cache is populated with the temp files downloaded in
// install. If this service worker is upgrading from one with a saved
// MANIFEST, then use this to retain unchanged resource files.
self.addEventListener("activate", function(event) {
  return event.waitUntil(async function() {
    try {
      var contentCache = await caches.open(CACHE_NAME);
      var tempCache = await caches.open(TEMP);
      var manifestCache = await caches.open(MANIFEST);
      var manifest = await manifestCache.match('manifest');

      // When there is no prior manifest, clear the entire cache.
      if (!manifest) {
        await caches.delete(CACHE_NAME);
445
        contentCache = await caches.open(CACHE_NAME);
446 447 448
        for (var request of await tempCache.keys()) {
          var response = await tempCache.match(request);
          await contentCache.put(request, response);
449
        }
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        await caches.delete(TEMP);
        // Save the manifest to make future upgrades efficient.
        await manifestCache.put('manifest', new Response(JSON.stringify(RESOURCES)));
        return;
      }

      var oldManifest = await manifest.json();
      var origin = self.location.origin;
      for (var request of await contentCache.keys()) {
        var key = request.url.substring(origin.length + 1);
        if (key == "") {
          key = "/";
        }
        // If a resource from the old manifest is not in the new cache, or if
        // the MD5 sum has changed, delete it. Otherwise the resource is left
        // in the cache and can be reused by the new service worker.
        if (!RESOURCES[key] || RESOURCES[key] != oldManifest[key]) {
          await contentCache.delete(request);
        }
      }
      // Populate the cache with the app shell TEMP files, potentially overwriting
      // cache files preserved above.
      for (var request of await tempCache.keys()) {
        var response = await tempCache.match(request);
        await contentCache.put(request, response);
      }
      await caches.delete(TEMP);
      // Save the manifest to make future upgrades efficient.
      await manifestCache.put('manifest', new Response(JSON.stringify(RESOURCES)));
      return;
    } catch (err) {
      // On an unhandled exception the state of the cache cannot be guaranteed.
      console.error('Failed to upgrade service worker: ' + err);
      await caches.delete(CACHE_NAME);
      await caches.delete(TEMP);
      await caches.delete(MANIFEST);
    }
  }());
});

// The fetch handler redirects requests for RESOURCE files to the service
// worker cache.
self.addEventListener("fetch", (event) => {
  var origin = self.location.origin;
  var key = event.request.url.substring(origin.length + 1);
495 496 497 498
  // Redirect URLs to the index.html
  if (event.request.url == origin || event.request.url.startsWith(origin + '/#')) {
    key = '/';
  }
499 500 501 502 503 504 505 506
  // If the URL is not the the RESOURCE list, skip the cache.
  if (!RESOURCES[key]) {
    return event.respondWith(fetch(event.request));
  }
  event.respondWith(caches.open(CACHE_NAME)
    .then((cache) =>  {
      return cache.match(event.request).then((response) => {
        // Either respond with the cached resource, or perform a fetch and
507 508 509 510
        // lazily populate the cache. Ensure the resources are not cached
        // by the browser for longer than the service worker expects.
        var modifiedRequest = new Request(event.request, {'cache': 'no-cache'});
        return response || fetch(modifiedRequest).then((response) => {
511 512 513
          cache.put(event.request, response.clone());
          return response;
        });
514
      })
515
    })
516 517
  );
});
518

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
self.addEventListener('message', (event) => {
  // SkipWaiting can be used to immediately activate a waiting service worker.
  // This will also require a page refresh triggered by the main worker.
  if (event.message == 'skipWaiting') {
    return self.skipWaiting();
  }

  if (event.message = 'downloadOffline') {
    downloadOffline();
  }
});

// Download offline will check the RESOURCES for all files not in the cache
// and populate them.
async function downloadOffline() {
  var resources = [];
  var contentCache = await caches.open(CACHE_NAME);
  var currentContent = {};
  for (var request of await contentCache.keys()) {
    var key = request.url.substring(origin.length + 1);
    if (key == "") {
      key = "/";
    }
    currentContent[key] = true;
  }
  for (var resourceKey in Object.keys(RESOURCES)) {
    if (!currentContent[resourceKey]) {
      resources.add(resourceKey);
    }
  }
  return Cache.addAll(resources);
}
551 552
''';
}