Last active
July 28, 2016 15:14
-
-
Save nlwillia/70303c2ccdb69ad3661d to your computer and use it in GitHub Desktop.
SystemJS translate hook that caches transpilation results of sources that haven't changed in IndexedDB storage.
This file contains hidden or 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
/** | |
* SystemJS translate hook that caches transpilation results of sources that haven't changed in IndexedDB storage. | |
* In Chrome dev tools the cache is easily managed under Resources > IndexedDB > jspm | |
* There's a global dependency on Dexie.js (ex: //npmcdn.com/[email protected]/dist/dexie.min.js) | |
* Adapted from https://gist.github.com/ineentho/3ccaaec164e418f685d7 | |
*/ | |
;(function(){ | |
var db = new Dexie("jspm"); | |
db.version(1).stores({ files: "&url,format,hash,contents" }); | |
db.open(); | |
var log = console.log.bind(console); | |
System.originalTranslate = System.translate; | |
System.translate = function (load) { | |
if (!load.metadata.deps) { | |
load.metadata.deps = []; // avoid https://github.com/systemjs/systemjs/pull/1158 | |
} | |
function hash(str) { | |
// Source: http://stackoverflow.com/a/7616484/502126 | |
var hash = 0, i, chr, len | |
if (str.length === 0) return hash | |
for (i = 0, len = str.length; i < len; i++) { | |
chr = str.charCodeAt(i) | |
hash = ((hash << 5) - hash) + chr | |
hash |= 0 | |
} | |
return hash.toString() | |
} | |
var file = {url:load.address, hash:hash(load.source)}; | |
var loader = this; | |
return db.files.where('url').equals(file.url).first().then(function(cached) { | |
if (!cached || cached.hash != file.hash) { | |
return System.originalTranslate.apply(loader, [load]).then(function(translated) { | |
file.format = load.metadata.format; | |
file.contents = translated; | |
return (cached ? db.files.delete(file.url) : Promise.resolve()) | |
.then(db.files.add(file)) | |
.then(function() { | |
return translated; | |
}).catch(log); | |
}); | |
} else { | |
load.metadata.format = cached.format || undefined; | |
return cached.contents; | |
} | |
}).catch(log); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment