web.dart 22.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 6
// @dart = 2.8

7 8
import 'dart:math';

9
import 'package:crypto/crypto.dart';
10
import 'package:meta/meta.dart';
11
import 'package:package_config/package_config.dart';
12

13 14 15 16
import '../../artifacts.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../build_info.dart';
17
import '../../cache.dart';
18
import '../../dart/language_version.dart';
19
import '../../dart/package_map.dart';
20
import '../../globals_null_migrated.dart' as globals;
21
import '../../project.dart';
22
import '../build_system.dart';
23
import '../depfile.dart';
24
import 'assets.dart';
25
import 'localizations.dart';
26 27 28 29 30 31 32 33 34

/// 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';

35 36 37
/// Whether to disable dynamic generation code to satisfy csp policies.
const String kCspMode = 'cspMode';

38 39 40 41 42 43
/// Base href to set in index.html in flutter build command
const String kBaseHref = 'baseHref';

/// Placeholder for base href
const String kBaseHrefPlaceholder = r'$FLUTTER_BASE_HREF';

44
/// The caching strategy to use for service worker generation.
45
const String kServiceWorkerStrategy = 'ServiceWorkerStrategy';
46

47 48 49
/// Whether the dart2js build should output source maps.
const String kSourceMapsEnabled = 'SourceMaps';

50 51 52
/// Whether the dart2js native null assertions are enabled.
const String kNativeNullAssertions = 'NativeNullAssertions';

53 54 55 56 57 58 59 60 61 62 63 64 65
/// The caching strategy for the generated service worker.
enum ServiceWorkerStrategy {
  /// Download the app shell eagerly and all other assets lazily.
  /// Prefer the offline cached version.
  offlineFirst,
  /// Do not generate a service worker,
  none,
}

const String kOfflineFirst = 'offline-first';
const String kNoneWorker = 'none';

/// Convert a [value] into a [ServiceWorkerStrategy].
66
ServiceWorkerStrategy _serviceWorkerStrategyFromString(String value) {
67 68 69 70 71 72 73 74 75
  switch (value) {
    case kNoneWorker:
      return ServiceWorkerStrategy.none;
    // offline-first is the default value for any invalid requests.
    default:
      return ServiceWorkerStrategy.offlineFirst;
  }
}

76
/// Generates an entry point for a web target.
Dan Field's avatar
Dan Field committed
77
// Keep this in sync with build_runner/resident_web_runner.dart
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
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 hasPlugins = environment.defines[kHasWebPlugins] == 'true';
101
    final Uri importUri = environment.fileSystem.file(targetFile).absolute.uri;
102 103
    // TODO(jonahwilliams): support configuration of this file.
    const String packageFile = '.packages';
104
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(
105
      environment.fileSystem.file(packageFile),
106
      logger: environment.logger,
107
    );
108
    final FlutterProject flutterProject = FlutterProject.current();
109
    final LanguageVersion languageVersion = determineLanguageVersion(
110 111
      environment.fileSystem.file(targetFile),
      packageConfig[flutterProject.manifest.appName],
112
      Cache.flutterRoot,
113
    );
114

115
    // Use the PackageConfig to find the correct package-scheme import path
116 117 118 119 120 121
    // 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
122 123
    // have an entry for the user's application or if the main file is
    // outside of the lib/ directory.
124 125
    final String mainImport = packageConfig.toPackageUri(importUri)?.toString()
      ?? importUri.toString();
126 127 128

    String contents;
    if (hasPlugins) {
129
      final Uri generatedUri = environment.projectDir
130 131
        .childDirectory('lib')
        .childFile('generated_plugin_registrant.dart')
132 133 134 135
        .absolute
        .uri;
      final String generatedImport = packageConfig.toPackageUri(generatedUri)?.toString()
        ?? generatedUri.toString();
136
      contents = '''
137
// @dart=${languageVersion.major}.${languageVersion.minor}
138

139 140 141 142
import 'dart:ui' as ui;

import 'package:flutter_web_plugins/flutter_web_plugins.dart';

143 144
import '$generatedImport';
import '$mainImport' as entrypoint;
145 146

Future<void> main() async {
147
  registerPlugins(webPluginRegistrar);
148
  await ui.webOnlyInitializePlatform();
149 150 151 152 153
  entrypoint.main();
}
''';
    } else {
      contents = '''
154
// @dart=${languageVersion.major}.${languageVersion.minor}
155

156 157
import 'dart:ui' as ui;

158
import '$mainImport' as entrypoint;
159 160

Future<void> main() async {
161
  await ui.webOnlyInitializePlatform();
162 163 164 165 166
  entrypoint.main();
}
''';
    }
    environment.buildDir.childFile('main.dart')
