devfs_web.dart 32.7 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 'dart:async';
6 7
import 'dart:typed_data';

8 9 10
import 'package:dwds/data/build_result.dart';
import 'package:dwds/dwds.dart';
import 'package:logging/logging.dart';
11 12
import 'package:meta/meta.dart';
import 'package:mime/mime.dart' as mime;
13
import 'package:package_config/package_config.dart';
14 15
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as shelf;
16

17 18
import '../artifacts.dart';
import '../asset.dart';
19 20 21
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
22
import '../base/net.dart';
23
import '../base/platform.dart';
24
import '../base/utils.dart';
25
import '../build_info.dart';
26
import '../bundle.dart';
27
import '../cache.dart';
28
import '../compile.dart';
29
import '../convert.dart';
30
import '../dart/package_map.dart';
31
import '../devfs.dart';
32
import '../globals.dart' as globals;
33 34
import '../web/bootstrap.dart';
import '../web/chrome.dart';
35

36 37 38 39 40 41 42 43 44
typedef DwdsLauncher = Future<Dwds> Function({
  @required AssetReader assetReader,
  @required Stream<BuildResult> buildResults,
  @required ConnectionProvider chromeConnection,
  @required LoadStrategy loadStrategy,
  @required bool enableDebugging,
  bool enableDebugExtension,
  String hostname,
  bool useSseForDebugProxy,
45
  bool useSseForDebugBackend,
46 47 48 49
  bool serveDevTools,
  void Function(Level, String) logWriter,
  bool verbose,
  UrlEncoder urlEncoder,
50
  bool useFileProvider,
51 52 53
  ExpressionCompiler expressionCompiler,
});

54 55 56 57 58 59 60 61 62
// A minimal index for projects that do not yet support web.
const String _kDefaultIndex = '''
<html>
    <body>
        <script src="main.dart.js"></script>
    </body>
</html>
''';

63
/// An expression compiler connecting to FrontendServer.
64
///
65
/// This is only used in development mode.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
class WebExpressionCompiler implements ExpressionCompiler {
  WebExpressionCompiler(this._generator);

  final ResidentCompiler _generator;

  @override
  Future<ExpressionCompilationResult> compileExpressionToJs(
    String isolateId,
    String libraryUri,
    int line,
    int column,
    Map<String, String> jsModules,
    Map<String, String> jsFrameValues,
    String moduleName,
    String expression,
  ) async {
    final CompilerOutput compilerOutput = await _generator.compileExpressionToJs(libraryUri,
        line, column, jsModules, jsFrameValues, moduleName, expression);

    if (compilerOutput != null && compilerOutput.outputFilename != null) {
      final String content = utf8.decode(
          globals.fs.file(compilerOutput.outputFilename).readAsBytesSync());
      return ExpressionCompilationResult(
          content, compilerOutput.errorCount > 0);
    }

92 93
    return ExpressionCompilationResult(
      'InternalError: frontend server failed to compile \'$expression\'', true);
94 95 96
  }
}

97 98 99
/// A web server which handles serving JavaScript and assets.
///
/// This is only used in development mode.
100
class WebAssetServer implements AssetReader {
101
  @visibleForTesting
102 103 104 105 106 107
  WebAssetServer(
    this._httpServer,
    this._packages,
    this.internetAddress,
    this._modules,
    this._digests,
108
    this._buildInfo,
109
  );
110 111 112 113 114

  // Fallback to "application/octet-stream" on null which
  // makes no claims as to the structure of the data.
  static const String _kDefaultMimeType = 'application/octet-stream';

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  final Map<String, String> _modules;
  final Map<String, String> _digests;

  void performRestart(List<String> modules) {
    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
      // to will change.
      final String moduleName = module.startsWith('/')
        ? module.substring(1)
        : module;
      final String name = moduleName.replaceAll('.lib.js', '');
      final String path = moduleName.replaceAll('.js', '');
      _modules[name] = path;
      _digests[name] = _files[moduleName].hashCode.toString();
    }
  }

133 134
  /// Start the web asset server on a [hostname] and [port].
  ///
135 136 137
  /// If [testMode] is true, do not actually initialize dwds or the shelf static
  /// server.
  ///
138 139
  /// Unhandled exceptions will throw a [ToolExit] with the error and stack
  /// trace.
