-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
1028 lines (848 loc) · 30.2 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
103
104
105
106
107
108
109
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
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
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
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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var __wpo = {
"assets": {
"main": [
"./embedEn.html",
"./iframeEn.html",
"./",
"./fonts/materialdesignicons-webfont.eot",
"./fonts/materialdesignicons-webfont.svg",
"./fonts/materialdesignicons-webfont.ttf",
"./fonts/materialdesignicons-webfont.woff2",
"./fonts/materialdesignicons-webfont.woff",
"./fonts/roboto/Roboto-Bold.woff",
"./fonts/roboto/Roboto-Bold.woff2",
"./fonts/roboto/Roboto-Light.woff",
"./fonts/roboto/Roboto-Light.woff2",
"./fonts/roboto/Roboto-Medium.woff",
"./fonts/roboto/Roboto-Medium.woff2",
"./fonts/roboto/Roboto-Regular.woff",
"./fonts/roboto/Roboto-Regular.woff2",
"./fonts/roboto/Roboto-Thin.woff",
"./fonts/roboto/Roboto-Thin.woff2",
"./img/guide.svg",
"./img/1.jpg",
"./img/10.jpg",
"./img/11.jpg",
"./img/12.jpg",
"./img/13.jpg",
"./img/14.jpg",
"./img/15.jpg",
"./img/16.jpg",
"./img/17.jpg",
"./img/18.jpg",
"./img/2.jpg",
"./img/3.jpg",
"./img/4.jpg",
"./img/5.jpg",
"./img/6.jpg",
"./img/7.jpg",
"./img/8.jpg",
"./img/9.jpg",
"./img/asterisk.svg",
"./img/birdwave.jpg",
"./img/kullabergsguiderna.png",
"./img/kullenDyk.gif",
"./img/kullensFyr.png",
"./img/lansstyrelsen.svg",
"./img/molleKajak.webp",
"./img/regionSkane.svg",
"./bundle.js",
"./android-chrome-192x192.png",
"./android-chrome-512x512.png",
"./favicon-32x32.png",
"./favicon-16x16.png",
"./js/materialize.min.js",
"./js/jquery-3.2.1.min.js",
"./manifest.json"
],
"additional": [],
"optional": []
},
"externals": [
"./android-chrome-192x192.png",
"./android-chrome-512x512.png",
"./favicon-32x32.png",
"./favicon-16x16.png",
"./js/materialize.min.js",
"./js/jquery-3.2.1.min.js",
"./manifest.json"
],
"hashesMap": {
"a0f5a976c5ea55ab598254f3e424c684e1dd77b8": "./embedEn.html",
"da85a7c325d8ff3771db387415f2dded4b084cc8": "./iframeEn.html",
"33f331a136f6ee27df1f7c4675d453b2e7c38aac": "./",
"02acf9a6077c6fd0ba37b5f16499365bf05eb7c9": "./fonts/materialdesignicons-webfont.eot",
"f70e244175be4f96a237a748577f28f39dd3c7cb": "./fonts/materialdesignicons-webfont.svg",
"0d237a357a6428d90612b24e71a74deb9a1b062a": "./fonts/materialdesignicons-webfont.ttf",
"ae356d6811285df99e5efa432a27a1ae2efb19b5": "./fonts/materialdesignicons-webfont.woff2",
"5b560e4a95f2e1efea1b4d2b39d9d545b012ca22": "./fonts/materialdesignicons-webfont.woff",
"e0655b6097eddf9df88cd194eff08436ea086a1c": "./fonts/roboto/Roboto-Bold.woff",
"5a8465896222227807ff29908d8648db510561a5": "./fonts/roboto/Roboto-Bold.woff2",
"c7494493f62984e2f581598739b5dd340e9e891b": "./fonts/roboto/Roboto-Light.woff",
"f6daab924b79b4822dc9faa56bbefe1d1efa3e42": "./fonts/roboto/Roboto-Light.woff2",
"b17bd60107c9ec0fd8c58a9e1fd222da7f1b99f4": "./fonts/roboto/Roboto-Medium.woff",
"7c512e2ebddd4dbd08d0f7bfb5b772501f707078": "./fonts/roboto/Roboto-Medium.woff2",
"6cfb2a5eb3a601ba450dda2d80bacef26c5ba873": "./fonts/roboto/Roboto-Regular.woff",
"c193deaa915e7183828400922700567900fb6cc3": "./fonts/roboto/Roboto-Regular.woff2",
"cb8f61464f349af887ba96f6a2ae1e318b3cc8d9": "./fonts/roboto/Roboto-Thin.woff",
"c321aeb611cf1dcb25717484a4ced717d8ca76fa": "./fonts/roboto/Roboto-Thin.woff2",
"5929c6ce2fe7d56d1c2ca1f279982196aba19bf1": "./img/guide.svg",
"1e7f5488350f04f0212c7c96093dca8e268e01e1": "./img/1.jpg",
"d582b697d35cd1ab5fbecfc722af2cec2c65710b": "./img/10.jpg",
"cc9446fe63008b64191f9c305e319f86056f6fd8": "./img/11.jpg",
"1fe57b595cc52e52635f13c6537ad6cf99009b54": "./img/12.jpg",
"b6367f5a4afac3f0b08d481f4285b2473a262710": "./img/13.jpg",
"b2cd50d35ffefa7111688b3ce006b1c259358383": "./img/14.jpg",
"242370988a400306364e1a6c1ab01a8ccc4a3310": "./img/15.jpg",
"911b63d0412cacb73a5c3fc1e4835c765865b723": "./img/16.jpg",
"aeff805eda505feb1818340eaabe3522d2ada0b0": "./img/17.jpg",
"aeabb0fc883c36cbc78cb4134993d0f9b6ac6ab7": "./img/18.jpg",
"bb425777acfdbb0f6a3345473a7c2676acdefa94": "./img/2.jpg",
"f0aff06579ef49635c4e434545bf7fbffb912465": "./img/3.jpg",
"2c67b7ffca46926abcf0963336d85c561aba768f": "./img/4.jpg",
"bbbbbcb6e3ea28494754159a15725242c0a3f5d8": "./img/5.jpg",
"16158d5520421386fc89b261a3dc4931a95d1478": "./img/6.jpg",
"794ccbc88da0b59a286b011f8d3d4c7e2072d935": "./img/7.jpg",
"8024fe733e753300d954a26cdadf5193a583ada3": "./img/8.jpg",
"31ded9b20f0a21c0ae134a43b37d6590e986ea6b": "./img/9.jpg",
"805db6e929e98fd3deb05cdb2935fc5a33183c15": "./img/asterisk.svg",
"c013ede0fd090edaffb8e7a42cf3c146edbd6b70": "./img/birdwave.jpg",
"e942e55767b32918dce7b853541dc008ef4776dc": "./img/kullabergsguiderna.png",
"98d6ecee7d853318bcdf7569b893f49e13e020e4": "./img/kullenDyk.gif",
"432302c2de75ea7550fd9b63407f1e7d0bf0cee6": "./img/kullensFyr.png",
"ff0a26a7386b54629869bca28f5d17161a824ce6": "./img/lansstyrelsen.svg",
"c0a372e40c1e38c5789ae01b7f2f74f3caf259ba": "./img/molleKajak.webp",
"270bc8ef11b4a50b2e22b347739c5e14f851c0ed": "./img/regionSkane.svg",
"5335918b7d2db17d02127c87e3e27be72f08fef7": "./bundle.js"
},
"strategy": "all",
"responseStrategy": "network-first",
"version": "2018-5-21 16:11:06",
"name": "webpack-offline",
"pluginVersion": "4.9.1",
"relativePaths": true
};
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
(function () {
var waitUntil = ExtendableEvent.prototype.waitUntil;
var respondWith = FetchEvent.prototype.respondWith;
var promisesMap = new WeakMap();
ExtendableEvent.prototype.waitUntil = function (promise) {
var extendableEvent = this;
var promises = promisesMap.get(extendableEvent);
if (promises) {
promises.push(Promise.resolve(promise));
return;
}
promises = [Promise.resolve(promise)];
promisesMap.set(extendableEvent, promises);
// call original method
return waitUntil.call(extendableEvent, Promise.resolve().then(function processPromises() {
var len = promises.length;
// wait for all to settle
return Promise.all(promises.map(function (p) {
return p["catch"](function () {});
})).then(function () {
// have new items been added? If so, wait again
if (promises.length != len) return processPromises();
// we're done!
promisesMap["delete"](extendableEvent);
// reject if one of the promises rejected
return Promise.all(promises);
});
}));
};
FetchEvent.prototype.respondWith = function (promise) {
this.waitUntil(promise);
return respondWith.call(this, promise);
};
})();;
'use strict';
if (typeof DEBUG === 'undefined') {
var DEBUG = false;
}
function WebpackServiceWorker(params, helpers) {
var loaders = helpers.loaders;
var cacheMaps = helpers.cacheMaps;
// navigationPreload: true, { map: (URL) => URL, test: (URL) => boolean }
var navigationPreload = helpers.navigationPreload;
// (update)strategy: changed, all
var strategy = params.strategy;
// responseStrategy: cache-first, network-first
var responseStrategy = params.responseStrategy;
var assets = params.assets;
var loadersMap = params.loaders || {};
var hashesMap = params.hashesMap;
var externals = params.externals;
var CACHE_PREFIX = params.name;
var CACHE_TAG = params.version;
var CACHE_NAME = CACHE_PREFIX + ':' + CACHE_TAG;
var PRELOAD_CACHE_NAME = CACHE_PREFIX + '$preload';
var STORED_DATA_KEY = '__offline_webpack__data';
mapAssets();
var allAssets = [].concat(assets.main, assets.additional, assets.optional);
// Deprecated {
var navigateFallbackURL = params.navigateFallbackURL;
var navigateFallbackForRedirects = params.navigateFallbackForRedirects;
// }
self.addEventListener('install', function (event) {
console.log('[SW]:', 'Install event');
var installing = undefined;
if (strategy === 'changed') {
installing = cacheChanged('main');
} else {
installing = cacheAssets('main');
}
event.waitUntil(installing);
});
self.addEventListener('activate', function (event) {
console.log('[SW]:', 'Activate event');
var activation = cacheAdditional();
// Delete all assets which name starts with CACHE_PREFIX and
// is not current cache (CACHE_NAME)
activation = activation.then(storeCacheData);
activation = activation.then(deleteObsolete);
activation = activation.then(function () {
if (self.clients && self.clients.claim) {
return self.clients.claim();
}
});
if (navigationPreload && self.registration.navigationPreload) {
activation = Promise.all([activation, self.registration.navigationPreload.enable()]);
}
event.waitUntil(activation);
});
function cacheAdditional() {
if (!assets.additional.length) {
return Promise.resolve();
}
if (DEBUG) {
console.log('[SW]:', 'Caching additional');
}
var operation = undefined;
if (strategy === 'changed') {
operation = cacheChanged('additional');
} else {
operation = cacheAssets('additional');
}
// Ignore fail of `additional` cache section
return operation['catch'](function (e) {
console.error('[SW]:', 'Cache section `additional` failed to load');
});
}
function cacheAssets(section) {
var batch = assets[section];
return caches.open(CACHE_NAME).then(function (cache) {
return addAllNormalized(cache, batch, {
bust: params.version,
request: params.prefetchRequest
});
}).then(function () {
logGroup('Cached assets: ' + section, batch);
})['catch'](function (e) {
console.error(e);
throw e;
});
}
function cacheChanged(section) {
return getLastCache().then(function (args) {
if (!args) {
return cacheAssets(section);
}
var lastCache = args[0];
var lastKeys = args[1];
var lastData = args[2];
var lastMap = lastData.hashmap;
var lastVersion = lastData.version;
if (!lastData.hashmap || lastVersion === params.version) {
return cacheAssets(section);
}
var lastHashedAssets = Object.keys(lastMap).map(function (hash) {
return lastMap[hash];
});
var lastUrls = lastKeys.map(function (req) {
var url = new URL(req.url);
url.search = '';
url.hash = '';
return url.toString();
});
var sectionAssets = assets[section];
var moved = [];
var changed = sectionAssets.filter(function (url) {
if (lastUrls.indexOf(url) === -1 || lastHashedAssets.indexOf(url) === -1) {
return true;
}
return false;
});
Object.keys(hashesMap).forEach(function (hash) {
var asset = hashesMap[hash];
// Return if not in sectionAssets or in changed or moved array
if (sectionAssets.indexOf(asset) === -1 || changed.indexOf(asset) !== -1 || moved.indexOf(asset) !== -1) return;
var lastAsset = lastMap[hash];
if (lastAsset && lastUrls.indexOf(lastAsset) !== -1) {
moved.push([lastAsset, asset]);
} else {
changed.push(asset);
}
});
logGroup('Changed assets: ' + section, changed);
logGroup('Moved assets: ' + section, moved);
var movedResponses = Promise.all(moved.map(function (pair) {
return lastCache.match(pair[0]).then(function (response) {
return [pair[1], response];
});
}));
return caches.open(CACHE_NAME).then(function (cache) {
var move = movedResponses.then(function (responses) {
return Promise.all(responses.map(function (pair) {
return cache.put(pair[0], pair[1]);
}));
});
return Promise.all([move, addAllNormalized(cache, changed, {
bust: params.version,
request: params.prefetchRequest
})]);
});
});
}
function deleteObsolete() {
return caches.keys().then(function (keys) {
var all = keys.map(function (key) {
if (key.indexOf(CACHE_PREFIX) !== 0 || key.indexOf(CACHE_NAME) === 0) return;
console.log('[SW]:', 'Delete cache:', key);
return caches['delete'](key);
});
return Promise.all(all);
});
}
function getLastCache() {
return caches.keys().then(function (keys) {
var index = keys.length;
var key = undefined;
while (index--) {
key = keys[index];
if (key.indexOf(CACHE_PREFIX) === 0) {
break;
}
}
if (!key) return;
var cache = undefined;
return caches.open(key).then(function (_cache) {
cache = _cache;
return _cache.match(new URL(STORED_DATA_KEY, location).toString());
}).then(function (response) {
if (!response) return;
return Promise.all([cache, cache.keys(), response.json()]);
});
});
}
function storeCacheData() {
return caches.open(CACHE_NAME).then(function (cache) {
var data = new Response(JSON.stringify({
version: params.version,
hashmap: hashesMap
}));
return cache.put(new URL(STORED_DATA_KEY, location).toString(), data);
});
}
self.addEventListener('fetch', function (event) {
var url = new URL(event.request.url);
url.hash = '';
var urlString = url.toString();
// Not external, so search part of the URL should be stripped,
// if it's external URL, the search part should be kept
if (externals.indexOf(urlString) === -1) {
url.search = '';
urlString = url.toString();
}
// Handle only GET requests
var isGET = event.request.method === 'GET';
var assetMatches = allAssets.indexOf(urlString) !== -1;
var cacheUrl = urlString;
if (!assetMatches) {
var cacheRewrite = matchCacheMap(event.request);
if (cacheRewrite) {
cacheUrl = cacheRewrite;
assetMatches = true;
}
}
if (!assetMatches && isGET) {
// If isn't a cached asset and is a navigation request,
// perform network request and fallback to navigateFallbackURL if available.
//
// Requesting with fetchWithPreload().
// Preload is used only if navigationPreload is enabled and
// navigationPreload mapping is not used.
if (navigateFallbackURL && isNavigateRequest(event.request)) {
event.respondWith(handleNavigateFallback(fetchWithPreload(event)));
return;
}
if (navigationPreload === true) {
event.respondWith(fetchWithPreload(event));
return;
}
// Something else, positive, but not `true`
if (navigationPreload) {
var preloadedResponse = retrivePreloadedResponse(event);
if (preloadedResponse) {
event.respondWith(preloadedResponse);
return;
}
}
// Logic exists here if no cache match, or no preload
return;
}
if (!assetMatches || !isGET) {
// Fix for https://twitter.com/wanderview/status/696819243262873600
if (url.origin !== location.origin && navigator.userAgent.indexOf('Firefox/44.') !== -1) {
event.respondWith(fetch(event.request));
}
// Logic exists here if no cache match
return;
}
// Cache handling/storing/fetching starts here
var resource = undefined;
if (responseStrategy === 'network-first') {
resource = networkFirstResponse(event, urlString, cacheUrl);
}
// 'cache-first' otherwise
// (responseStrategy has been validated before)
else {
resource = cacheFirstResponse(event, urlString, cacheUrl);
}
if (navigateFallbackURL && isNavigateRequest(event.request)) {
resource = handleNavigateFallback(resource);
}
event.respondWith(resource);
});
self.addEventListener('message', function (e) {
var data = e.data;
if (!data) return;
switch (data.action) {
case 'skipWaiting':
{
if (self.skipWaiting) self.skipWaiting();
}break;
}
});
function cacheFirstResponse(event, urlString, cacheUrl) {
handleNavigationPreload(event);
return cachesMatch(cacheUrl, CACHE_NAME).then(function (response) {
if (response) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + cacheUrl + '](' + urlString + ') from cache');
}
return response;
}
// Load and cache known assets
var fetching = fetch(event.request).then(function (response) {
if (!response.ok) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] wrong response: [' + response.status + '] ' + response.type);
}
return response;
}
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
if (cacheUrl === urlString) {
(function () {
var responseClone = response.clone();
var storing = caches.open(CACHE_NAME).then(function (cache) {
return cache.put(urlString, responseClone);
}).then(function () {
console.log('[SW]:', 'Cache asset: ' + urlString);
});
event.waitUntil(storing);
})();
}
return response;
});
return fetching;
});
}
function networkFirstResponse(event, urlString, cacheUrl) {
return fetchWithPreload(event).then(function (response) {
if (response.ok) {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from network');
}
return response;
}
// Throw to reach the code in the catch below
throw new Error('Response is not ok');
})
// This needs to be in a catch() and not just in the then() above
// cause if your network is down, the fetch() will throw
['catch'](function () {
if (DEBUG) {
console.log('[SW]:', 'URL [' + urlString + '] from cache if possible');
}
return cachesMatch(cacheUrl, CACHE_NAME);
});
}
function handleNavigationPreload(event) {
if (navigationPreload && typeof navigationPreload.map === 'function' &&
// Use request.mode === 'navigate' instead of isNavigateRequest
// because everything what supports navigationPreload supports
// 'navigate' request.mode
event.preloadResponse && event.request.mode === 'navigate') {
var mapped = navigationPreload.map(new URL(event.request.url), event.request);
if (mapped) {
storePreloadedResponse(mapped, event);
}
}
}
// Temporary in-memory store for faster access
var navigationPreloadStore = new Map();
function storePreloadedResponse(_url, event) {
var url = new URL(_url, location);
var preloadResponsePromise = event.preloadResponse;
navigationPreloadStore.set(preloadResponsePromise, {
url: url,
response: preloadResponsePromise
});
var isSamePreload = function isSamePreload() {
return navigationPreloadStore.has(preloadResponsePromise);
};
var storing = preloadResponsePromise.then(function (res) {
// Return if preload isn't enabled or hasn't happened
if (!res) return;
// If navigationPreloadStore already consumed
// or navigationPreloadStore already contains another preload,
// then do not store anything and return
if (!isSamePreload()) {
return;
}
var clone = res.clone();
// Storing the preload response for later consume (hasn't yet been consumed)
return caches.open(PRELOAD_CACHE_NAME).then(function (cache) {
if (!isSamePreload()) return;
return cache.put(url, clone).then(function () {
if (!isSamePreload()) {
return caches.open(PRELOAD_CACHE_NAME).then(function (cache) {
return cache['delete'](url);
});
}
});
});
});
event.waitUntil(storing);
}
function retriveInMemoryPreloadedResponse(url) {
if (!navigationPreloadStore) {
return;
}
var foundResponse = undefined;
var foundKey = undefined;
navigationPreloadStore.forEach(function (store, key) {
if (store.url.href === url.href) {
foundResponse = store.response;
foundKey = key;
}
});
if (foundResponse) {
navigationPreloadStore['delete'](foundKey);
return foundResponse;
}
}
function retrivePreloadedResponse(event) {
var url = new URL(event.request.url);
if (self.registration.navigationPreload && navigationPreload && navigationPreload.test && navigationPreload.test(url, event.request)) {} else {
return;
}
var fromMemory = retriveInMemoryPreloadedResponse(url);
var request = event.request;
if (fromMemory) {
event.waitUntil(caches.open(PRELOAD_CACHE_NAME).then(function (cache) {
return cache['delete'](request);
}));
return fromMemory;
}
return cachesMatch(request, PRELOAD_CACHE_NAME).then(function (response) {
if (response) {
event.waitUntil(caches.open(PRELOAD_CACHE_NAME).then(function (cache) {
return cache['delete'](request);
}));
}
return response || fetch(event.request);
});
}
function handleNavigateFallback(fetching) {
return fetching['catch'](function () {}).then(function (response) {
var isOk = response && response.ok;
var isRedirect = response && response.type === 'opaqueredirect';
if (isOk || isRedirect && !navigateFallbackForRedirects) {
return response;
}
if (DEBUG) {
console.log('[SW]:', 'Loading navigation fallback [' + navigateFallbackURL + '] from cache');
}
return cachesMatch(navigateFallbackURL, CACHE_NAME);
});
}
function mapAssets() {
Object.keys(assets).forEach(function (key) {
assets[key] = assets[key].map(function (path) {
var url = new URL(path, location);
url.hash = '';
if (externals.indexOf(path) === -1) {
url.search = '';
}
return url.toString();
});
});
Object.keys(loadersMap).forEach(function (key) {
loadersMap[key] = loadersMap[key].map(function (path) {
var url = new URL(path, location);
url.hash = '';
if (externals.indexOf(path) === -1) {
url.search = '';
}
return url.toString();
});
});
hashesMap = Object.keys(hashesMap).reduce(function (result, hash) {
var url = new URL(hashesMap[hash], location);
url.search = '';
url.hash = '';
result[hash] = url.toString();
return result;
}, {});
externals = externals.map(function (path) {
var url = new URL(path, location);
url.hash = '';
return url.toString();
});
}
function addAllNormalized(cache, requests, options) {
var allowLoaders = options.allowLoaders !== false;
var bustValue = options && options.bust;
var requestInit = options.request || {
credentials: 'omit',
mode: 'cors'
};
return Promise.all(requests.map(function (request) {
if (bustValue) {
request = applyCacheBust(request, bustValue);
}
return fetch(request, requestInit).then(fixRedirectedResponse);
})).then(function (responses) {
if (responses.some(function (response) {
return !response.ok;
})) {
return Promise.reject(new Error('Wrong response status'));
}
var extracted = [];
var addAll = responses.map(function (response, i) {
if (allowLoaders) {
extracted.push(extractAssetsWithLoaders(requests[i], response));
}
return cache.put(requests[i], response);
});
if (extracted.length) {
(function () {
var newOptions = copyObject(options);
newOptions.allowLoaders = false;
var waitAll = addAll;
addAll = Promise.all(extracted).then(function (all) {
var extractedRequests = [].concat.apply([], all);
if (requests.length) {
waitAll = waitAll.concat(addAllNormalized(cache, extractedRequests, newOptions));
}
return Promise.all(waitAll);
});
})();
} else {
addAll = Promise.all(addAll);
}
return addAll;
});
}
function extractAssetsWithLoaders(request, response) {
var all = Object.keys(loadersMap).map(function (key) {
var loader = loadersMap[key];
if (loader.indexOf(request) !== -1 && loaders[key]) {
return loaders[key](response.clone());
}
}).filter(function (a) {
return !!a;
});
return Promise.all(all).then(function (all) {
return [].concat.apply([], all);
});
}
function matchCacheMap(request) {
var urlString = request.url;
var url = new URL(urlString);
var requestType = undefined;
if (isNavigateRequest(request)) {
requestType = 'navigate';
} else if (url.origin === location.origin) {
requestType = 'same-origin';
} else {
requestType = 'cross-origin';
}
for (var i = 0; i < cacheMaps.length; i++) {
var map = cacheMaps[i];
if (!map) continue;
if (map.requestTypes && map.requestTypes.indexOf(requestType) === -1) {
continue;
}
var newString = undefined;
if (typeof map.match === 'function') {
newString = map.match(url, request);
} else {
newString = urlString.replace(map.match, map.to);
}
if (newString && newString !== urlString) {
return newString;
}
}
}
function fetchWithPreload(event) {
if (!event.preloadResponse || navigationPreload !== true) {
return fetch(event.request);
}
return event.preloadResponse.then(function (response) {
return response || fetch(event.request);
});
}
}
function cachesMatch(request, cacheName) {
return caches.match(request, {
cacheName: cacheName
}).then(function (response) {
if (isNotRedirectedResponse(response)) {
return response;
}
// Fix already cached redirected responses
return fixRedirectedResponse(response).then(function (fixedResponse) {
return caches.open(cacheName).then(function (cache) {
return cache.put(request, fixedResponse);
}).then(function () {
return fixedResponse;
});
});
})
// Return void if error happened (cache not found)
['catch'](function () {});
}
function applyCacheBust(asset, key) {
var hasQuery = asset.indexOf('?') !== -1;
return asset + (hasQuery ? '&' : '?') + '__uncache=' + encodeURIComponent(key);
}
function isNavigateRequest(request) {
return request.mode === 'navigate' || request.headers.get('Upgrade-Insecure-Requests') || (request.headers.get('Accept') || '').indexOf('text/html') !== -1;
}
function isNotRedirectedResponse(response) {
return !response || !response.redirected || !response.ok || response.type === 'opaqueredirect';
}
// Based on https://github.com/GoogleChrome/sw-precache/pull/241/files#diff-3ee9060dc7a312c6a822cac63a8c630bR85
function fixRedirectedResponse(response) {
if (isNotRedirectedResponse(response)) {
return Promise.resolve(response);
}
var body = 'body' in response ? Promise.resolve(response.body) : response.blob();
return body.then(function (data) {
return new Response(data, {
headers: response.headers,
status: response.status
});
});