167
      .writeAsStringSync(contents);
168 169 170
  }
}

171
/// Compiles a web entry point with dart2js.
172 173 174 175 176 177 178 179
class Dart2JSTarget extends Target {
  const Dart2JSTarget();

  @override
  String get name => 'dart2js';

  @override
  List<Target> get dependencies => const <Target>[
180 181
    WebEntrypointTarget(),
    GenerateLocalizationsTarget(),
182 183 184 185
  ];

  @override
  List<Source> get inputs => const <Source>[
186 187 188
    Source.hostArtifact(HostArtifact.flutterWebSdk),
    Source.hostArtifact(HostArtifact.dart2jsSnapshot),
    Source.hostArtifact(HostArtifact.engineDartBinary),
189
    Source.pattern('{BUILD_DIR}/main.dart'),
190
    Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'),
191 192 193
  ];

  @override
194 195 196 197 198
  List<Source> get outputs => const <Source>[];

  @override
  List<String> get depfiles => const <String>[
    'dart2js.d',
199 200 201 202 203
  ];

  @override
  Future<void> build(Environment environment) async {
    final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
204
    final bool sourceMapsEnabled = environment.defines[kSourceMapsEnabled] == 'true';
205
    final bool nativeNullAssertions = environment.defines[kNativeNullAssertions] == 'true';
206
    final String librariesSpec = (globals.artifacts.getHostArtifact(HostArtifact.flutterWebSdk) as Directory).childFile('libraries.json').path;
207
    final List<String> sharedCommandOptions = <String>[
208
      globals.artifacts.getHostArtifact(HostArtifact.engineDartBinary).path,
209
      '--disable-dart-dev',
210 211
      globals.artifacts.getHostArtifact(HostArtifact.dart2jsSnapshot).path,
      '--libraries-spec=$librariesSpec',
212
      ...?decodeCommaSeparated(environment.defines, kExtraFrontEndOptions),
213 214
      if (nativeNullAssertions)
        '--native-null-assertions',
215 216 217 218
      if (buildMode == BuildMode.profile)
        '-Ddart.vm.profile=true'
      else
        '-Ddart.vm.product=true',
219
      for (final String dartDefine in decodeDartDefines(environment.defines, kDartDefines))
220
        '-D$dartDefine',
221 222
      if (!sourceMapsEnabled)
        '--no-source-maps',
223 224 225 226 227 228 229 230 231
    ];

    // 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>[
      ...sharedCommandOptions,
      '-o',
      environment.buildDir.childFile('app.dill').path,
      '--packages=.packages',
232
      '--cfe-only',
233
      environment.buildDir.childFile('main.dart').path, // dartfile
234 235 236 237
    ]);
    if (kernelResult.exitCode != 0) {
      throw Exception(kernelResult.stdout + kernelResult.stderr);
    }
238 239 240 241 242

    final String dart2jsOptimization = environment.defines[kDart2jsOptimization];
    final File outputJSFile = environment.buildDir.childFile('main.dart.js');
    final bool csp = environment.defines[kCspMode] == 'true';

243
    final ProcessResult javaScriptResult = await environment.processManager.run(<String>[
244 245 246 247
      ...sharedCommandOptions,
      if (dart2jsOptimization != null) '-$dart2jsOptimization' else '-O4',
      if (buildMode == BuildMode.profile) '--no-minify',
      if (csp) '--csp',
248
      '-o',
249 250
      outputJSFile.path,
      environment.buildDir.childFile('app.dill').path, // dartfile
251
    ]);
252 253
    if (javaScriptResult.exitCode != 0) {
      throw Exception(javaScriptResult.stdout + javaScriptResult.stderr);
254
    }
255
    final File dart2jsDeps = environment.buildDir
256
      .childFile('app.dill.deps');
257
    if (!dart2jsDeps.existsSync()) {
258
      globals.printError('Warning: dart2js did not produced expected deps list at '
259 260 261
        '${dart2jsDeps.path}');
      return;
    }