140
  static Future<WebAssetServer> start(
141
    ChromiumLauncher chromiumLauncher,
142 143 144
    String hostname,
    int port,
    UrlTunneller urlTunneller,
145
    bool useSseForDebugProxy,
146
    bool useSseForDebugBackend,
147
    BuildInfo buildInfo,
148
    bool enableDwds,
149 150
    Uri entrypoint,
    ExpressionCompiler expressionCompiler, {
151
    bool testMode = false,
152
    DwdsLauncher dwdsLauncher = Dwds.start,
153
  }) async {
154
    try {
155 156 157 158 159 160
      InternetAddress address;
      if (hostname == 'any') {
        address = InternetAddress.anyIPv4;
      } else {
        address = (await InternetAddress.lookup(hostname)).first;
      }
161
      final HttpServer httpServer = await HttpServer.bind(address, port);
162 163 164
      // Allow rendering in a iframe.
      httpServer.defaultResponseHeaders.remove('x-frame-options', 'SAMEORIGIN');

165
      final PackageConfig packageConfig = await loadPackageConfigWithLogging(
166
        globals.fs.file(buildInfo.packagesPath),
167
        logger: globals.logger,
168
      );
169 170 171 172
      final Map<String, String> digests = <String, String>{};
      final Map<String, String> modules = <String, String>{};
      final WebAssetServer server = WebAssetServer(
        httpServer,
173
        packageConfig,
174 175 176
        address,
        modules,
        digests,
177
        buildInfo,
178
      );
179 180 181
      if (testMode) {
        return server;
      }
182 183

      // In release builds deploy a simpler proxy server.
184
      if (buildInfo.mode != BuildMode.debug) {
185 186 187 188 189 190 191
        final ReleaseAssetServer releaseAssetServer = ReleaseAssetServer(
          entrypoint,
          fileSystem: globals.fs,
          platform: globals.platform,
          flutterRoot: Cache.flutterRoot,
          webBuildDirectory: getWebBuildDirectory(),
        );
192 193 194
        shelf.serveRequests(httpServer, releaseAssetServer.handle);
        return server;
      }
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
      // Return the set of all active modules. This is populated by the
      // frontend_server update logic.
      Future<Map<String, String>> moduleProvider(String path) async {
        return modules;
      }
      // Return a version string for all active modules. This is populated
      // along with the `moduleProvider` update logic.
      Future<Map<String, String>> digestProvider(String path) async {
        return digests;
      }
      // Return the module name for a given server path. These are the names
      // used by the browser to request JavaScript files.
      String moduleForServerPath(String serverPath) {
        if (serverPath.endsWith('.lib.js')) {
          serverPath = serverPath.startsWith('/')
            ? serverPath.substring(1)
            : serverPath;
          return serverPath.replaceAll('.lib.js', '');
        }
        return null;
      }
      // Return the server path for modules. These are the JavaScript file names
      // output by the frontend_server.
      String serverPathForModule(String module) {
        return '$module.lib.js';
      }
      // Return the server path for modules or resources that have an
      // org-dartlang-app scheme.
      String serverPathForAppUri(String appUri) {
        if (appUri.startsWith('org-dartlang-app:')) {
          return Uri.parse(appUri).path.substring(1);
        }
        return null;
      }

230
      // In debug builds, spin up DWDS and the full asset server.
231
      final Dwds dwds = await dwdsLauncher(
232
        assetReader: server,
233
        enableDebugExtension: true,
234 235
        buildResults: const Stream<BuildResult>.empty(),
        chromeConnection: () async {
236 237
          final Chromium chromium = await chromiumLauncher.connectedInstance;
          return chromium.chromeConnection;
238
        },
239
        hostname: hostname,
240 241
        urlEncoder: urlTunneller,
        enableDebugging: true,
242
        useSseForDebugProxy: useSseForDebugProxy,
243
        useSseForDebugBackend: useSseForDebugBackend,
244
        serveDevTools: false,
245 246 247 248
        logWriter: (Level logLevel, String message) => globals.printTrace(message),
        loadStrategy: RequireStrategy(
          ReloadConfiguration.none,
          '.lib.js',
249 250 251 252 253
          moduleProvider,
          digestProvider,
          moduleForServerPath,
          serverPathForModule,
          serverPathForAppUri,
254
        ),
255
        useFileProvider: true,
256
        expressionCompiler: expressionCompiler
257 258 259 260 261 262 263 264 265 266 267 268
      );
      shelf.Pipeline pipeline = const shelf.Pipeline();
      if (enableDwds) {
        pipeline = pipeline.addMiddleware(dwds.middleware);
      }
      final shelf.Handler dwdsHandler = pipeline.addHandler(server.handleRequest);
      final shelf.Cascade cascade = shelf.Cascade()
        .add(dwds.handler)
        .add(dwdsHandler);
      shelf.serveRequests(httpServer, cascade.handler);
      server.dwds = dwds;
      return server;
269 270 271 272 273 274 275
    } on SocketException catch (err) {
      throwToolExit('Failed to bind web development server:\n$err');
    }
    assert(false);
    return null;
  }

