build.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. const fs = require('fs');
  2. const { join, normalize, resolve } = require('path');
  3. const { totalist } = require('totalist/sync');
  4. const { parse } = require('@polka/url');
  5. const { lookup } = require('mrmime');
  6. const noop = () => {};
  7. function isMatch(uri, arr) {
  8. for (let i=0; i < arr.length; i++) {
  9. if (arr[i].test(uri)) return true;
  10. }
  11. }
  12. function toAssume(uri, extns) {
  13. let i=0, x, len=uri.length - 1;
  14. if (uri.charCodeAt(len) === 47) {
  15. uri = uri.substring(0, len);
  16. }
  17. let arr=[], tmp=`${uri}/index`;
  18. for (; i < extns.length; i++) {
  19. x = extns[i] ? `.${extns[i]}` : '';
  20. if (uri) arr.push(uri + x);
  21. arr.push(tmp + x);
  22. }
  23. return arr;
  24. }
  25. function viaCache(cache, uri, extns) {
  26. let i=0, data, arr=toAssume(uri, extns);
  27. for (; i < arr.length; i++) {
  28. if (data = cache[arr[i]]) return data;
  29. }
  30. }
  31. function viaLocal(dir, isEtag, uri, extns) {
  32. let i=0, arr=toAssume(uri, extns);
  33. let abs, stats, name, headers;
  34. for (; i < arr.length; i++) {
  35. abs = normalize(join(dir, name=arr[i]));
  36. if (abs.startsWith(dir) && fs.existsSync(abs)) {
  37. stats = fs.statSync(abs);
  38. if (stats.isDirectory()) continue;
  39. headers = toHeaders(name, stats, isEtag);
  40. headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
  41. return { abs, stats, headers };
  42. }
  43. }
  44. }
  45. function is404(req, res) {
  46. return (res.statusCode=404,res.end());
  47. }
  48. function send(req, res, file, stats, headers) {
  49. let code=200, tmp, opts={};
  50. headers = { ...headers };
  51. for (let key in headers) {
  52. tmp = res.getHeader(key);
  53. if (tmp) headers[key] = tmp;
  54. }
  55. if (tmp = res.getHeader('content-type')) {
  56. headers['Content-Type'] = tmp;
  57. }
  58. if (req.headers.range) {
  59. code = 206;
  60. let [x, y] = req.headers.range.replace('bytes=', '').split('-');
  61. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  62. let start = opts.start = parseInt(x, 10) || 0;
  63. if (end >= stats.size) {
  64. end = stats.size - 1;
  65. }
  66. if (start >= stats.size) {
  67. res.setHeader('Content-Range', `bytes */${stats.size}`);
  68. res.statusCode = 416;
  69. return res.end();
  70. }
  71. headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
  72. headers['Content-Length'] = (end - start + 1);
  73. headers['Accept-Ranges'] = 'bytes';
  74. }
  75. res.writeHead(code, headers);
  76. fs.createReadStream(file, opts).pipe(res);
  77. }
  78. const ENCODING = {
  79. '.br': 'br',
  80. '.gz': 'gzip',
  81. };
  82. function toHeaders(name, stats, isEtag) {
  83. let enc = ENCODING[name.slice(-3)];
  84. let ctype = lookup(name.slice(0, enc && -3)) || '';
  85. if (ctype === 'text/html') ctype += ';charset=utf-8';
  86. let headers = {
  87. 'Content-Length': stats.size,
  88. 'Content-Type': ctype,
  89. 'Last-Modified': stats.mtime.toUTCString(),
  90. };
  91. if (enc) headers['Content-Encoding'] = enc;
  92. if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  93. return headers;
  94. }
  95. module.exports = function (dir, opts={}) {
  96. dir = resolve(dir || '.');
  97. let isNotFound = opts.onNoMatch || is404;
  98. let setHeaders = opts.setHeaders || noop;
  99. let extensions = opts.extensions || ['html', 'htm'];
  100. let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
  101. let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
  102. const FILES = {};
  103. let fallback = '/';
  104. let isEtag = !!opts.etag;
  105. let isSPA = !!opts.single;
  106. if (typeof opts.single === 'string') {
  107. let idx = opts.single.lastIndexOf('.');
  108. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  109. }
  110. let ignores = [];
  111. if (opts.ignores !== false) {
  112. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
  113. if (opts.dotfiles) ignores.push(/\/\.\w/);
  114. else ignores.push(/\/\.well-known/);
  115. [].concat(opts.ignores || []).forEach(x => {
  116. ignores.push(new RegExp(x, 'i'));
  117. });
  118. }
  119. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  120. if (cc && opts.immutable) cc += ',immutable';
  121. else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
  122. if (!opts.dev) {
  123. totalist(dir, (name, abs, stats) => {
  124. if (/\.well-known[\\+\/]/.test(name)) {} // keep
  125. else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  126. let headers = toHeaders(name, stats, isEtag);
  127. if (cc) headers['Cache-Control'] = cc;
  128. FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
  129. });
  130. }
  131. let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
  132. return function (req, res, next) {
  133. let extns = [''];
  134. let pathname = parse(req).pathname;
  135. let val = req.headers['accept-encoding'] || '';
  136. if (gzips && val.includes('gzip')) extns.unshift(...gzips);
  137. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  138. extns.push(...extensions); // [...br, ...gz, orig, ...exts]
  139. if (pathname.indexOf('%') !== -1) {
  140. try { pathname = decodeURI(pathname) }
  141. catch (err) { /* malform uri */ }
  142. }
  143. let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
  144. if (!data) return next ? next() : isNotFound(req, res);
  145. if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
  146. res.writeHead(304);
  147. return res.end();
  148. }
  149. if (gzips || brots) {
  150. res.setHeader('Vary', 'Accept-Encoding');
  151. }
  152. setHeaders(res, pathname, data.stats);
  153. send(req, res, data.abs, data.stats, data.headers);
  154. };
  155. }