build_script.dart 19.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2019 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.

// ignore_for_file: implementation_imports
import 'dart:async';
import 'dart:convert'; // ignore: dart_convert_import
import 'dart:io'; // ignore: dart_io_import
import 'dart:isolate';

11 12
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/utilities.dart';
13
import 'package:analyzer/dart/ast/ast.dart';
14
import 'package:archive/archive.dart';
15 16 17 18 19 20 21
import 'package:build/build.dart';
import 'package:build_config/build_config.dart';
import 'package:build_modules/build_modules.dart';
import 'package:build_modules/builders.dart';
import 'package:build_modules/src/module_builder.dart';
import 'package:build_modules/src/platform.dart';
import 'package:build_modules/src/workers.dart';
22
import 'package:build_runner/build_runner.dart' as build_runner;
23 24 25 26 27 28 29
import 'package:build_runner_core/build_runner_core.dart' as core;
import 'package:build_test/builder.dart';
import 'package:build_test/src/debug_test_builder.dart';
import 'package:build_web_compilers/build_web_compilers.dart';
import 'package:build_web_compilers/builders.dart';
import 'package:build_web_compilers/src/dev_compiler_bootstrap.dart';
import 'package:crypto/crypto.dart';
30
import 'package:glob/glob.dart';
31 32 33 34 35 36 37 38 39 40 41 42
import 'package:path/path.dart' as path; // ignore: package_path_import
import 'package:scratch_space/scratch_space.dart';
import 'package:test_core/backend.dart';

const String ddcBootstrapExtension = '.dart.bootstrap.js';
const String jsEntrypointExtension = '.dart.js';
const String jsEntrypointSourceMapExtension = '.dart.js.map';
const String jsEntrypointArchiveExtension = '.dart.js.tar.gz';
const String digestsEntrypointExtension = '.digests';
const String jsModuleErrorsExtension = '.ddc.js.errors';
const String jsModuleExtension = '.ddc.js';
const String jsSourceMapExtension = '.ddc.js.map';
43 44
const String kReleaseFlag = 'release';
const String kProfileFlag = 'profile';
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
// A minimum set of libraries to skip checks for to keep the examples compiling
// until we make a decision on whether to support dart:io on the web.
// See https://github.com/dart-lang/sdk/issues/35969
// See https://github.com/flutter/flutter/issues/39998
const Set<String> skipPlatformCheckPackages = <String>{
  'flutter',
  'flutter_test',
  'flutter_driver',
  'flutter_goldens',
  'flutter_goldens_client',
  'flutter_gallery',
  'connectivity',
  'video_player',
};

61
final DartPlatform flutterWebPlatform = DartPlatform.register('flutter_web', <String>[
62 63 64 65 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 92 93 94 95 96 97 98 99 100 101 102
  'async',
  'collection',
  'convert',
  'core',
  'developer',
  'html',
  'html_common',
  'indexed_db',
  'js',
  'js_util',
  'math',
  'svg',
  'typed_data',
  'web_audio',
  'web_gl',
  'web_sql',
  '_internal',
  // Flutter web specific libraries.
  'ui',
  '_engine',
]);