276
  final BuildInfo _buildInfo;
277
  final HttpServer _httpServer;
278 279
  // If holding these in memory is too much overhead, this can be switched to a
  // RandomAccessFile and read on demand.
280
  final Map<String, Uint8List> _files = <String, Uint8List>{};
281
  final Map<String, Uint8List> _sourcemaps = <String, Uint8List>{};
282 283
  final Map<String, Uint8List> _metadataFiles = <String, Uint8List>{};
  String _mergedMetadata;
284
  final PackageConfig _packages;
285
  final InternetAddress internetAddress;
286
  /* late final */ Dwds dwds;
287
  Directory entrypointCacheDirectory;
288

289 290 291
  @visibleForTesting
  HttpHeaders get defaultResponseHeaders => _httpServer.defaultResponseHeaders;

292 293 294 295 296 297
  @visibleForTesting
  Uint8List getFile(String path) => _files[path];

  @visibleForTesting
  Uint8List getSourceMap(String path) => _sourcemaps[path];

298 299 300
  @visibleForTesting
  Uint8List getMetadata(String path) => _metadataFiles[path];

301
  // handle requests for JavaScript source, dart sources maps, or asset files.
302 303
  @visibleForTesting
  Future<shelf.Response> handleRequest(shelf.Request request) async {
304 305 306 307
    String requestPath = request.url.path;
    while (requestPath.startsWith('/')) {
      requestPath = requestPath.substring(1);
    }
308
    final Map<String, String> headers = <String, String>{};
309
    // If the response is `/`, then we are requesting the index file.
310
    if (request.url.path == '/' || request.url.path.isEmpty) {
311
      final File indexFile = globals.fs.currentDirectory
312 313
        .childDirectory('web')
        .childFile('index.html');
314
      if (indexFile.existsSync()) {
315 316 317
        headers[HttpHeaders.contentTypeHeader] = 'text/html';
        headers[HttpHeaders.contentLengthHeader] = indexFile.lengthSync().toString();
        return shelf.Response.ok(indexFile.openRead(), headers: headers);
318 319 320 321
      } else {
        headers[HttpHeaders.contentTypeHeader] = 'text/html';
        headers[HttpHeaders.contentLengthHeader] = _kDefaultIndex.length.toString();
        return shelf.Response.ok(_kDefaultIndex, headers: headers);
322 323
      }
    }
324

325 326 327 328
    // Track etag headers for better caching of resources.
    final String ifNoneMatch = request.headers[HttpHeaders.ifNoneMatchHeader];
    headers[HttpHeaders.cacheControlHeader] = 'max-age=0, must-revalidate';

329
    // If this is a JavaScript file, it must be in the in-memory cache.
330
    // Attempt to look up the file by URI.
331 332 333
    final String webServerPath = requestPath.replaceFirst('.dart.js', '.dart.lib.js');
    if (_files.containsKey(requestPath) || _files.containsKey(webServerPath)) {
      final List<int> bytes = getFile(requestPath)  ?? getFile(webServerPath);
334 335 336 337 338 339 340
      // Use the underlying buffer hashCode as a revision string. This buffer is
      // replaced whenever the frontend_server produces new output files, which
      // will also change the hashCode.
      final String etag = bytes.hashCode.toString();
      if (ifNoneMatch == etag) {
        return shelf.Response.notModified();
      }
341 342
      headers[HttpHeaders.contentLengthHeader] = bytes.length.toString();
      headers[HttpHeaders.contentTypeHeader] = 'application/javascript';
343
      headers[HttpHeaders.etagHeader] = etag;
344
      return shelf.Response.ok(bytes, headers: headers);
345
    }
346 347
    // If this is a sourcemap file, then it might be in the in-memory cache.
    // Attempt to lookup the file by URI.
348
    if (_sourcemaps.containsKey(requestPath)) {
349
      final List<int> bytes = getSourceMap(requestPath);
350 351 352 353
      final String etag = bytes.hashCode.toString();
      if (ifNoneMatch == etag) {
        return shelf.Response.notModified();
      }
354 355
      headers[HttpHeaders.contentLengthHeader] = bytes.length.toString();
      headers[HttpHeaders.contentTypeHeader] = 'application/json';
356
      headers[HttpHeaders.etagHeader] = etag;
357
      return shelf.Response.ok(bytes, headers: headers);
358 359
    }

360 361 362 363 364 365 366 367 368 369 370 371 372 373
    // If this is a metadata file, then it might be in the in-memory cache.
    // Attempt to lookup the file by URI.
    if (_metadataFiles.containsKey(requestPath)) {
      final List<int> bytes = getMetadata(requestPath);
      final String etag = bytes.hashCode.toString();
      if (ifNoneMatch == etag) {
        return shelf.Response.notModified();
      }
      headers[HttpHeaders.contentLengthHeader] = bytes.length.toString();
      headers[HttpHeaders.contentTypeHeader] = 'application/json';
      headers[HttpHeaders.etagHeader] = etag;
      return shelf.Response.ok(bytes, headers: headers);
    }

374
    File file = _resolveDartFile(requestPath);
375 376

    // If all of the lookups above failed, the file might have been an asset.
377 378
    // Try and resolve the path relative to the built asset directory.
    if (!file.existsSync()) {
379
      final Uri potential = globals.fs.directory(getAssetBuildDirectory())
380
        .uri.resolve(requestPath.replaceFirst('assets/', ''));
381
      file = globals.fs.file(potential);
382 383
    }

384
    if (!file.existsSync()) {
385 386 387
      final Uri webPath = globals.fs.currentDirectory
        .childDirectory('web')
        .uri.resolve(requestPath);
388 389 390
      file = globals.fs.file(webPath);
    }

391
    if (!file.existsSync()) {
392
      return shelf.Response.notFound('');
393
    }
394

395 396
    // For real files, use a serialized file stat plus path as a revision.
    // This allows us to update between canvaskit and non-canvaskit SDKs.
397 398
    final String etag = file.lastModifiedSync().toIso8601String()
      + Uri.encodeComponent(file.path);
399 400 401 402
    if (ifNoneMatch == etag) {
      return shelf.Response.notModified();
    }

403 404 405 406 407 408
    final int length = file.lengthSync();
    // Attempt to determine the file's mime type. if this is not provided some
    // browsers will refuse to render images/show video et cetera. If the tool
    // cannot determine a mime type, fall back to application/octet-stream.
    String mimeType;
    if (length >= 12) {
409
      mimeType = mime.lookupMimeType(
410 411 412 413 414
        file.path,
        headerBytes: await file.openRead(0, 12).first,
      );
    }
    mimeType ??= _kDefaultMimeType;
415 416
    headers[HttpHeaders.contentLengthHeader] = length.toString();
    headers[HttpHeaders.contentTypeHeader] = mimeType;
417
    headers[HttpHeaders.etagHeader] = etag;
418
    return shelf.Response.ok(file.openRead(), headers: headers);
419 420 421 422 423 424 425 426 427
  }

  /// Tear down the http server running.
  Future<void> dispose() {
    return _httpServer.close();
  }

  /// Write a single file into the in-memory cache.
  void writeFile(String filePath, String contents) {
428 429 430 431 432
    writeBytes(filePath, utf8.encode(contents) as Uint8List);
  }

  void writeBytes(String filePath, Uint8List contents) {
    _files[filePath] = contents;
433 434 435 436 437
  }

  /// Update the in-memory asset server with the provided source and manifest files.
  ///
  /// Returns a list of updated modules.