262 263 264 265 266
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    final Depfile depfile = depfileService.parseDart2js(
267
      environment.buildDir.childFile('app.dill.deps'),
268
      outputJSFile,
269
    );
270 271 272 273
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('dart2js.d'),
    );
274 275 276
  }
}

277
/// Unpacks the dart2js compilation and resources to a given output directory.
278 279 280 281 282 283 284 285 286 287 288 289 290 291
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'),
292
    Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
293 294 295 296 297
  ];

  @override
  List<Source> get outputs => const <Source>[
    Source.pattern('{OUTPUT_DIR}/main.dart.js'),
298 299 300 301 302
  ];

  @override
  List<String> get depfiles => const <String>[
    'dart2js.d',
303 304
    'flutter_assets.d',
    'web_resources.d',
305 306 307 308
  ];

  @override
  Future<void> build(Environment environment) async {
309
    for (final File outputFile in environment.buildDir.listSync(recursive: true).whereType<File>()) {
310 311 312 313 314 315
      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')) {
316 317 318
        continue;
      }
      outputFile.copySync(
319
        environment.outputDir.childFile(globals.fs.path.basename(outputFile.path)).path
320 321
      );
    }
322 323 324 325 326

    final String versionInfo = FlutterProject.current().getVersionInfo();
    environment.outputDir
        .childFile('version.json')
        .writeAsStringSync(versionInfo);
327 328
    final Directory outputDirectory = environment.outputDir.childDirectory('assets');
    outputDirectory.createSync(recursive: true);
329 330 331 332 333
    final Depfile depfile = await copyAssets(
      environment,
      environment.outputDir.childDirectory('assets'),
      targetPlatform: TargetPlatform.web_javascript,
    );
334 335 336 337 338 339 340 341
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('flutter_assets.d'),
    );
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

    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);
      }
      outputResourcesFiles.add(outputFile);
360 361 362
      // insert a random hash into the requests for service_worker.js. This is not a content hash,
      // because it would need to be the hash for the entire bundle and not just the resource
      // in question.
363 364
      if (environment.fileSystem.path.basename(inputFile.path) == 'index.html') {
        final String randomHash = Random().nextInt(4294967296).toString();
365
        String resultString = inputFile.readAsStringSync()
366 367 368 369 370 371
          .replaceFirst(
            'var serviceWorkerVersion = null',
            "var serviceWorkerVersion = '$randomHash'",
          )
          // This is for legacy index.html that still use the old service
          // worker loading mechanism.
372 373 374 375
          .replaceFirst(
            "navigator.serviceWorker.register('flutter_service_worker.js')",
            "navigator.serviceWorker.register('flutter_service_worker.js?v=$randomHash')",
          );
376 377 378 379 380 381 382
        if (resultString.contains(kBaseHrefPlaceholder) &&
            environment.defines[kBaseHref] == null) {
          resultString = resultString.replaceAll(kBaseHrefPlaceholder, '/');
        } else if (resultString.contains(kBaseHrefPlaceholder) &&
            environment.defines[kBaseHref] != null) {
          resultString = resultString.replaceAll(kBaseHrefPlaceholder, environment.defines[kBaseHref]);
        }
383 384 385 386
        outputFile.writeAsStringSync(resultString);
        continue;
      }
      inputFile.copySync(outputFile.path);
387 388
    }
    final Depfile resourceFile = Depfile(inputResourceFiles, outputResourcesFiles);
389 390 391 392
    depfileService.writeToFile(
      resourceFile,
      environment.buildDir.childFile('web_resources.d'),
    );
393 394
  }
}
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

/// 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();
428 429 430 431

    final Map<String, String> urlToHash = <String, String>{};
    for (final File file in contents) {
      // Do not force caching of source maps.
432 433
      if (file.path.endsWith('main.dart.js.map') ||
        file.path.endsWith('.part.js.map')) {
434 435 436 437 438 439 440 441 442
        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;
443 444 445 446
      // Add an additional entry for the base URL.
      if (globals.fs.path.basename(url) == 'index.html') {
        urlToHash['/'] = hash;
      }
447 448
    }

449 450 451
    final File serviceWorkerFile = environment.outputDir
      .childFile('flutter_service_worker.js');
    final Depfile depfile = Depfile(contents, <File>[serviceWorkerFile]);
452
    final ServiceWorkerStrategy serviceWorkerStrategy = _serviceWorkerStrategyFromString(
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
      environment.defines[kServiceWorkerStrategy],
    );
    final String serviceWorker = generateServiceWorker(
      urlToHash,
      <String>[
        '/',
        'main.dart.js',
        'index.html',
        'assets/NOTICES',
        if (urlToHash.containsKey('assets/AssetManifest.json'))
          'assets/AssetManifest.json',
        if (urlToHash.containsKey('assets/FontManifest.json'))
          'assets/FontManifest.json',
      ],
      serviceWorkerStrategy: serviceWorkerStrategy,
    );
469 470
    serviceWorkerFile
      .writeAsStringSync(serviceWorker);
471 472 473 474 475 476 477 478
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    depfileService.writeToFile(
      depfile,
      environment.buildDir.childFile('service_worker.d'),
    );
479 480 481 482 483 484
  }
}