/// The builders required to compile a Flutter application to the web.
final List<core.BuilderApplication> builders = <core.BuilderApplication>[
  core.apply(
    'flutter_tools:test_bootstrap',
    <BuilderFactory>[
      (BuilderOptions options) => const DebugTestBuilder(),
      (BuilderOptions options) => const FlutterWebTestBootstrapBuilder(),
    ],
    core.toRoot(),
    hideOutput: true,
    defaultGenerateFor: const InputSet(
      include: <String>[
        'test/**',
      ],
    ),
  ),
  core.apply(
    'flutter_tools:shell',
    <BuilderFactory>[
103 104
      (BuilderOptions options) {
        final bool hasPlugins = options.config['hasPlugins'] == true;
105 106 107 108 109
        final bool initializePlatform = options.config['initializePlatform'] == true;
        return FlutterWebShellBuilder(
          hasPlugins: hasPlugins,
          initializePlatform: initializePlatform,
        );
110
      },
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    ],
    core.toRoot(),
    hideOutput: true,
    defaultGenerateFor: const InputSet(
      include: <String>[
        'lib/**',
        'web/**',
      ],
    ),
  ),
  core.apply(
      'flutter_tools:module_library',
      <Builder Function(BuilderOptions)>[moduleLibraryBuilder],
      core.toAllPackages(),
      isOptional: true,
      hideOutput: true,
      appliesBuilders: <String>['flutter_tools:module_cleanup']),
  core.apply(
      'flutter_tools:ddc_modules',
      <Builder Function(BuilderOptions)>[
        (BuilderOptions options) => MetaModuleBuilder(flutterWebPlatform),
        (BuilderOptions options) => MetaModuleCleanBuilder(flutterWebPlatform),
        (BuilderOptions options) => ModuleBuilder(flutterWebPlatform),
      ],
      core.toNoneByDefault(),
      isOptional: true,
      hideOutput: true,
      appliesBuilders: <String>['flutter_tools:module_cleanup']),
  core.apply(
      'flutter_tools:ddc',
      <Builder Function(BuilderOptions)>[
        (BuilderOptions builderOptions) => KernelBuilder(
              platformSdk: builderOptions.config['flutterWebSdk'],
              summaryOnly: true,
              sdkKernelPath: path.join('kernel', 'flutter_ddc_sdk.dill'),
              outputExtension: ddcKernelExtension,
              platform: flutterWebPlatform,
148
              librariesPath: path.absolute(path.join(builderOptions.config['flutterWebSdk'], 'libraries.json')),
149
              kernelTargetName: 'ddc',
150
              useIncrementalCompiler: true,
151 152
            ),
        (BuilderOptions builderOptions) => DevCompilerBuilder(
153
              useIncrementalCompiler: true,
154 155
              platform: flutterWebPlatform,
              platformSdk: builderOptions.config['flutterWebSdk'],
156
              sdkKernelPath: path.url.join('kernel', 'flutter_ddc_sdk.dill'),
157
              librariesPath: path.absolute(path.join(builderOptions.config['flutterWebSdk'], 'libraries.json')),
158 159 160 161 162 163 164 165 166 167
            ),
      ],
      core.toAllPackages(),
      isOptional: true,
      hideOutput: true,
      appliesBuilders: <String>['flutter_tools:ddc_modules']),
  core.apply(
    'flutter_tools:entrypoint',
    <BuilderFactory>[
      (BuilderOptions options) => FlutterWebEntrypointBuilder(
168 169
          options.config[kReleaseFlag] ?? false,
          options.config[kProfileFlag] ?? false,
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
          options.config['flutterWebSdk'],
      ),
    ],
    core.toRoot(),
    hideOutput: true,
    defaultGenerateFor: const InputSet(
      include: <String>[
        'lib/**_web_entrypoint.dart',
      ],
    ),
  ),
  core.apply(
    'flutter_tools:test_entrypoint',
    <BuilderFactory>[
      (BuilderOptions options) => const FlutterWebTestEntrypointBuilder(),
    ],
    core.toRoot(),
    hideOutput: true,
    defaultGenerateFor: const InputSet(
      include: <String>[
        'test/**_test.dart.browser_test.dart',
      ],
    ),
  ),
  core.applyPostProcess('flutter_tools:module_cleanup', moduleCleanup,
195
      defaultGenerateFor: const InputSet()),
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
];

/// The entrypoint to this build script.
Future<void> main(List<String> args, [SendPort sendPort]) async {
  core.overrideGeneratedOutputDirectory('flutter_web');
  final int result = await build_runner.run(args, builders);
  sendPort?.send(result);
}

/// A ddc-only entrypoint builder that respects the Flutter target flag.
class FlutterWebTestEntrypointBuilder implements Builder {
  const FlutterWebTestEntrypointBuilder();

  @override
  Map<String, List<String>> get buildExtensions => const <String, List<String>>{
211 212 213 214 215 216 217 218
    '.dart': <String>[
      ddcBootstrapExtension,
      jsEntrypointExtension,
      jsEntrypointSourceMapExtension,
      jsEntrypointArchiveExtension,
      digestsEntrypointExtension,
    ],
  };
219 220 221 222

  @override
  Future<void> build(BuildStep buildStep) async {
    log.info('building for target ${buildStep.inputId.path}');
223 224
    await bootstrapDdc(buildStep, platform: flutterWebPlatform,
        skipPlatformCheckPackages: skipPlatformCheckPackages);
225 226 227 228 229
  }
}

/// A ddc-only entrypoint builder that respects the Flutter target flag.
class FlutterWebEntrypointBuilder implements Builder {
230
  const FlutterWebEntrypointBuilder(this.release, this.profile, this.flutterWebSdk);
231 232