438 439 440 441 442
  List<String> write(
      File codeFile,
      File manifestFile,
      File sourcemapFile,
      File metadataFile) {
443
    final List<String> modules = <String>[];
444 445
    final Uint8List codeBytes = codeFile.readAsBytesSync();
    final Uint8List sourcemapBytes = sourcemapFile.readAsBytesSync();
446
    final Uint8List metadataBytes = metadataFile.readAsBytesSync();
447
    final Map<String, dynamic> manifest = castStringKeyedMap(json.decode(manifestFile.readAsStringSync()));
448
    for (final String filePath in manifest.keys) {
449
      if (filePath == null) {
450
        globals.printTrace('Invalid manfiest file: $filePath');
451 452
        continue;
      }
453 454 455
      final Map<String, dynamic> offsets = castStringKeyedMap(manifest[filePath]);
      final List<int> codeOffsets = (offsets['code'] as List<dynamic>).cast<int>();
      final List<int> sourcemapOffsets = (offsets['sourcemap'] as List<dynamic>).cast<int>();
456 457 458 459
      final List<int> metadataOffsets = (offsets['metadata'] as List<dynamic>).cast<int>();
      if (codeOffsets.length != 2 ||
          sourcemapOffsets.length != 2 ||
          metadataOffsets.length != 2) {
460
        globals.printTrace('Invalid manifest byte offsets: $offsets');
461 462
        continue;
      }
463 464 465 466

      final int codeStart = codeOffsets[0];
      final int codeEnd = codeOffsets[1];
      if (codeStart < 0 || codeEnd > codeBytes.lengthInBytes) {
467
        globals.printTrace('Invalid byte index: [$codeStart, $codeEnd]');
468 469
        continue;
      }
470 471 472 473 474
      final Uint8List byteView = Uint8List.view(
        codeBytes.buffer,
        codeStart,
        codeEnd - codeStart,
      );
475 476 477 478
      final String fileName = filePath.startsWith('/')
        ? filePath.substring(1)
        : filePath;
      _files[fileName] = byteView;
479 480 481 482

      final int sourcemapStart = sourcemapOffsets[0];
      final int sourcemapEnd = sourcemapOffsets[1];
      if (sourcemapStart < 0 || sourcemapEnd > sourcemapBytes.lengthInBytes) {
483
        globals.printTrace('Invalid byte index: [$sourcemapStart, $sourcemapEnd]');
484 485 486 487 488
        continue;
      }
      final Uint8List sourcemapView = Uint8List.view(
        sourcemapBytes.buffer,
        sourcemapStart,
489
        sourcemapEnd - sourcemapStart,
490
      );
491 492
      final String sourcemapName = '$fileName.map';
      _sourcemaps[sourcemapName] = sourcemapView;
493

494 495 496 497 498 499 500 501 502 503 504 505 506 507
      final int metadataStart = metadataOffsets[0];
      final int metadataEnd = metadataOffsets[1];
      if (metadataStart < 0 || metadataEnd > metadataBytes.lengthInBytes) {
        globals.printTrace('Invalid byte index: [$metadataStart, $metadataEnd]');
        continue;
      }
      final Uint8List metadataView = Uint8List.view(
        metadataBytes.buffer,
        metadataStart,
        metadataEnd - metadataStart,
      );
      final String metadataName = '$fileName.metadata';
      _metadataFiles[metadataName] = metadataView;

508
      modules.add(fileName);
509
    }
510 511 512 513 514

    _mergedMetadata = _metadataFiles.values
      .map((Uint8List encoded) => utf8.decode(encoded))
      .join('\n');

515 516
    return modules;
  }
