Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

dsw

Package Overview
Dependencies
Maintainers
1
Versions
25
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dsw - npm Package Compare versions

Comparing version 1.7.2 to 1.8.0

sandbox/api/bypass/log.js

233

dist/dsw.js

@@ -7,16 +7,21 @@ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

});
function getBestMatchingRX(str) {
function getBestMatchingRX(str, expressions) {
var bestMatchingRX = void 0;
var bestMatchingGroup = Number.MAX_SAFE_INTEGER;
var rx = []; // list of regular expressions
rx.forEach(function (currentRX) {
var regex = new RegExp(currentRX);
var groups = regex.exec(str);
if (groups && groups.length < bestMatchingGroup) {
var bestMatchingGroupSize = Number.MAX_SAFE_INTEGER;
var bestMatchingGroup = void 0;
expressions.forEach(function (currentRX) {
var regex = new RegExp(currentRX.rx);
var groups = str.match(regex);
if (groups && groups.length < bestMatchingGroupSize) {
bestMatchingRX = currentRX;
bestMatchingGroup = groups.length;
bestMatchingGroupSize = groups.length;
bestMatchingGroup = groups;
}
console.log(groups);
});
return bestMatchingRX;
debugger;
return {
rule: bestMatchingRX,
matching: bestMatchingGroup
};
}

@@ -41,2 +46,6 @@

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -79,3 +88,3 @@

} else {
console.warn('Invalid duration ' + duration, rule);
_logger2.default.warn('Invalid duration ' + duration, rule);
duration = -1;

@@ -150,3 +159,6 @@ }

return caches.open(cacheManager.mountCacheId(rule)).then(function (cache) {
cache.put(request, cloned);
request = _utils2.default.createRequest(request, { mode: 'no-cors' });
if (request.method != 'POST') {
cache.put(request, cloned);
}
return response;

@@ -161,4 +173,7 @@ });

caches.open(cacheId).then(function (cache) {
// adding to cache`
cache.put(request, response.clone());
// adding to cache
request = _utils2.default.createRequest(request, { mode: 'no-cors' });
if (request.method != 'POST') {
cache.put(request, response.clone());
}
resolve(response);

@@ -171,3 +186,3 @@ // in case it is supposed to expire

}).catch(function (err) {
console.error(err);
_logger2.default.error(err);
resolve(response);

@@ -182,3 +197,3 @@ });

fetch(goFetch(null, request)).then(addIt).catch(function (err) {
console.error('[ DSW ] :: Failed fetching ' + (request.url || request), err);
_logger2.default.error('[ DSW ] :: Failed fetching ' + (request.url || request), err);
reject(response);

@@ -244,2 +259,31 @@ });

switch (actionType) {
case 'bypass':
{
// if it is a bypass action (no rule shall be applied, at all)
if (rule.action[actionType] == 'request') {
// it may be of type request
// and we will simple allow it to go ahead
// this also means we will NOT treat any result from it
_logger2.default.info('Bypassing request, going for the network for', request.url);
var treatResponse = function treatResponse(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
_logger2.default.info('Bypassed request for ', request.url, 'failed and was, therefore, ignored');
return new Response(''); // ignored
}
};
// here we will use a "raw" fetch, instead of goFetch, which would
// create a new Request and define propreties to it
return fetch(event.request).then(treatResponse).catch(treatResponse);
} else {
// or of type 'ignore' (or anything else, actually)
// and we will simply output nothing, as if ignoring both the
// request and response
actionType = 'output';
rule.action[actionType] = '';
_logger2.default.info('Bypassing request, outputing nothing out of it');
}
}
case 'output':

@@ -309,3 +353,3 @@ {

lookForCache = Promise.resolve();
console.info('Cache expired for ', request.url);
_logger2.default.info('Cache expired for ', request.url);
} else {

@@ -371,3 +415,3 @@ // if not expired, let's look for it!

if (rule.action.cache !== false) {
return cacheManager.add(request, cacheManager.mountCacheId(rule), response, rule);
return cacheManager.add(_utils2.default.createRequest(request, { mode: 'no-cors' }), cacheManager.mountCacheId(rule), response, rule);
}

@@ -394,3 +438,3 @@ return response;

if (expired) {
console.warn('Cache for ', request.url || request, 'had expired, but the updated version could not be retrieved from the network!\n', 'Delivering the outdated cached data');
_logger2.default.warn('Cache for ', request.url || request, 'had expired, but the updated version could not be retrieved from the network!\n', 'Delivering the outdated cached data');
return cacheManager.get(rule, request, event, matching, true);

@@ -421,3 +465,3 @@ }

},{"./indexeddb-manager.js":4,"./utils.js":7}],3:[function(require,module,exports){
},{"./indexeddb-manager.js":4,"./logger.js":5,"./utils.js":8}],3:[function(require,module,exports){
'use strict';

@@ -478,12 +522,13 @@

};
if (request.credentials) {
reqConfig.credentials = request.credentials;
}
// if (request.credentials && request.credentials != 'omit') {
// reqConfig.credentials = request.credentials;
// }
// if the host is not the same
if (new URL(tmpUrl).hostname.indexOf(domain) >= 0) {
if (new URL(tmpUrl).hostname.indexOf(domain) < 0) {
// we set it to an opaque request
//reqConfig.mode = 'no-cors';
request = new Request(tmpUrl || request.url, reqConfig);
reqConfig.mode = 'no-cors';
}
request = new Request(tmpUrl || request.url, reqConfig);

@@ -504,3 +549,3 @@ if (actionType == 'redirect') {

},{"./utils.js":7}],4:[function(require,module,exports){
},{"./utils.js":8}],4:[function(require,module,exports){
'use strict';

@@ -512,2 +557,8 @@

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_DB_NAME = 'defaultDSWDB';

@@ -538,3 +589,3 @@ var INDEXEDDB_REQ_IDS = 'indexeddb-id-request';

db.close();
console.log('There is a new version of the database(IndexedDB) for ' + config.name);
_logger2.default.log('There is a new version of the database(IndexedDB) for ' + config.name);
};

@@ -690,3 +741,3 @@

}).catch(function (err) {
console.error('Failed saving into indexedDB!\n', err.message, err);
_logger2.default.error('Failed saving into indexedDB!\n', err.message, err);
reject('Failed saving into indexedDB!');

@@ -700,3 +751,53 @@ });

},{}],5:[function(require,module,exports){
},{"./logger.js":5}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var TYPES = {
log: '[ LG ] :: ',
info: '[ INFO ] :: ',
warn: '[ WARN ] :: ',
error: '[ FAIL ] :: ',
track: '[ STEP ] :: '
};
var logger = {
info: function info() {
var args = [].slice.call(arguments);
args.unshift('color: blue');
args.unshift('%c ' + TYPES.info);
console.info.apply(console, args);
},
log: function log() {
var args = [].slice.call(arguments);
args.unshift('color: gray');
args.unshift('%c ' + TYPES.log);
console.log.apply(console, args);
},
warn: function warn() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold; color: yellow; text-shadow: 0 0 1px black;');
args.unshift('%c ' + TYPES.warn);
console.warn.apply(console, args);
},
error: function error() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold; color: red');
args.unshift('%c ' + TYPES.error);
console.error.apply(console, args);
},
track: function track() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold');
args.unshift('%c ' + TYPES.track);
console.error.apply(console, args);
}
};
exports.default = logger;
},{}],6:[function(require,module,exports){
(function (global){

@@ -709,2 +810,6 @@ 'use strict';

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
var _bestMatchingRx = require('./best-matching-rx.js');

@@ -774,3 +879,3 @@

// fetch a different resource
console.info('Found fallback rule for ', pathName, '\nLooking for its result');
_logger2.default.info('Found fallback rule for ', pathName, '\nLooking for its result');
result = _cacheManager2.default.get(cur, new Request(cur.action.fetch), event, matching);

@@ -782,3 +887,3 @@ return true; // stopping the loop

if (!result) {
console.info('No rules for failed request: ', pathName, '\nWill output the failure');
_logger2.default.info('No rules for failed request: ', pathName, '\nWill output the failure');
}

@@ -925,5 +1030,7 @@ return result || response;

DSW.requestId = 1 + (DSW.requestId || 0);
// in case there are no rules (happens when chrome crashes, for example)
if (!Object.keys(DSWManager.rules).length) {
return DSWManager.setup().then(function (_) {
return DSWManager.setup(PWASettings).then(function (_) {
return fetch(event);

@@ -943,13 +1050,12 @@ });

var i = 0,
l = (DSWManager.rules['*'] || []).length;
// get the best fiting rx for the path, to find the rule that
// matches the most
var matchingRule = (0, _bestMatchingRx2.default)(pathName, DSWManager.rules['*']);
if (matchingRule) {
// if there is a rule that matches the url
return event.respondWith(
// we apply the right strategy for the matching rule
_strategies2.default[matchingRule.rule.strategy](matchingRule.rule, event.request, event, matchingRule.matching));
}
for (; i < l; i++) {
var rule = DSWManager.rules['*'][i];
var matching = pathName.match(rule.rx);
if (matching) {
// if there is a rule that matches the url
return event.respondWith(_strategies2.default[rule.strategy](rule, event.request, event, matching));
}
}
// if no rule is applied, we will request it

@@ -1018,3 +1124,3 @@ // this is the function to deal with the resolt of this request

navigator.serviceWorker.register(src).then(function (SW) {
console.info('[ SW ] :: registered');
_logger2.default.info('Registered service worker');
if (config && config.sync) {

@@ -1085,3 +1191,3 @@ if ('SyncManager' in window) {

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./best-matching-rx.js":1,"./cache-manager.js":2,"./go-fetch.js":3,"./strategies.js":6}],6:[function(require,module,exports){
},{"./best-matching-rx.js":1,"./cache-manager.js":2,"./go-fetch.js":3,"./logger.js":5,"./strategies.js":7}],7:[function(require,module,exports){
'use strict';

@@ -1093,2 +1199,8 @@

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DSWManager = void 0;

@@ -1109,3 +1221,3 @@ var cacheManager = void 0;

// and then return it to be used
console.info('offline first: Looking into cache for\n', request.url);
_logger2.default.info('offline first: Looking into cache for\n', request.url);
return cacheManager.get(rule, request, event, matching);

@@ -1121,6 +1233,6 @@ },

cacheManager.put(rule, request, response).then(function (_) {
console.info('Updated in cache: ', request.url);
_logger2.default.info('Updated in cache: ', request.url);
});
}
console.info('From network: ', request.url);
_logger2.default.info('From network: ', request.url);
return response;

@@ -1133,3 +1245,3 @@ }

if (result) {
console.info('From cache(after network failure): ', request.url);
_logger2.default.info('From cache(after network failure): ', request.url);
}

@@ -1166,3 +1278,3 @@ return result || DSWManager.treatBadPage(response, pathName, event);

cacheManager.put(rule, request, response).then(function (_) {
console.info('Updated in cache (from fastest): ', request.url);
_logger2.default.info('Updated in cache (from fastest): ', request.url);
});

@@ -1176,3 +1288,3 @@ }

if (response.status == 200) {
console.log('fastest strategy: loaded from network', request.url);
_logger2.default.log('fastest strategy: loaded from network', request.url);
networkTreated = true;

@@ -1194,3 +1306,3 @@ // if cache could not resolve it, the network resolves

cacheTreated = true; // this will prevent network from resolving too
console.log('fastest strategy: loaded from cache', request.url);
_logger2.default.log('fastest strategy: loaded from cache', request.url);
resolve(result);

@@ -1225,3 +1337,3 @@ return result;

},{}],7:[function(require,module,exports){
},{"./logger.js":5}],8:[function(require,module,exports){
'use strict';

@@ -1234,2 +1346,4 @@

var utils = {
// Applies the matched patterns into strings (used to replace variables)
applyMatch: function applyMatch(matching, text) {

@@ -1243,2 +1357,13 @@ if (matching && matching.length > 1 && text) {

return text;
},
createRequest: function createRequest(request, reqData) {
var reqConfig = {
method: reqData.method || request.method || 'GET',
headers: reqData.headers || request.headers || new Headers(),
mode: reqData.mode || (reqData.redirect ? 'same-origin' : 'cors'),
redirect: reqData.redirect || 'manual',
cache: 'default'
};
return new Request(request.url || request, reqConfig);
}

@@ -1249,2 +1374,2 @@ };

},{}]},{},[5]);
},{}]},{},[6]);

@@ -40,3 +40,3 @@ {

"easterEgg": {
"match": { "path": "\/easter-egg" },
"match": { "path": "/easter-egg" },
"apply": {

@@ -62,3 +62,3 @@ // by using the output action (it accepts variables, as in other examples)

// In this example, everything inside this directory should be redirected
"path": "\/legacy-images\/.*"
"path": "/legacy-images/.*"
},

@@ -77,3 +77,3 @@ "apply": {

// the image named "not-cached" will
"match": { "path": "\/images\/not-cached" },
"match": { "path": "/images/not-cached" },
"apply": {

@@ -116,3 +116,3 @@ // not be cached...ever!

// this expression, between parenthesis
"path": "\/old-site\/(.*)"
"path": "/old-site/(.*)"
},

@@ -134,3 +134,3 @@ "apply": {

// everything in /
{ "path": "\/$" }
{ "path": "/$" }
],

@@ -153,3 +153,3 @@ // The default strategy is 'offline-first'

"userData": {
"match": { "path": "\/api\/user\/.*" },
"match": { "path": "/api/user/.*" },
// We will try to keep it up to date.

@@ -185,4 +185,25 @@ // DSW will look for it online, and if not possible, then look in the

},
// You can also bypass some requests
"byPassable": {
"match": { "path": "/bypass/" },
"apply": {
// With the "request" value, it WILL perform the request, with no treatment.
// But the response will either be the response itself(in case of success)
// or an empty string(if failed)
"bypass": "request"
}
},
// When bypassing, you may also want to simply ignore some path
"ignorable": {
// imagine you have an old path and that some legacy script, html or css is
// still trying to load resources from it
"match": { "path": "/ignore/" },
"apply": {
// by ignoring it, no network request will be started, and the output
// will be always a successful empty string
"bypass": "ignore"
}
},
"dashbord": {
"match": { "path": "\/api\/dashbord\/.*" },
"match": { "path": "/api/dashbord/.*" },
// Here, we are telling the browser to send cookies and session credentions

@@ -189,0 +210,0 @@ // when fetching this

{
"name": "dsw",
"version": "1.7.2",
"version": "1.8.0",
"description": "Dynamic Service Worker, offline Progressive Web Apps much easier",

@@ -5,0 +5,0 @@ "bin": {

@@ -13,3 +13,3 @@ # Dynamic Service Worker

If you are starting from scratch and want to see it working "out of nothing", you can use the content inside `/boilerplate`.
If you are starting from scratch and want to see it working right away, you can use the content inside of `/boilerplate`.

@@ -21,3 +21,3 @@ ## Live Demo

You can then go offline and reload the page to validate it.
[Dynamic Service Worker demo](https://dsw-demo-jbzuwbkfeh.now.sh)
[Dynamic Service Worker demo](https://dsw-demo-zrrauyeple.now.sh)

@@ -81,3 +81,4 @@ ## Advantages

Done! Now, for any change in your Dynamic Service Worker configuration, just run again the `dsw` command line on your project.<br/>
Done! Now, for any change in your Dynamic Service Worker configuration, just run the `dsw` command line on your project.<br/>
For ever new change or version, you will have to run `dsw` again, so it will generate the updated service worker file.<br/>
This will create the `manifest` (if not there, already) and the `dsw.js` file.

@@ -175,2 +176,3 @@

- output: String, accepting the use of variables ($1, $2, etc) to be the response itselfe
- bypass: Will **not** treat the request anyhow, neither the response.<br.>Accepts the values `request` (will go for the network, and if it fails, will output an empty string) or `ignore` (will always output an empty string).

@@ -403,3 +405,2 @@ #### Cache

#### Caching your static files

@@ -406,0 +407,0 @@

@@ -5,2 +5,3 @@ const PWASettings = {

"appShell": [
"/dsw.js",
"/helmet.png",

@@ -13,4 +14,16 @@ "/index.html?homescreen=1"

"dswRules": {
"byPassable": {
"match": { "path": "/bypass/" },
"apply": {
"bypass": "request"
}
},
"ignorable": {
"match": { "path": "/ignore/" },
"apply": {
"bypass": "ignore"
}
},
"easterEgg": {
"match": { "path": "\/easter-egg" },
"match": { "path": "/easter-egg" },
"apply": {

@@ -21,3 +34,3 @@ "output": "You found an easter egg!!!"

"moved-pages": {
"match": { "path": "\/old-site\/(.*)" },
"match": { "path": "/old-site/(.*)" },
"apply": {

@@ -38,3 +51,3 @@ "redirect": "/redirected.html?$1"

"match": {
"path": "\/legacy-images\/.*"
"path": "/legacy-images/.*"
},

@@ -54,3 +67,3 @@ "apply": {

"imageNotCached": {
"match": { "path": "\/images\/not-cached" },
"match": { "path": "/images/not-cached" },
"apply": {

@@ -82,3 +95,3 @@ "cache": false

{ "extension": ["html"] },
{ "path": "\/$" }
{ "path": "/$" }
],

@@ -94,3 +107,3 @@ "strategy": "fastest",

"userData": {
"match": { "path": "\/api\/user\/.*" },
"match": { "path": "/api/user/.*" },
"options": { "credentials": "same-origin"},

@@ -117,3 +130,3 @@ "strategy": "offline-first",

"service": {
"match": { "path": "\/api\/service\/.*" },
"match": { "path": "/api/service/.*" },
"options": { "credentials": "same-origin"},

@@ -138,16 +151,21 @@ "strategy": "fastest",

});
function getBestMatchingRX(str) {
function getBestMatchingRX(str, expressions) {
var bestMatchingRX = void 0;
var bestMatchingGroup = Number.MAX_SAFE_INTEGER;
var rx = []; // list of regular expressions
rx.forEach(function (currentRX) {
var regex = new RegExp(currentRX);
var groups = regex.exec(str);
if (groups && groups.length < bestMatchingGroup) {
var bestMatchingGroupSize = Number.MAX_SAFE_INTEGER;
var bestMatchingGroup = void 0;
expressions.forEach(function (currentRX) {
var regex = new RegExp(currentRX.rx);
var groups = str.match(regex);
if (groups && groups.length < bestMatchingGroupSize) {
bestMatchingRX = currentRX;
bestMatchingGroup = groups.length;
bestMatchingGroupSize = groups.length;
bestMatchingGroup = groups;
}
console.log(groups);
});
return bestMatchingRX;
debugger;
return {
rule: bestMatchingRX,
matching: bestMatchingGroup
};
}

@@ -172,2 +190,6 @@

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -210,3 +232,3 @@

} else {
console.warn('Invalid duration ' + duration, rule);
_logger2.default.warn('Invalid duration ' + duration, rule);
duration = -1;

@@ -281,3 +303,6 @@ }

return caches.open(cacheManager.mountCacheId(rule)).then(function (cache) {
cache.put(request, cloned);
request = _utils2.default.createRequest(request, { mode: 'no-cors' });
if (request.method != 'POST') {
cache.put(request, cloned);
}
return response;

@@ -292,4 +317,7 @@ });

caches.open(cacheId).then(function (cache) {
// adding to cache`
cache.put(request, response.clone());
// adding to cache
request = _utils2.default.createRequest(request, { mode: 'no-cors' });
if (request.method != 'POST') {
cache.put(request, response.clone());
}
resolve(response);

@@ -302,3 +330,3 @@ // in case it is supposed to expire

}).catch(function (err) {
console.error(err);
_logger2.default.error(err);
resolve(response);

@@ -313,3 +341,3 @@ });

fetch(goFetch(null, request)).then(addIt).catch(function (err) {
console.error('[ DSW ] :: Failed fetching ' + (request.url || request), err);
_logger2.default.error('[ DSW ] :: Failed fetching ' + (request.url || request), err);
reject(response);

@@ -375,2 +403,31 @@ });

switch (actionType) {
case 'bypass':
{
// if it is a bypass action (no rule shall be applied, at all)
if (rule.action[actionType] == 'request') {
// it may be of type request
// and we will simple allow it to go ahead
// this also means we will NOT treat any result from it
_logger2.default.info('Bypassing request, going for the network for', request.url);
var treatResponse = function treatResponse(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
_logger2.default.info('Bypassed request for ', request.url, 'failed and was, therefore, ignored');
return new Response(''); // ignored
}
};
// here we will use a "raw" fetch, instead of goFetch, which would
// create a new Request and define propreties to it
return fetch(event.request).then(treatResponse).catch(treatResponse);
} else {
// or of type 'ignore' (or anything else, actually)
// and we will simply output nothing, as if ignoring both the
// request and response
actionType = 'output';
rule.action[actionType] = '';
_logger2.default.info('Bypassing request, outputing nothing out of it');
}
}
case 'output':

@@ -440,3 +497,3 @@ {

lookForCache = Promise.resolve();
console.info('Cache expired for ', request.url);
_logger2.default.info('Cache expired for ', request.url);
} else {

@@ -502,3 +559,3 @@ // if not expired, let's look for it!

if (rule.action.cache !== false) {
return cacheManager.add(request, cacheManager.mountCacheId(rule), response, rule);
return cacheManager.add(_utils2.default.createRequest(request, { mode: 'no-cors' }), cacheManager.mountCacheId(rule), response, rule);
}

@@ -525,3 +582,3 @@ return response;

if (expired) {
console.warn('Cache for ', request.url || request, 'had expired, but the updated version could not be retrieved from the network!\n', 'Delivering the outdated cached data');
_logger2.default.warn('Cache for ', request.url || request, 'had expired, but the updated version could not be retrieved from the network!\n', 'Delivering the outdated cached data');
return cacheManager.get(rule, request, event, matching, true);

@@ -552,3 +609,3 @@ }

},{"./indexeddb-manager.js":4,"./utils.js":7}],3:[function(require,module,exports){
},{"./indexeddb-manager.js":4,"./logger.js":5,"./utils.js":8}],3:[function(require,module,exports){
'use strict';

@@ -609,12 +666,13 @@

};
if (request.credentials) {
reqConfig.credentials = request.credentials;
}
// if (request.credentials && request.credentials != 'omit') {
// reqConfig.credentials = request.credentials;
// }
// if the host is not the same
if (new URL(tmpUrl).hostname.indexOf(domain) >= 0) {
if (new URL(tmpUrl).hostname.indexOf(domain) < 0) {
// we set it to an opaque request
//reqConfig.mode = 'no-cors';
request = new Request(tmpUrl || request.url, reqConfig);
reqConfig.mode = 'no-cors';
}
request = new Request(tmpUrl || request.url, reqConfig);

@@ -635,3 +693,3 @@ if (actionType == 'redirect') {

},{"./utils.js":7}],4:[function(require,module,exports){
},{"./utils.js":8}],4:[function(require,module,exports){
'use strict';

@@ -643,2 +701,8 @@

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_DB_NAME = 'defaultDSWDB';

@@ -669,3 +733,3 @@ var INDEXEDDB_REQ_IDS = 'indexeddb-id-request';

db.close();
console.log('There is a new version of the database(IndexedDB) for ' + config.name);
_logger2.default.log('There is a new version of the database(IndexedDB) for ' + config.name);
};

@@ -821,3 +885,3 @@

}).catch(function (err) {
console.error('Failed saving into indexedDB!\n', err.message, err);
_logger2.default.error('Failed saving into indexedDB!\n', err.message, err);
reject('Failed saving into indexedDB!');

@@ -831,3 +895,53 @@ });

},{}],5:[function(require,module,exports){
},{"./logger.js":5}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var TYPES = {
log: '[ LG ] :: ',
info: '[ INFO ] :: ',
warn: '[ WARN ] :: ',
error: '[ FAIL ] :: ',
track: '[ STEP ] :: '
};
var logger = {
info: function info() {
var args = [].slice.call(arguments);
args.unshift('color: blue');
args.unshift('%c ' + TYPES.info);
console.info.apply(console, args);
},
log: function log() {
var args = [].slice.call(arguments);
args.unshift('color: gray');
args.unshift('%c ' + TYPES.log);
console.log.apply(console, args);
},
warn: function warn() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold; color: yellow; text-shadow: 0 0 1px black;');
args.unshift('%c ' + TYPES.warn);
console.warn.apply(console, args);
},
error: function error() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold; color: red');
args.unshift('%c ' + TYPES.error);
console.error.apply(console, args);
},
track: function track() {
var args = [].slice.call(arguments);
args.unshift('font-weight: bold');
args.unshift('%c ' + TYPES.track);
console.error.apply(console, args);
}
};
exports.default = logger;
},{}],6:[function(require,module,exports){
(function (global){

@@ -840,2 +954,6 @@ 'use strict';

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
var _bestMatchingRx = require('./best-matching-rx.js');

@@ -905,3 +1023,3 @@

// fetch a different resource
console.info('Found fallback rule for ', pathName, '\nLooking for its result');
_logger2.default.info('Found fallback rule for ', pathName, '\nLooking for its result');
result = _cacheManager2.default.get(cur, new Request(cur.action.fetch), event, matching);

@@ -913,3 +1031,3 @@ return true; // stopping the loop

if (!result) {
console.info('No rules for failed request: ', pathName, '\nWill output the failure');
_logger2.default.info('No rules for failed request: ', pathName, '\nWill output the failure');
}

@@ -1056,5 +1174,7 @@ return result || response;

DSW.requestId = 1 + (DSW.requestId || 0);
// in case there are no rules (happens when chrome crashes, for example)
if (!Object.keys(DSWManager.rules).length) {
return DSWManager.setup().then(function (_) {
return DSWManager.setup(PWASettings).then(function (_) {
return fetch(event);

@@ -1074,13 +1194,12 @@ });

var i = 0,
l = (DSWManager.rules['*'] || []).length;
// get the best fiting rx for the path, to find the rule that
// matches the most
var matchingRule = (0, _bestMatchingRx2.default)(pathName, DSWManager.rules['*']);
if (matchingRule) {
// if there is a rule that matches the url
return event.respondWith(
// we apply the right strategy for the matching rule
_strategies2.default[matchingRule.rule.strategy](matchingRule.rule, event.request, event, matchingRule.matching));
}
for (; i < l; i++) {
var rule = DSWManager.rules['*'][i];
var matching = pathName.match(rule.rx);
if (matching) {
// if there is a rule that matches the url
return event.respondWith(_strategies2.default[rule.strategy](rule, event.request, event, matching));
}
}
// if no rule is applied, we will request it

@@ -1149,3 +1268,3 @@ // this is the function to deal with the resolt of this request

navigator.serviceWorker.register(src).then(function (SW) {
console.info('[ SW ] :: registered');
_logger2.default.info('Registered service worker');
if (config && config.sync) {

@@ -1216,3 +1335,3 @@ if ('SyncManager' in window) {

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./best-matching-rx.js":1,"./cache-manager.js":2,"./go-fetch.js":3,"./strategies.js":6}],6:[function(require,module,exports){
},{"./best-matching-rx.js":1,"./cache-manager.js":2,"./go-fetch.js":3,"./logger.js":5,"./strategies.js":7}],7:[function(require,module,exports){
'use strict';

@@ -1224,2 +1343,8 @@

var _logger = require('./logger.js');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DSWManager = void 0;

@@ -1240,3 +1365,3 @@ var cacheManager = void 0;

// and then return it to be used
console.info('offline first: Looking into cache for\n', request.url);
_logger2.default.info('offline first: Looking into cache for\n', request.url);
return cacheManager.get(rule, request, event, matching);

@@ -1252,6 +1377,6 @@ },

cacheManager.put(rule, request, response).then(function (_) {
console.info('Updated in cache: ', request.url);
_logger2.default.info('Updated in cache: ', request.url);
});
}
console.info('From network: ', request.url);
_logger2.default.info('From network: ', request.url);
return response;

@@ -1264,3 +1389,3 @@ }

if (result) {
console.info('From cache(after network failure): ', request.url);
_logger2.default.info('From cache(after network failure): ', request.url);
}

@@ -1297,3 +1422,3 @@ return result || DSWManager.treatBadPage(response, pathName, event);

cacheManager.put(rule, request, response).then(function (_) {
console.info('Updated in cache (from fastest): ', request.url);
_logger2.default.info('Updated in cache (from fastest): ', request.url);
});

@@ -1307,3 +1432,3 @@ }

if (response.status == 200) {
console.log('fastest strategy: loaded from network', request.url);
_logger2.default.log('fastest strategy: loaded from network', request.url);
networkTreated = true;

@@ -1325,3 +1450,3 @@ // if cache could not resolve it, the network resolves

cacheTreated = true; // this will prevent network from resolving too
console.log('fastest strategy: loaded from cache', request.url);
_logger2.default.log('fastest strategy: loaded from cache', request.url);
resolve(result);

@@ -1356,3 +1481,3 @@ return result;

},{}],7:[function(require,module,exports){
},{"./logger.js":5}],8:[function(require,module,exports){
'use strict';

@@ -1365,2 +1490,4 @@

var utils = {
// Applies the matched patterns into strings (used to replace variables)
applyMatch: function applyMatch(matching, text) {

@@ -1374,2 +1501,13 @@ if (matching && matching.length > 1 && text) {

return text;
},
createRequest: function createRequest(request, reqData) {
var reqConfig = {
method: reqData.method || request.method || 'GET',
headers: reqData.headers || request.headers || new Headers(),
mode: reqData.mode || (reqData.redirect ? 'same-origin' : 'cors'),
redirect: reqData.redirect || 'manual',
cache: 'default'
};
return new Request(request.url || request, reqConfig);
}

@@ -1380,2 +1518,2 @@ };

},{}]},{},[5]);
},{}]},{},[6]);

@@ -5,2 +5,3 @@ {

"appShell": [
"/dsw.js",
"/helmet.png",

@@ -13,4 +14,16 @@ "/index.html?homescreen=1"

"dswRules": {
"byPassable": {
"match": { "path": "/bypass/" },
"apply": {
"bypass": "request"
}
},
"ignorable": {
"match": { "path": "/ignore/" },
"apply": {
"bypass": "ignore"
}
},
"easterEgg": {
"match": { "path": "\/easter-egg" },
"match": { "path": "/easter-egg" },
"apply": {

@@ -21,3 +34,3 @@ "output": "You found an easter egg!!!"

"moved-pages": {
"match": { "path": "\/old-site\/(.*)" },
"match": { "path": "/old-site/(.*)" },
"apply": {

@@ -38,3 +51,3 @@ "redirect": "/redirected.html?$1"

"match": {
"path": "\/legacy-images\/.*"
"path": "/legacy-images/.*"
},

@@ -54,3 +67,3 @@ "apply": {

"imageNotCached": {
"match": { "path": "\/images\/not-cached" },
"match": { "path": "/images/not-cached" },
"apply": {

@@ -82,3 +95,3 @@ "cache": false

{ "extension": ["html"] },
{ "path": "\/$" }
{ "path": "/$" }
],

@@ -94,3 +107,3 @@ "strategy": "fastest",

"userData": {
"match": { "path": "\/api\/user\/.*" },
"match": { "path": "/api/user/.*" },
"options": { "credentials": "same-origin"},

@@ -117,3 +130,3 @@ "strategy": "offline-first",

"service": {
"match": { "path": "\/api\/service\/.*" },
"match": { "path": "/api/service/.*" },
"options": { "credentials": "same-origin"},

@@ -120,0 +133,0 @@ "strategy": "fastest",

@@ -42,23 +42,21 @@ console.log('LOADED THE SCRIPT');

let idx = Math.ceil(Math.random() * 5) -1;
console.log(idx);
set(document.getElementById('test-7-iframe'), 'src', '/old-site/' +
listOfOlderPages[idx]);
});
/*
document.getElementById('btn-img-6').addEventListener('click', function(){
// fetch('/api/user/2.json').then(function(response){
// response.text().then(function(text){
// document.getElementById('fetch-result').innerHTML = text;
// });
// });
});
document.getElementById('btn-7').addEventListener('click', function(){
fetch('/api/user/1.json').then(function(response){
response.text().then(function(text){
document.getElementById('test-5-iframe').innerHTML = text;
setTimeout(_=>{
fetch('/api/bypass/log.js').then(_=>{
_.text().then(content=>{
console.log(content);
});
});
});
*/
setTimeout(_=>{
fetch('/ignore/index.html').then(_=>{
_.text().then(content=>{
console.log(content);
});
});
}, 1000);
}, 3000);
});

@@ -1,17 +0,22 @@

function getBestMatchingRX(str){
function getBestMatchingRX(str, expressions){
let bestMatchingRX;
let bestMatchingGroup = Number.MAX_SAFE_INTEGER;
let rx = []; // list of regular expressions
rx.forEach(function(currentRX){
const regex = new RegExp(currentRX);
const groups = regex.exec(str);
if (groups && groups.length < bestMatchingGroup){
let bestMatchingGroupSize = Number.MAX_SAFE_INTEGER;
let bestMatchingGroup;
expressions.forEach(function(currentRX){
const regex = new RegExp(currentRX.rx);
const groups = str.match(regex);
if (groups && groups.length < bestMatchingGroupSize){
bestMatchingRX = currentRX;
bestMatchingGroup = groups.length;
bestMatchingGroupSize = groups.length;
bestMatchingGroup = groups;
}
console.log(groups);
});
return bestMatchingRX;
debugger;
return {
rule: bestMatchingRX,
matching: bestMatchingGroup
};
}
export default getBestMatchingRX;
import indexedDBManager from './indexeddb-manager.js';
import utils from './utils.js';
import logger from './logger.js';

@@ -39,3 +40,3 @@ const DEFAULT_CACHE_NAME = 'defaultDSWCached';

} else {
console.warn('Invalid duration ' + duration, rule);
logger.warn('Invalid duration ' + duration, rule);
duration = -1;

@@ -121,3 +122,6 @@ }

.then(function(cache) {
cache.put(request, cloned);
request = utils.createRequest(request, { mode: 'no-cors' });
if (request.method != 'POST') {
cache.put(request, cloned);
}
return response;

@@ -132,4 +136,7 @@ });

caches.open(cacheId).then(cache => {
// adding to cache`
cache.put(request, response.clone());
// adding to cache
request = utils.createRequest(request, { mode: 'no-cors' });
if (request.method != 'POST') {
cache.put(request, response.clone());
}
resolve(response);

@@ -147,3 +154,3 @@ // in case it is supposed to expire

}).catch(err=>{
console.error(err);
logger.error(err);
resolve(response);

@@ -160,3 +167,3 @@ });

.catch(err=>{
console.error('[ DSW ] :: Failed fetching ' + (request.url || request), err);
logger.error('[ DSW ] :: Failed fetching ' + (request.url || request), err);
reject(response);

@@ -227,2 +234,33 @@ });

switch (actionType) {
case 'bypass': {
// if it is a bypass action (no rule shall be applied, at all)
if (rule.action[actionType] == 'request') {
// it may be of type request
// and we will simple allow it to go ahead
// this also means we will NOT treat any result from it
logger.info('Bypassing request, going for the network for',
request.url);
let treatResponse = function (response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
logger.info('Bypassed request for ', request.url, 'failed and was, therefore, ignored');
return new Response(''); // ignored
}
};
// here we will use a "raw" fetch, instead of goFetch, which would
// create a new Request and define propreties to it
return fetch(event.request)
.then(treatResponse)
.catch(treatResponse);
} else {
// or of type 'ignore' (or anything else, actually)
// and we will simply output nothing, as if ignoring both the
// request and response
actionType = 'output';
rule.action[actionType] = '';
logger.info('Bypassing request, outputing nothing out of it');
}
}
case 'output': {

@@ -298,3 +336,3 @@ return new Response(

lookForCache = Promise.resolve();
console.info('Cache expired for ', request.url);
logger.info('Cache expired for ', request.url);
} else{

@@ -362,3 +400,3 @@ // if not expired, let's look for it!

if (rule.action.cache !== false) {
return cacheManager.add(request,
return cacheManager.add(utils.createRequest(request, { mode: 'no-cors' }),
cacheManager.mountCacheId(rule),

@@ -391,3 +429,3 @@ response,

if (expired) {
console.warn('Cache for ',
logger.warn('Cache for ',
request.url || request,

@@ -394,0 +432,0 @@ 'had expired, but the updated version could not be retrieved from the network!\n',

@@ -47,12 +47,13 @@ import utils from './utils.js';

};
if (request.credentials) {
reqConfig.credentials = request.credentials;
}
// if (request.credentials && request.credentials != 'omit') {
// reqConfig.credentials = request.credentials;
// }
// if the host is not the same
if ((new URL(tmpUrl)).hostname.indexOf(domain) >= 0) {
if ((new URL(tmpUrl)).hostname.indexOf(domain) < 0) {
// we set it to an opaque request
//reqConfig.mode = 'no-cors';
request = new Request(tmpUrl || request.url, reqConfig);
reqConfig.mode = 'no-cors';
}
request = new Request(tmpUrl || request.url, reqConfig);

@@ -59,0 +60,0 @@ if (actionType == 'redirect') {

@@ -1,2 +0,2 @@

import logger from './logger.js';
const DEFAULT_DB_NAME = 'defaultDSWDB';

@@ -26,3 +26,3 @@ const INDEXEDDB_REQ_IDS = 'indexeddb-id-request';

db.close();
console.log('There is a new version of the database(IndexedDB) for '+
logger.log('There is a new version of the database(IndexedDB) for '+
config.name);

@@ -189,3 +189,3 @@ };

}).catch(err=>{
console.error('Failed saving into indexedDB!\n', err.message, err);
logger.error('Failed saving into indexedDB!\n', err.message, err);
reject('Failed saving into indexedDB!');

@@ -192,0 +192,0 @@ });

@@ -6,2 +6,3 @@ // TODO: should pre-cache or cache in the first load, some of the page's already sources (like css, js or images), or tell the user it supports offline usage, only in the next reload

import logger from './logger.js';
import getBestMatchingRX from './best-matching-rx.js';

@@ -47,4 +48,4 @@ import cacheManager from './cache-manager.js';

(DSWManager.rules[
response && response.status? response.status : 404
] || [])
response && response.status? response.status : 404
] || [])
.some((cur, idx)=>{

@@ -56,3 +57,3 @@ let matching = pathName.match(cur.rx);

// fetch a different resource
console.info('Found fallback rule for ', pathName, '\nLooking for its result');
logger.info('Found fallback rule for ', pathName, '\nLooking for its result');
result = cacheManager.get(cur,

@@ -67,3 +68,3 @@ new Request(cur.action.fetch),

if (!result) {
console.info('No rules for failed request: ', pathName, '\nWill output the failure');
logger.info('No rules for failed request: ', pathName, '\nWill output the failure');
}

@@ -215,5 +216,7 @@ return result || response;

DSW.requestId = 1 + (DSW.requestId || 0);
// in case there are no rules (happens when chrome crashes, for example)
if (!Object.keys(DSWManager.rules).length) {
return DSWManager.setup().then(_=>fetch(event));
return DSWManager.setup(PWASettings).then(_=>fetch(event));
}

@@ -232,20 +235,19 @@

let i = 0,
l = (DSWManager.rules['*'] || []).length;
// get the best fiting rx for the path, to find the rule that
// matches the most
let matchingRule = getBestMatchingRX(pathName,
DSWManager.rules['*']);
if (matchingRule) {
// if there is a rule that matches the url
return event.respondWith(
// we apply the right strategy for the matching rule
strategies[matchingRule.rule.strategy](
matchingRule.rule,
event.request,
event,
matchingRule.matching
)
);
}
for (; i<l; i++) {
let rule = DSWManager.rules['*'][i];
let matching = pathName.match(rule.rx);
if (matching) {
// if there is a rule that matches the url
return event.respondWith(
strategies[rule.strategy](
rule,
event.request,
event,
matching
)
);
}
}
// if no rule is applied, we will request it

@@ -319,3 +321,3 @@ // this is the function to deal with the resolt of this request

.then(SW=>{
console.info('[ SW ] :: registered');
logger.info('Registered service worker');
if (config && config.sync) {

@@ -322,0 +324,0 @@ if ('SyncManager' in window) {

@@ -6,2 +6,4 @@

import logger from './logger.js';
const strategies = {

@@ -18,3 +20,3 @@ setup: function (dswM, cacheM, gf) {

// and then return it to be used
console.info('offline first: Looking into cache for\n', request.url);
logger.info('offline first: Looking into cache for\n', request.url);
return cacheManager.get(

@@ -35,6 +37,6 @@ rule,

cacheManager.put(rule, request, response).then(_=>{
console.info('Updated in cache: ', request.url);
logger.info('Updated in cache: ', request.url);
});
}
console.info('From network: ', request.url);
logger.info('From network: ', request.url);
return response;

@@ -48,3 +50,3 @@ }

if(result){
console.info('From cache(after network failure): ', request.url);
logger.info('From cache(after network failure): ', request.url);
}

@@ -83,3 +85,3 @@ return result || DSWManager.treatBadPage(response, pathName, event);

cacheManager.put(rule, request, response).then(_=>{
console.info('Updated in cache (from fastest): ', request.url);
logger.info('Updated in cache (from fastest): ', request.url);
});

@@ -93,3 +95,3 @@ }

if (response.status == 200) {
console.log('fastest strategy: loaded from network', request.url);
logger.log('fastest strategy: loaded from network', request.url);
networkTreated = true;

@@ -111,3 +113,3 @@ // if cache could not resolve it, the network resolves

cacheTreated = true; // this will prevent network from resolving too
console.log('fastest strategy: loaded from cache', request.url);
logger.log('fastest strategy: loaded from cache', request.url);
resolve(result);

@@ -114,0 +116,0 @@ return result;

const utils = {
// Applies the matched patterns into strings (used to replace variables)
applyMatch (matching, text) {

@@ -11,2 +12,14 @@ if (matching && matching.length > 1 && text) {

return text;
},
createRequest(request, reqData){
let reqConfig = {
method: reqData.method || request.method || 'GET',
headers: reqData.headers || request.headers || new Headers(),
mode: reqData.mode || (reqData.redirect? 'same-origin' : 'cors'),
redirect: reqData.redirect || 'manual',
cache: 'default'
};
return new Request(request.url || request, reqConfig);
}

@@ -13,0 +26,0 @@ };

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc