-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__offline_serviceworker
778 lines (625 loc) · 21 KB
/
__offline_serviceworker
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
/******/ (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;
var strategy = params.strategy;
var responseStrategy = params.responseStrategy;
var assets = params.assets;
var loadersMap = params.loaders || {};
var hashesMap = params.hashesMap;
var externals = params.externals;
// Not used yet
// const alwaysRevalidate = params.alwaysRevalidate;
// const ignoreSearch = params.ignoreSearch;
// const preferOnline = params.preferOnline;
var CACHE_PREFIX = params.name;
var CACHE_TAG = params.version;
var CACHE_NAME = CACHE_PREFIX + ':' + CACHE_TAG;
var STORED_DATA_KEY = '__offline_webpack__data';
mapAssets();
var allAssets = [].concat(assets.main, assets.additional, assets.optional);
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();
}
});
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,
// fallback to navigateFallbackURL if available
if (navigateFallbackURL && isNavigateRequest(event.request)) {
event.respondWith(handleNavigateFallback(fetch(event.request)));
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));
}
return;
}
// Logic of caching / fetching is here
// * urlString -- url to match from the CACHE_NAME
// * event.request -- original Request to perform fetch() if necessary
var resource = undefined;
if (responseStrategy === 'network-first') {
resource = networkFirstResponse(event, urlString, cacheUrl);
}
// 'cache-first'
// (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) {
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 fetch(event.request).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 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 (request.mode === 'navigate') {
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 cachesMatch(request, cacheName) {
return caches.match(request, {
cacheName: cacheName
}).then(function (response) {
if (isNotRedirectedResponse()) {
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 getClientsURLs() {
if (!self.clients) {
return Promise.resolve([]);
}
return self.clients.matchAll({
includeUncontrolled: true
}).then(function (clients) {
if (!clients.length) return [];
var result = [];
clients.forEach(function (client) {
var url = new URL(client.url);
url.search = '';
url.hash = '';
var urlString = url.toString();
if (!result.length || result.indexOf(urlString) === -1) {
result.push(urlString);
}
});
return result;
});
}
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
});
});
}
function copyObject(original) {
return Object.keys(original).reduce(function (result, key) {
result[key] = original[key];
return result;
}, {});
}
function logGroup(title, assets) {
console.groupCollapsed('[SW]:', title);
assets.forEach(function (asset) {
console.log('Asset:', asset);
});
console.groupEnd();
}
WebpackServiceWorker(__wpo, {
loaders: {},
cacheMaps: [],
});
module.exports = __webpack_require__(0)
/***/ })
/******/ ]);