517

518 519 520
  /// Whether to use the cavaskit SDK for rendering.
  bool canvasKitRendering = false;

521 522
  // Attempt to resolve `path` to a dart file.
  File _resolveDartFile(String path) {
523 524
    // Return the actual file objects so that local engine changes are automatically picked up.
    switch (path) {
525
      case 'dart_sdk.js':
526 527 528 529 530 531 532 533 534 535
        if (_buildInfo.nullSafetyMode == NullSafetyMode.unsound) {
          return globals.fs.file(canvasKitRendering
            ? globals.artifacts.getArtifactPath(Artifact.webPrecompiledCanvaskitSdk)
            : globals.artifacts.getArtifactPath(Artifact.webPrecompiledSdk));
        } else {
          return globals.fs.file(canvasKitRendering
            ? globals.artifacts.getArtifactPath(Artifact.webPrecompiledCanvaskitSoundSdk)
            : globals.artifacts.getArtifactPath(Artifact.webPrecompiledSoundSdk));
        }
        break;
536
      case 'dart_sdk.js.map':
537 538 539 540 541 542 543 544 545
        if (_buildInfo.nullSafetyMode == NullSafetyMode.unsound) {
          return globals.fs.file(canvasKitRendering
            ? globals.artifacts.getArtifactPath(Artifact.webPrecompiledCanvaskitSdkSourcemaps)
            : globals.artifacts.getArtifactPath(Artifact.webPrecompiledSdkSourcemaps));
        } else {
          return globals.fs.file(canvasKitRendering
            ? globals.artifacts.getArtifactPath(Artifact.webPrecompiledCanvaskitSoundSdkSourcemaps)
            : globals.artifacts.getArtifactPath(Artifact.webPrecompiledSoundSdkSourcemaps));
        }
546
    }
547 548 549 550 551
    // This is the special generated entrypoint.
    if (path == 'web_entrypoint.dart') {
      return entrypointCacheDirectory.childFile('web_entrypoint.dart');
    }

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
    // If this is a dart file, it must be on the local file system and is
    // likely coming from a source map request. The tool doesn't currently
    // consider the case of Dart files as assets.
    final File dartFile = globals.fs.file(globals.fs.currentDirectory.uri.resolve(path));
    if (dartFile.existsSync()) {
      return dartFile;
    }

    final List<String> segments = path.split('/');
    if (segments.first.isEmpty) {
      segments.removeAt(0);
    }

    // The file might have been a package file which is signaled by a
    // `/packages/<package>/<path>` request.
    if (segments.first == 'packages') {
568 569 570 571 572 573 574
      final Uri filePath = _packages.resolve(Uri(
        scheme: 'package', pathSegments: segments.skip(1)));
      if (filePath != null) {
        final File packageFile = globals.fs.file(filePath);
        if (packageFile.existsSync()) {
          return packageFile;
        }
575 576 577 578 579 580 581
      }
    }

    // Otherwise it must be a Dart SDK source or a Flutter Web SDK source.
    final Directory dartSdkParent = globals.fs
      .directory(globals.artifacts.getArtifactPath(Artifact.engineDartSdkPath))
      .parent;
582
    final File dartSdkFile = globals.fs.file(dartSdkParent.uri.resolve(path));
583 584 585 586
    if (dartSdkFile.existsSync()) {
      return dartSdkFile;
    }

587 588 589
    final Directory flutterWebSdk = globals.fs.directory(globals.artifacts
      .getArtifactPath(Artifact.flutterWebSdk));
    final File webSdkFile = globals.fs.file(flutterWebSdk.uri.resolve(path));
590 591 592 593 594

    return webSdkFile;
  }

  @override
595
  Future<String> dartSourceContents(String serverPath) async {
596 597 598 599 600 601 602 603 604 605 606
    final File result = _resolveDartFile(serverPath);
    if (result.existsSync()) {
      return result.readAsString();
    }
    return null;
  }

  @override
  Future<String> sourceMapContents(String serverPath) async {
    return utf8.decode(_sourcemaps[serverPath]);
  }
607 608

  @override
609 610 611 612 613 614 615
  Future<String> metadataContents(String serverPath) async {
    if (serverPath == 'main_module.ddc_merged_metadata') {
      return _mergedMetadata;
    }
    if (_metadataFiles.containsKey(serverPath)) {
      return utf8.decode(_metadataFiles[serverPath]);
    }
616 617
    return null;
  }
618 619 620 621 622 623 624
}

class ConnectionResult {
  ConnectionResult(this.appConnection, this.debugConnection);

  final AppConnection appConnection;
  final DebugConnection debugConnection;
625
}
626

627
/// The web specific DevFS implementation.
628
class WebDevFS implements DevFS {
629 630 631 632
  /// Create a new [WebDevFS] instance.
  ///
  /// [testMode] is true, do not actually initialize dwds or the shelf static
  /// server.
633 634 635 636 637
  WebDevFS({
    @required this.hostname,
    @required this.port,
    @required this.packagesFilePath,
    @required this.urlTunneller,
638
    @required this.useSseForDebugProxy,
639
    @required this.useSseForDebugBackend,
640
    @required this.buildInfo,
641
    @required this.enableDwds,
642
    @required this.entrypoint,
643
    @required this.expressionCompiler,
644
    @required this.chromiumLauncher,
645
    @required this.nullAssertions,
646
    this.testMode = false,
647
  });
648

649
  final Uri entrypoint;
650 651
  final String hostname;
  final int port;
652 653
  final String packagesFilePath;
  final UrlTunneller urlTunneller;
654
  final bool useSseForDebugProxy;
655
  final bool useSseForDebugBackend;
656
  final BuildInfo buildInfo;
657
  final bool enableDwds;
658
  final bool testMode;
659
  final ExpressionCompiler expressionCompiler;
660
  final ChromiumLauncher chromiumLauncher;
661
  final bool nullAssertions;
662 663

  WebAssetServer webAssetServer;
664

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
  Dwds get dwds => webAssetServer.dwds;

  Future<DebugConnection> _cachedExtensionFuture;
  StreamSubscription<void> _connectedApps;

  /// Connect and retrieve the [DebugConnection] for the current application.
  ///
  /// Only calls [AppConnection.runMain] on the subsequent connections.
  Future<ConnectionResult> connect(bool useDebugExtension) {
    final Completer<ConnectionResult> firstConnection = Completer<ConnectionResult>();
    _connectedApps = dwds.connectedApps.listen((AppConnection appConnection) async {
      try {
        final DebugConnection debugConnection = useDebugExtension
          ? await (_cachedExtensionFuture ??= dwds.extensionDebugConnections.stream.first)
          : await dwds.debugConnection(appConnection);
        if (firstConnection.isCompleted) {
          appConnection.runMain();
        } else {
          firstConnection.complete(ConnectionResult(appConnection, debugConnection));
        }
      } on Exception catch (error, stackTrace) {
        if (!firstConnection.isCompleted) {
          firstConnection.completeError(error, stackTrace);
        }
      }
    }, onError: (dynamic error, StackTrace stackTrace) {
      globals.printError('Unknown error while waiting for debug connection:$error\n$stackTrace');
      if (!firstConnection.isCompleted) {
        firstConnection.completeError(error, stackTrace);
      }
    });
    return firstConnection.future;
  }

699 700 701 702 703 704
  @override
  List<Uri> sources = <Uri>[];

