Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 97 additions & 91 deletions cjs/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
'use strict';
const {
createReadStream, stat, mkdir, readFile, unlink, existsSync, writeFileSync, watchFile, unwatchFile
createReadStream, mkdir, unlink, existsSync, writeFileSync, watch
} = require('fs');
const {tmpdir} = require('os');
const {dirname, extname, join, resolve} = require('path');

const ucompress = (m => m.__esModule ? /* istanbul ignore next */ m.default : /* istanbul ignore next */ m)(require('ucompress'));

const {parse} = JSON;
const json = (m => m.__esModule ? /* istanbul ignore next */ m.default : /* istanbul ignore next */ m)(require('./json.js'));
const stat = (m => m.__esModule ? /* istanbul ignore next */ m.default : /* istanbul ignore next */ m)(require('./stat.js'));

const {compressed} = ucompress;

const getPath = source => (source[0] === '/' ? source : resolve(source));
Expand All @@ -18,15 +20,12 @@ const internalServerError = res => {
res.end();
};

const readAndServe = (res, asset, IfNoneMatch) => {
readFile(asset + '.json', (err, data) => {
const readAndServe = (res, asset, cacheTimeout, IfNoneMatch) =>
json(asset, cacheTimeout).then(
headers => serveFile(res, asset, headers, IfNoneMatch),
/* istanbul ignore next */
if (err)
internalServerError(res);
else
serveFile(res, asset, parse(data), IfNoneMatch);
});
};
() => internalServerError(res)
);

