This repository has been archived by the owner on Nov 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
[WIP] Offliner integration #96
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
bda8955
Making git to ignore only the root level dist folder.
delapuente a755140
Fixing the location for the sw template
delapuente bb6cf25
Recovering original name for both the manager and the service worker.
delapuente 82c56ee
Removing a reference to sw-precache
delapuente 54dd941
Reverting .gitignore
delapuente 888e5ec
Reverting the nam of the offline manager
delapuente d16cac2
Solving nits and completing current oghliner update strategy
delapuente 0590473
Fixing rebase
delapuente 8905f41
Removing unnecessary / sw-precache related tests
delapuente File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,11 +20,13 @@ | |
var promisify = require('promisify-node'); | ||
|
||
var fs = require('fs'); | ||
var conflict = require('gulp-conflict'); | ||
var path = require('path'); | ||
var swPrecache = require('sw-precache'); | ||
var gutil = require('gulp-util'); | ||
var ghslug = promisify(require('github-slug')); | ||
var glob = require('glob'); | ||
var template = require('gulp-template'); | ||
var crypto = require('crypto'); | ||
var gulp = require('gulp'); | ||
var ghslug = promisify(require('github-slug')); | ||
|
||
module.exports = promisify(function(config, callback) { | ||
var rootDir = config.rootDir || './'; | ||
|
@@ -40,7 +42,7 @@ module.exports = promisify(function(config, callback) { | |
|
||
var fileGlobs = config.fileGlobs || ['**/*']; | ||
|
||
// Remove the existing service worker, if any, so sw-precache doesn't include | ||
// Remove the existing service worker, if any, so offliner doesn't include | ||
// it in the list of files to cache. | ||
try { | ||
fs.unlinkSync(path.join(rootDir, 'offline-worker.js')); | ||
|
@@ -59,29 +61,49 @@ module.exports = promisify(function(config, callback) { | |
return ''; | ||
} | ||
}).then(function(cacheId) { | ||
var staticFileGlobs = fileGlobs.map(function(v) { | ||
return path.join(rootDir, v) | ||
}); | ||
var absoluteGlobs = | ||
fileGlobs.map(function (v) { return path.join(rootDir, v); }); | ||
var files = flatGlobs(absoluteGlobs); | ||
var filesAndHashes = getFilesAndHashes(files, rootDir); | ||
var replacements = { resources: filesAndHashes, name: cacheId }; | ||
|
||
var stream = gulp.src([__dirname + '/../templates/app/offline-worker.js']) | ||
.pipe(template(replacements)) | ||
.pipe(conflict(rootDir)) | ||
.pipe(gulp.dest(rootDir)); | ||
|
||
staticFileGlobs.forEach(function(globPattern) { | ||
glob.sync(globPattern.replace(path.sep, '/')).forEach(function(file) { | ||
var stat = fs.statSync(file); | ||
stream.on('finish', function () { callback(); }); | ||
stream.on('error', function (e) { callback(e); }); | ||
}); | ||
|
||
if (stat.isFile() && stat.size > 2 * 1024 * 1024 && staticFileGlobs.indexOf(file) === -1) { | ||
gutil.log(gutil.colors.red.bold(file + ' is bigger than 2 MiB. Are you sure you want to cache it? To suppress this warning, explicitly include the file in the fileGlobs list.')); | ||
} | ||
function flatGlobs(fileGlobs) { | ||
return Object.keys(fileGlobs.reduce(function (matchings, fileGlob) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: matchings -> matches |
||
fileGlob = fileGlob.replace(path.sep, '/'); | ||
glob.sync(fileGlob, { nodir: true }).forEach(function (m) { | ||
matchings[m] = m; | ||
}); | ||
}); | ||
return matchings; | ||
}, {})); | ||
} | ||
|
||
function getFilesAndHashes(files, stripPrefix) { | ||
return files | ||
.map(function (filepath) { | ||
var data = fs.readFileSync(filepath); | ||
var hash = getHash(data); | ||
return { | ||
filepath: filepath.replace(stripPrefix, function (match, offset) { | ||
return offset === 0 ? '' : match; | ||
}), | ||
hash: hash | ||
}; | ||
}); | ||
} | ||
|
||
function getHash(data) { | ||
var sha1 = crypto.createHash('sha1'); | ||
sha1.update(data); | ||
return sha1.digest('hex'); | ||
} | ||
|
||
swPrecache.write(path.join(rootDir, 'offline-worker.js'), { | ||
staticFileGlobs: staticFileGlobs, | ||
stripPrefix: rootDir, | ||
verbose: true, | ||
logger: gutil.log, | ||
importScripts: config.importScripts || [], | ||
cacheId: cacheId, | ||
ignoreUrlParametersMatching: config.ignoreUrlParametersMatching || [/./], | ||
maximumFileSizeToCacheInBytes: Infinity, | ||
}, callback); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
importScripts('./scripts/offliner/offliner.js'); | ||
importScripts('./scripts/offliner/middlewares.js'); | ||
|
||
var offliner = new off.Offliner("<%= name %>"); | ||
offliner.prefetch.use(off.fetchers.urls).resources([ | ||
<% resources.forEach(function (resource) { | ||
%> '<%= resource.filepath %>', /* <%= resource.hash %> */ | ||
<% }); %> | ||
]); | ||
|
||
offliner.fetch | ||
.use(off.sources.cache) | ||
.use(off.sources.network) | ||
.orFail(); | ||
|
||
offliner.update | ||
.use(off.updaters.reinstall); | ||
|
||
offliner.standalone(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +1,32 @@ | ||
function updateFound() { | ||
var installingWorker = this.installing; | ||
(function (global) { | ||
'use strict'; | ||
|
||
// Wait for the new service worker to be installed before prompting to update. | ||
installingWorker.addEventListener('statechange', function() { | ||
switch (installingWorker.state) { | ||
case 'installed': | ||
// Only show the prompt if there is currently a controller so it is not | ||
// shown on first load. | ||
if (navigator.serviceWorker.controller && | ||
window.confirm('An updated version of this page is available, would you like to update?')) { | ||
window.location.reload(); | ||
return; | ||
} | ||
break; | ||
|
||
case 'redundant': | ||
console.error('The installing service worker became redundant.'); | ||
break; | ||
} | ||
}); | ||
} | ||
if ('serviceWorker' in navigator) { | ||
var script = document.createElement('SCRIPT'); | ||
script.src = 'scripts/offliner/offliner-client.js'; | ||
script.dataset.worker = 'offline-worker.js'; | ||
script.onload = function () { | ||
var off = global.off.restore(); | ||
var isActivationDelayed = false; | ||
|
||
if ('serviceWorker' in navigator) { | ||
navigator.serviceWorker.register('offline-worker.js').then(function(registration) { | ||
console.log('offline worker registered'); | ||
registration.addEventListener('updatefound', updateFound); | ||
}); | ||
} | ||
off.on('activationPending', function () { | ||
if (confirm('An updated version of this page is available, would you like to update?')) { | ||
off.activate().then(function () { window.location.reload(); }); | ||
} | ||
else if (!isActivationDelayed) { | ||
global.addEventListener('beforeunload', function () { | ||
off.activate(); | ||
}); | ||
isActivationDelayed = true; | ||
} | ||
}); | ||
off.install().then(function () { | ||
console.log('offline worker registered'); | ||
}); | ||
}; | ||
document.addEventListener('DOMContentLoaded', function onBody() { | ||
document.removeEventListener('DOMContentLoaded', onBody); | ||
document.body.appendChild(script); | ||
}); | ||
} | ||
}(this)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
|
||
self.off.sources.cache = function (request, activeCache) { | ||
return activeCache.match(request).then(function (response) { | ||
return response ? Promise.resolve(response) : Promise.reject(); | ||
}); | ||
}; | ||
self.off.sources.network = function (request) { | ||
return fetch(request); | ||
}; | ||
|
||
self.off.fetchers.urls = { | ||
|
||
type: 'url', | ||
|
||
normalize: function (resource) { | ||
return { type: this.type, url: resource }; | ||
}, | ||
|
||
prefetch: function (resources, cache) { | ||
return Promise.all(resources.map(function (resource) { | ||
var bustedUrl = resource.url + '?__b=' + Date.now(); | ||
var request = new Request(bustedUrl, { mode: 'no-cors' }); | ||
return fetch(request).then(function (response) { | ||
var url = new URL(request.url, location); | ||
if (url.pathname.match(/\/index\.html?$/)) { | ||
cache.put('/', response.clone()); | ||
} | ||
cache.put(resource.url, response); | ||
}); | ||
})); | ||
} | ||
}; | ||
|
||
self.off.updaters.reinstall = { | ||
check: function () { | ||
return Promise.resolve('v' + Date().toString()); | ||
}, | ||
|
||
isNewVersion: function () { | ||
return this.flags.isCalledFromInstall; | ||
}, | ||
|
||
evolve: function (previousCache, newCache, reinstall) { | ||
return reinstall(); | ||
} | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note that there's no line width restriction for this codebase. Statements like this are welcome to live on one line and exceed 80 columns:
(That said, it's also ok to wrap lines; do whatever feels most readable!)