  @override
  DateTime lastCompiled;

705 706 707
  @override
  PackageConfig lastPackageConfig;

708 709 710 711 712
  // We do not evict assets on the web.
  @override
  Set<String> get assetPathsToEvict => const <String>{};

  @override
713 714
  Uri get baseUri => _baseUri;
  Uri _baseUri;
715 716 717

  @override
  Future<Uri> create() async {
718
    webAssetServer = await WebAssetServer.start(
719
      chromiumLauncher,
720 721 722
      hostname,
      port,
      urlTunneller,
723
      useSseForDebugProxy,
724
      useSseForDebugBackend,
725
      buildInfo,
726
      enableDwds,
727
      entrypoint,
728
      expressionCompiler,
729
      testMode: testMode,
730
    );
731 732 733
    if (buildInfo.dartDefines.contains('FLUTTER_WEB_USE_SKIA=true')) {
      webAssetServer.canvasKitRendering = true;
    }
734 735 736 737 738
    if (hostname == 'any') {
      _baseUri = Uri.http('localhost:$port', '');
    } else {
      _baseUri = Uri.http('$hostname:$port', '');
    }
739
    return _baseUri;
740 741 742 743
  }

  @override
  Future<void> destroy() async {
744
    await webAssetServer.dispose();
745
    await _connectedApps?.cancel();
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
  }

  @override
  Uri deviceUriToHostUri(Uri deviceUri) {
    return deviceUri;
  }

  @override
  String get fsName => 'web_asset';

  @override
  Directory get rootDirectory => null;

  @override
  Future<UpdateFSReport> update({
761
    Uri mainUri,
762 763 764 765 766 767 768 769 770 771 772
    String target,
    AssetBundle bundle,
    DateTime firstBuildTime,
    bool bundleFirstUpload = false,
    @required ResidentCompiler generator,
    String dillOutputPath,
    @required bool trackWidgetCreation,
    bool fullRestart = false,
    String projectRootPath,
    String pathToReload,
    List<Uri> invalidatedFiles,
773
    bool skipAssets = false,
774
    @required PackageConfig packageConfig,
775 776 777
  }) async {
    assert(trackWidgetCreation != null);
    assert(generator != null);
778 779 780
    lastPackageConfig = packageConfig;
    final File mainFile = globals.fs.file(mainUri);
    final String outputDirectoryPath = mainFile.parent.path;
781

782
    if (bundleFirstUpload) {
783
      webAssetServer.entrypointCacheDirectory = globals.fs.directory(outputDirectoryPath);
784
      generator.addFileSystemRoot(outputDirectoryPath);
785 786 787 788
      final String entrypoint = globals.fs.path.basename(mainFile.path);
      webAssetServer.writeBytes(entrypoint, mainFile.readAsBytesSync());
      webAssetServer.writeBytes('require.js', requireJS.readAsBytesSync());
      webAssetServer.writeBytes('stack_trace_mapper.js', stackTraceMapper.readAsBytesSync());
789 790
      webAssetServer.writeFile('manifest.json', '{"info":"manifest not generated in run mode."}');
      webAssetServer.writeFile('flutter_service_worker.js', '// Service worker not loaded in run mode.');
791
      webAssetServer.writeFile(
792
        'main.dart.js',
793
        generateBootstrapScript(
794 795
          requireUrl: 'require.js',
          mapperUrl: 'stack_trace_mapper.js',
796 797
        ),
      );
798
      webAssetServer.writeFile(
799
        'main_module.bootstrap.js',
800
        generateMainModule(
801
          entrypoint: entrypoint,
802
          nullAssertions: nullAssertions,
803 804
        ),
      );
805 806
      // TODO(jonahwilliams): refactor the asset code in this and the regular devfs to
      // be shared.
807 808
      if (bundle != null) {
        await writeBundle(
809 810 811
          globals.fs.directory(getAssetBuildDirectory()),
          bundle.entries,
        );
812
      }
813 814 815 816 817
    }
    final DateTime candidateCompileTime = DateTime.now();
    if (fullRestart) {
      generator.reset();
    }
818 819 820 821 822

    // The tool generates an entrypoint file in a temp directory to handle
    // the web specific bootrstrap logic. To make it easier for DWDS to handle
    // mapping the file name, this is done via an additional file root and
    // specicial hard-coded scheme.
823
    final CompilerOutput compilerOutput = await generator.recompile(
824 825 826 827
      Uri(
        scheme: 'org-dartlang-app',
        path: '/' + mainUri.pathSegments.last,
      ),
828
      invalidatedFiles,
829
      outputPath: dillOutputPath ??
830
        getDefaultApplicationKernelPath(trackWidgetCreation: trackWidgetCreation),
831
      packageConfig: packageConfig,
832 833 834 835
    );
    if (compilerOutput == null || compilerOutput.errorCount > 0) {
      return UpdateFSReport(success: false);
    }
836

837 838 839 840 841 842 843
    // Only update the last compiled time if we successfully compiled.
    lastCompiled = candidateCompileTime;
    // list of sources that needs to be monitored are in [compilerOutput.sources]
    sources = compilerOutput.sources;
    File codeFile;
    File manifestFile;
    File sourcemapFile;
844
    File metadataFile;
845 846
    List<String> modules;
    try {
847 848 849 850
      final Directory parentDirectory = globals.fs.directory(outputDirectoryPath);
      codeFile = parentDirectory.childFile('${compilerOutput.outputFilename}.sources');
      manifestFile = parentDirectory.childFile('${compilerOutput.outputFilename}.json');
      sourcemapFile = parentDirectory.childFile('${compilerOutput.outputFilename}.map');
851 852
      metadataFile = parentDirectory.childFile('${compilerOutput.outputFilename}.metadata');
      modules = webAssetServer.write(codeFile, manifestFile, sourcemapFile, metadataFile);
853 854 855
    } on FileSystemException catch (err) {
      throwToolExit('Failed to load recompiled sources:\n$err');
    }
856
    webAssetServer.performRestart(modules);
857
    return UpdateFSReport(
858 859 860
      success: true,
      syncedBytes: codeFile.lengthSync(),
      invalidatedSourcesCount: invalidatedFiles.length,
861
    );
862
  }
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881