  final bool release;
233
  final bool profile;
234 235 236 237
  final String flutterWebSdk;

  @override
  Map<String, List<String>> get buildExtensions => const <String, List<String>>{
238 239 240 241 242 243 244 245
    '.dart': <String>[
      ddcBootstrapExtension,
      jsEntrypointExtension,
      jsEntrypointSourceMapExtension,
      jsEntrypointArchiveExtension,
      digestsEntrypointExtension,
    ],
  };
246 247 248

  @override
  Future<void> build(BuildStep buildStep) async {
249 250
    if (release || profile) {
      await bootstrapDart2Js(buildStep, flutterWebSdk, profile);
251
    } else {
252 253
      await bootstrapDdc(buildStep, platform: flutterWebPlatform,
          skipPlatformCheckPackages: skipPlatformCheckPackages);
254 255 256 257 258 259 260 261 262 263 264 265
    }
  }
}

/// Bootstraps the test entrypoint.
class FlutterWebTestBootstrapBuilder implements Builder {
  const FlutterWebTestBootstrapBuilder();

  @override
  Map<String, List<String>> get buildExtensions => const <String, List<String>>{
    '_test.dart': <String>[
      '_test.dart.browser_test.dart',
266
    ],
267 268 269 270 271 272 273 274 275 276 277 278 279
  };

  @override
  Future<void> build(BuildStep buildStep) async {
    final AssetId id = buildStep.inputId;
    final String contents = await buildStep.readAsString(id);
    final String assetPath = id.pathSegments.first == 'lib'
        ? path.url.join('packages', id.package, id.path)
        : id.path;
    final Metadata metadata = parseMetadata(
        assetPath, contents, Runtime.builtIn.map((Runtime runtime) => runtime.name).toSet());

    if (metadata.testOn.evaluate(SuitePlatform(Runtime.chrome))) {
280
      await buildStep.writeAsString(id.addExtension('.browser_test.dart'), '''
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
import 'dart:ui' as ui;
import 'dart:html';
import 'dart:js';

import 'package:stream_channel/stream_channel.dart';
import 'package:test_api/src/backend/stack_trace_formatter.dart'; // ignore: implementation_imports
import 'package:test_api/src/util/stack_trace_mapper.dart'; // ignore: implementation_imports
import 'package:test_api/src/remote_listener.dart'; // ignore: implementation_imports
import 'package:test_api/src/suite_channel_manager.dart'; // ignore: implementation_imports

import "${path.url.basename(id.path)}" as test;

Future<void> main() async {
  // Extra initialization for flutter_web.
  // The following parameters are hard-coded in Flutter's test embedder. Since
  // we don't have an embedder yet this is the lowest-most layer we can put
  // this stuff in.
  await ui.webOnlyInitializeEngine();
  // TODO(flutterweb): remove need for dynamic cast.
  (ui.window as dynamic).debugOverrideDevicePixelRatio(3.0);
  (ui.window as dynamic).webOnlyDebugPhysicalSizeOverride = const ui.Size(2400, 1800);
  internalBootstrapBrowserTest(() => test.main);
}

void internalBootstrapBrowserTest(Function getMain()) {
  var channel =
      serializeSuite(getMain, hidePrints: false, beforeLoad: () async {
    var serialized =
        await suiteChannel("test.browser.mapper").stream.first as Map;
    if (serialized == null) return;
  });
  postMessageChannel().pipe(channel);
}
StreamChannel serializeSuite(Function getMain(),
        {bool hidePrints = true, Future beforeLoad()}) =>
    RemoteListener.start(getMain,
        hidePrints: hidePrints, beforeLoad: beforeLoad);

StreamChannel suiteChannel(String name) {
  var manager = SuiteChannelManager.current;
  if (manager == null) {
    throw StateError('suiteChannel() may only be called within a test worker.');
  }

  return manager.connectOut(name);
}

StreamChannel postMessageChannel() {
  var controller = StreamChannelController(sync: true);
  window.onMessage.firstWhere((message) {
    return message.origin == window.location.origin && message.data == "port";
  }).then((message) {
    var port = message.ports.first;
    var portSubscription = port.onMessage.listen((message) {
      controller.local.sink.add(message.data);
    });

    controller.local.stream.listen((data) {
      port.postMessage({"data": data});
    }, onDone: () {
      port.postMessage({"event": "done"});
      portSubscription.cancel();
    });
  });

  context['parent'].callMethod('postMessage', [
    JsObject.jsify({"href": window.location.href, "ready": true}),
    window.location.origin,
  ]);
  return controller.foreign;
}

void setStackTraceMapper(StackTraceMapper mapper) {
  var formatter = StackTraceFormatter.current;
  if (formatter == null) {
    throw StateError(
        'setStackTraceMapper() may only be called within a test worker.');
  }

  formatter.configure(mapper: mapper);
}
''');
    }
  }
}