/// Generate a service worker with an app-specific cache name a map of
/// resource files.
///
485
/// The tool embeds file hashes directly into the worker so that the byte for byte
486 487
/// invalidation will automatically reactivate workers whenever a new
/// version is deployed.
488 489 490 491 492 493 494 495
String generateServiceWorker(
  Map<String, String> resources,
  List<String> coreBundle, {
  @required ServiceWorkerStrategy serviceWorkerStrategy,
}) {
  if (serviceWorkerStrategy == ServiceWorkerStrategy.none) {
    return '';
  }
496 497
  return '''
'use strict';
498 499
const MANIFEST = 'flutter-app-manifest';
const TEMP = 'flutter-temp-cache';
500 501 502 503 504
const CACHE_NAME = 'flutter-app-cache';
const RESOURCES = {
  ${resources.entries.map((MapEntry<String, String> entry) => '"${entry.key}": "${entry.value}"').join(",\n")}
};

505 506 507 508 509 510
// 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) => {
511
  self.skipWaiting();
512 513
  return event.waitUntil(
    caches.open(TEMP).then((cache) => {
514
      return cache.addAll(
515
        CORE.map((value) => new Request(value, {'cache': 'reload'})));
516 517 518 519
    })
  );
});

520 521 522 523 524 525 526 527 528 529 530 531 532
// 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);
533
        contentCache = await caches.open(CACHE_NAME);
534 535 536
        for (var request of await tempCache.keys()) {
          var response = await tempCache.match(request);
          await contentCache.put(request, response);
537
        }
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
        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) => {
580 581 582
  if (event.request.method !== 'GET') {
    return;
  }
583 584
  var origin = self.location.origin;
  var key = event.request.url.substring(origin.length + 1);
585
  // Redirect URLs to the index.html
586 587 588 589
  if (key.indexOf('?v=') != -1) {
    key = key.split('?v=')[0];
  }
  if (event.request.url == origin || event.request.url.startsWith(origin + '/#') || key == '') {
590 591
    key = '/';
  }
592 593
  // If the URL is not the RESOURCE list then return to signal that the
  // browser should take over.
594
  if (!RESOURCES[key]) {
595
    return;
596
  }
597 598 599 600
  // If the URL is the index.html, perform an online-first request.
  if (key == '/') {
    return onlineFirst(event);
  }
601 602 603 604
  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
605 606
        // lazily populate the cache.
        return response || fetch(event.request).then((response) => {
607 608 609
          cache.put(event.request, response.clone());
          return response;
        });
610
      })
611
    })
612 613
  );
});
614

615 616 617
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.
618
  if (event.data === 'skipWaiting') {
619
    self.skipWaiting();
620
    return;
621
  }
622
  if (event.data === 'downloadOffline') {
623
    downloadOffline();
624
    return;
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
  }
});

// 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;
  }
641
  for (var resourceKey of Object.keys(RESOURCES)) {
642
    if (!currentContent[resourceKey]) {
643
      resources.push(resourceKey);
644 645
    }
  }
646
  return contentCache.addAll(resources);
647
}
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

// Attempt to download the resource online before falling back to
// the offline cache.
function onlineFirst(event) {
  return event.respondWith(
    fetch(event.request).then((response) => {
      return caches.open(CACHE_NAME).then((cache) => {
        cache.put(event.request, response.clone());
        return response;
      });
    }).catch((error) => {
      return caches.open(CACHE_NAME).then((cache) => {
        return cache.match(event.request).then((response) => {
          if (response != null) {
            return response;
          }
          throw error;
        });
      });
    })
  );
}
670 671
''';
}