  @visibleForTesting
  final File requireJS = globals.fs.file(globals.fs.path.join(
    globals.artifacts.getArtifactPath(Artifact.engineDartSdkPath),
    'lib',
    'dev_compiler',
    'kernel',
    'amd',
    'require.js',
  ));

  @visibleForTesting
  final File stackTraceMapper = globals.fs.file(globals.fs.path.join(
    globals.artifacts.getArtifactPath(Artifact.engineDartSdkPath),
    'lib',
    'dev_compiler',
    'web',
    'dart_stack_trace_mapper.js',
  ));
882 883
}

884
class ReleaseAssetServer {
885 886 887 888 889 890 891 892 893 894
  ReleaseAssetServer(this.entrypoint, {
    @required FileSystem fileSystem,
    @required String webBuildDirectory,
    @required String flutterRoot,
    @required Platform platform,
  }) : _fileSystem = fileSystem,
       _platform = platform,
       _flutterRoot = flutterRoot,
       _webBuildDirectory = webBuildDirectory,
       _fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform);
895 896

  final Uri entrypoint;
897 898 899 900 901
  final String _flutterRoot;
  final String _webBuildDirectory;
  final FileSystem _fileSystem;
  final FileSystemUtils _fileSystemUtils;
  final Platform _platform;
902

903
  // Locations where source files, assets, or source maps may be located.
904 905 906 907 908 909
  List<Uri> _searchPaths() => <Uri>[
    _fileSystem.directory(_webBuildDirectory).uri,
    _fileSystem.directory(_flutterRoot).uri,
    _fileSystem.directory(_flutterRoot).parent.uri,
    _fileSystem.currentDirectory.uri,
    _fileSystem.directory(_fileSystemUtils.homeDirPath).uri,
910 911 912 913
  ];

  Future<shelf.Response> handle(shelf.Request request) async {
    Uri fileUri;
914 915 916
    if (request.url.toString() == 'main.dart') {
      fileUri = entrypoint;
    } else {
917
      for (final Uri uri in _searchPaths()) {
918
        final Uri potential = uri.resolve(request.url.path);
919 920
        if (potential == null || !_fileSystem.isFileSync(
          potential.toFilePath(windows: _platform.isWindows))) {
921 922 923 924
          continue;
        }
        fileUri = potential;
        break;
925 926 927
      }
    }
    if (fileUri != null) {
928
      final File file = _fileSystem.file(fileUri);
929 930 931 932 933 934 935 936 937 938
      final Uint8List bytes = file.readAsBytesSync();
      // Fallback to "application/octet-stream" on null which
      // makes no claims as to the structure of the data.
      final String mimeType = mime.lookupMimeType(file.path, headerBytes: bytes)
        ?? 'application/octet-stream';
      return shelf.Response.ok(bytes, headers: <String, String>{
        'Content-Type': mimeType,
      });
    }
    if (request.url.path == '') {
939
      final File file = _fileSystem.file(_fileSystem.path.join(_webBuildDirectory, 'index.html'));
940 941 942 943 944 945 946
      return shelf.Response.ok(file.readAsBytesSync(), headers: <String, String>{
        'Content-Type': 'text/html',
      });
    }
    return shelf.Response.notFound('');
  }
}