/// A shell builder which generates the web specific entrypoint.
class FlutterWebShellBuilder implements Builder {
369
  const FlutterWebShellBuilder({this.hasPlugins = false, this.initializePlatform = true});
370 371

  final bool hasPlugins;
372

373 374 375
  /// Whether to call webOnlyInitializePlatform.
  final bool initializePlatform;

376 377 378 379 380 381 382 383
  @override
  Future<void> build(BuildStep buildStep) async {
    final AssetId dartEntrypointId = buildStep.inputId;
    final bool isAppEntrypoint = await _isAppEntryPoint(dartEntrypointId, buildStep);
    if (!isAppEntrypoint) {
      return;
    }
    final AssetId outputId = buildStep.inputId.changeExtension('_web_entrypoint.dart');
384 385
    if (hasPlugins) {
      await buildStep.writeAsString(outputId, '''
386
import 'dart:ui' as ui;
387 388 389 390

import 'package:flutter_web_plugins/flutter_web_plugins.dart';

import 'generated_plugin_registrant.dart';
391 392 393
import "${path.url.basename(buildStep.inputId.path)}" as entrypoint;

Future<void> main() async {
394
  registerPlugins(webPluginRegistry);
395 396 397
  if ($initializePlatform) {
    await ui.webOnlyInitializePlatform();
  }
398 399
  entrypoint.main();
}
400 401 402 403
''');
    } else {
      await buildStep.writeAsString(outputId, '''
import 'dart:ui' as ui;
404

405 406 407
import "${path.url.basename(buildStep.inputId.path)}" as entrypoint;

Future<void> main() async {
408 409 410
  if ($initializePlatform) {
    await ui.webOnlyInitializePlatform();
  }
411 412
  entrypoint.main();
}
413
''');
414
    }
415 416 417 418 419 420 421 422
  }

  @override
  Map<String, List<String>> get buildExtensions => const <String, List<String>>{
    '.dart': <String>['_web_entrypoint.dart'],
  };
}

423
Future<void> bootstrapDart2Js(BuildStep buildStep, String flutterWebSdk, bool profile) async {
424 425 426
  final AssetId dartEntrypointId = buildStep.inputId;
  final AssetId moduleId = dartEntrypointId.changeExtension(moduleExtension(flutterWebPlatform));
  final Module module = Module.fromJson(json.decode(await buildStep.readAsString(moduleId)));
427 428 429 430 431
  final List<Module> allDeps = await module.computeTransitiveDependencies(
    buildStep,
    throwIfUnsupported: true,
    skipPlatformCheckPackages: skipPlatformCheckPackages,
  )..add(module);
432 433 434 435
  final ScratchSpace scratchSpace = await buildStep.fetchResource(scratchSpaceResource);
  final Iterable<AssetId> allSrcs = allDeps.expand((Module module) => module.sources);
  await scratchSpace.ensureAssets(allSrcs, buildStep);

436
  final String packageFile = _createPackageFile(allSrcs, buildStep, scratchSpace);
437 438 439 440 441 442 443 444 445 446 447
  final String dartPath = dartEntrypointId.path.startsWith('lib/')
      ? 'package:${dartEntrypointId.package}/'
          '${dartEntrypointId.path.substring('lib/'.length)}'
      : dartEntrypointId.path;
  final String jsOutputPath =
      '${path.withoutExtension(dartPath.replaceFirst('package:', 'packages/'))}'
      '$jsEntrypointExtension';
  final String flutterWebSdkPath = flutterWebSdk;
  final String librariesPath = path.join(flutterWebSdkPath, 'libraries.json');
  final List<String> args = <String>[
    '--libraries-spec="$librariesPath"',
448 449 450 451
    if (profile)
      '-O1'
    else
      '-O4',
452 453 454
    '-o',
    '$jsOutputPath',
    '--packages="$packageFile"',
455 456 457 458
    if (profile)
      '-Ddart.vm.profile=true'
    else
      '-Ddart.vm.product=true',
459 460 461 462 463 464 465
    dartPath,
  ];
  final Dart2JsBatchWorkerPool dart2js = await buildStep.fetchResource(dart2JsWorkerResource);
  final Dart2JsResult result = await dart2js.compile(args);
  final AssetId jsOutputId = dartEntrypointId.changeExtension(jsEntrypointExtension);
  final File jsOutputFile = scratchSpace.fileFor(jsOutputId);
  if (result.succeeded && jsOutputFile.existsSync()) {
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
    final String rootDir = path.dirname(jsOutputFile.path);
    final String dartFile = path.basename(dartEntrypointId.path);
    final Glob fileGlob = Glob('$dartFile.js*');
    final Archive archive = Archive();
    await for (FileSystemEntity jsFile in fileGlob.list(root: rootDir)) {
      if (jsFile.path.endsWith(jsEntrypointExtension) ||
          jsFile.path.endsWith(jsEntrypointSourceMapExtension)) {
        // These are explicitly output, and are not part of the archive.
        continue;
      }
      if (jsFile is File) {
        final String fileName = path.relative(jsFile.path, from: rootDir);
        final FileStat fileStats = jsFile.statSync();
        archive.addFile(
            ArchiveFile(fileName, fileStats.size, await jsFile.readAsBytes())
              ..mode = fileStats.mode
              ..lastModTime = fileStats.modified.millisecondsSinceEpoch);
      }
    }
    if (archive.isNotEmpty) {
      final AssetId archiveId = dartEntrypointId.changeExtension(jsEntrypointArchiveExtension);
      await buildStep.writeAsBytes(archiveId, TarEncoder().encode(archive));
    }

    // Explicitly write out the original js file and sourcemap - we can't output
    // these as part of the archive because they already have asset nodes.
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
    await scratchSpace.copyOutput(jsOutputId, buildStep);
    final AssetId jsSourceMapId =
        dartEntrypointId.changeExtension(jsEntrypointSourceMapExtension);
    await _copyIfExists(jsSourceMapId, scratchSpace, buildStep);
  } else {
    log.severe(result.output);
  }
}