const serveFile = (res, asset, headers, IfNoneMatch) => {
if (headers.ETag === IfNoneMatch) {
Expand All @@ -42,99 +41,106 @@ const streamFile = (res, asset, headers) => {
createReadStream(asset).pipe(res);
};

module.exports = ({source, dest, headers}) => {
module.exports = ({source, dest, headers, cacheTimeout: CT}) => {
const SOURCE = getPath(source);
const DEST = dest ? getPath(dest) : join(tmpdir(), 'ucdn');
const options = {createFiles: true, headers};
return (req, res, next) => {
const path = req.url.replace(/\?.*$/, '');
const original = SOURCE + path;
stat(original, (err, stats) => {
if (err || !stats.isFile()) {
stat(original, CT).then(
({lastModified, size}) => {
if (path === '/favicon.ico')
streamFile(res, original, {
'Content-Length': size,
'Content-Type': 'image/vnd.microsoft.icon',
...headers
});
else {
let asset = DEST + path;
let compression = '';
const {
['accept-encoding']: AcceptEncoding,
['if-none-match']: IfNoneMatch,
['if-modified-since']: IfModifiedSince
} = req.headers;
if (compressed.has(extname(path).toLowerCase())) {
switch (true) {
/* istanbul ignore next */
case /\bbr\b/.test(AcceptEncoding):
compression = '.br';
break;
case /\bgzip\b/.test(AcceptEncoding):
compression = '.gzip';
break;
/* istanbul ignore next */
case /\bdeflate\b/.test(AcceptEncoding):
compression = '.deflate';
break;
}
asset += compression;
}
const create = () => {
const {length} = compression;
const compress = length ? asset.slice(0, -length) : asset;
const waitForIt = compress + '.wait';
mkdir(dirname(waitForIt), {recursive: true}, err => {
/* istanbul ignore if */
if (err)
internalServerError(res);
else if (existsSync(waitForIt))
watch(waitForIt, andClose).on(
'close',
() => readAndServe(res, asset, CT, IfNoneMatch)
);
else {
try {
writeFileSync(waitForIt, path);
ucompress(original, compress, options)
.then(
() => {
unlink(waitForIt, err => {
/* istanbul ignore if */
if (err)
internalServerError(res);
else
readAndServe(res, asset, CT, IfNoneMatch);
});
},
/* istanbul ignore next */
() => unlink(waitForIt, () => internalServerError(res))
);
}
catch (o_O) {
/* istanbul ignore next */
internalServerError(res);
}
}
});
};
json(asset, CT).then(
headers => {
if (lastModified === IfModifiedSince)
serveFile(res, asset, headers, IfNoneMatch);
else
create();
},
create
);
}
},
() => {
if (next)
next();
else {
res.writeHead(404);
res.end();
}
}
else if (path === '/favicon.ico')
streamFile(res, original, {
'Content-Length': stats.size,
'Content-Type': 'image/vnd.microsoft.icon',
...headers
});
else {
let asset = DEST + path;
let compression = '';
const {
['accept-encoding']: AcceptEncoding,
['if-none-match']: IfNoneMatch,
['if-modified-since']: IfModifiedSince
} = req.headers;
if (compressed.has(extname(path).toLowerCase())) {
switch (true) {
/* istanbul ignore next */
case /\bbr\b/.test(AcceptEncoding):
compression = '.br';
break;
case /\bgzip\b/.test(AcceptEncoding):
compression = '.gzip';
break;
/* istanbul ignore next */
case /\bdeflate\b/.test(AcceptEncoding):
compression = '.deflate';
break;
}
asset += compression;
}
readFile(asset + '.json', (err, data) => {
// if there was no error, be sure the source file is still the same
if (!err) {
if (new Date(stats.mtimeMs).toUTCString() === IfModifiedSince) {
serveFile(res, asset, parse(data), IfNoneMatch);
return;
}
}
// if the file was modified, re-optimize it, assuming it changed too
const {length} = compression;
const compress = length ? asset.slice(0, -length) : asset;
const waitForIt = compress + '.wait';
mkdir(dirname(waitForIt), {recursive: true}, err => {
/* istanbul ignore next */
if (err)
internalServerError(res);
else if (existsSync(waitForIt))
watchFile(waitForIt, () => {
unwatchFile(waitForIt);
readAndServe(res, asset, IfNoneMatch);
});
else {
try {
writeFileSync(waitForIt, path);
ucompress(original, compress, options)
.then(
() => {
unlink(waitForIt, err => {
/* istanbul ignore next */
if (err)
internalServerError(res);
else
readAndServe(res, asset, IfNoneMatch);
});
},
/* istanbul ignore next */
() => unlink(waitForIt, () => internalServerError(res))
);
}
catch (o_O) {
/* istanbul ignore next */
internalServerError(res);
}
}
});
});
}
});
);
};
};

function andClose() {
this.close();
}
29 changes: 29 additions & 0 deletions cjs/json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict';
const {readFile} = require('fs');

const umap = (m => m.__esModule ? /* istanbul ignore next */ m.default : /* istanbul ignore next */ m)(require('umap'));

const {parse} = JSON;

const _ = new Map;
const $ = umap(_);

const clear = asset => {
_.delete(asset);
};

module.exports = (asset, timeout = 1000) => (
$.get(asset) ||
$.set(asset, new Promise((res, rej) => {
readFile(asset + '.json', (err, data) => {
if (err) {
_.delete(asset);
rej();
}
else {
res(parse(data));
setTimeout(clear, timeout, asset);
}
});
}))
);
30 changes: 30 additions & 0 deletions cjs/stat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use strict';
const {stat} = require('fs');

const umap = (m => m.__esModule ? /* istanbul ignore next */ m.default : /* istanbul ignore next */ m)(require('umap'));

const _ = new Map;
const $ = umap(_);

const clear = asset => {
_.delete(asset);
};

module.exports = (asset, timeout = 1000) => (
$.get(asset) ||
$.set(asset, new Promise((res, rej) => {
stat(asset, (err, stats) => {
if (err || !stats.isFile()) {
_.delete(asset);
rej();
}
else {
setTimeout(clear, timeout, asset);
res({
lastModified: new Date(stats.mtimeMs).toUTCString(),
size: stats.size
});
}
});
}))
);
Loading