Future<void> _copyIfExists(
    AssetId id, ScratchSpace scratchSpace, AssetWriter writer) async {
  final File file = scratchSpace.fileFor(id);
  if (file.existsSync()) {
    await scratchSpace.copyOutput(id, writer);
  }
}

/// Creates a `.packages` file unique to this entrypoint at the root of the
/// scratch space and returns it's filename.
///
/// Since mulitple invocations of Dart2Js will share a scratch space and we only
/// know the set of packages involved the current entrypoint we can't construct
/// a `.packages` file that will work for all invocations of Dart2Js so a unique
/// file is created for every entrypoint that is run.
///
/// The filename is based off the MD5 hash of the asset path so that files are
/// unique regarless of situations like `web/foo/bar.dart` vs
/// `web/foo-bar.dart`.
520
String _createPackageFile(Iterable<AssetId> inputSources, BuildStep buildStep, ScratchSpace scratchSpace) {
521 522 523 524 525 526 527 528
  final Uri inputUri = buildStep.inputId.uri;
  final String packageFileName =
      '.package-${md5.convert(inputUri.toString().codeUnits)}';
  final File packagesFile =
      scratchSpace.fileFor(AssetId(buildStep.inputId.package, packageFileName));
  final Set<String> packageNames = inputSources.map((AssetId s) => s.package).toSet();
  final String packagesFileContent =
      packageNames.map((String name) => '$name:packages/$name/').join('\n');
529
  packagesFile .writeAsStringSync('# Generated for $inputUri\n$packagesFileContent');
530 531 532 533 534 535 536 537 538
  return packageFileName;
}

/// Returns whether or not [dartId] is an app entrypoint (basically, whether
/// or not it has a `main` function).
Future<bool> _isAppEntryPoint(AssetId dartId, AssetReader reader) async {
  assert(dartId.extension == '.dart');
  // Skip reporting errors here, dartdevc will report them later with nicer
  // formatting.
539 540 541 542
  final ParseStringResult result = parseString(
    content: await reader.readAsString(dartId),
    throwIfDiagnostics: false,
  );
543 544
  // Allow two or fewer arguments so that entrypoints intended for use with
  // [spawnUri] get counted.
545
  return result.unit.declarations.any((CompilationUnitMember node) {
546 547 548 549 550
    return node is FunctionDeclaration &&
        node.name.name == 'main' &&
        node.functionExpression.parameters.parameters.length <= 2;
  });
}