build.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. const fs = require('fs');
  2. const { join, normalize, resolve } = require('path');
  3. const { parse } = require('@polka/url');
  4. const list = require('totalist/sync');
  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 (start >= stats.size || end >= stats.size) {
  64. res.setHeader('Content-Range', `bytes */${stats.size}`);
  65. res.statusCode = 416;
  66. return res.end();
  67. }
  68. headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
  69. headers['Content-Length'] = (end - start + 1);
  70. headers['Accept-Ranges'] = 'bytes';
  71. }
  72. res.writeHead(code, headers);
  73. fs.createReadStream(file, opts).pipe(res);
  74. }
  75. const ENCODING = {
  76. '.br': 'br',
  77. '.gz': 'gzip',
  78. };
  79. function toHeaders(name, stats, isEtag) {
  80. let enc = ENCODING[name.slice(-3)];
  81. let ctype = lookup(name.slice(0, enc && -3)) || '';
  82. if (ctype === 'text/html') ctype += ';charset=utf-8';
  83. let headers = {
  84. 'Content-Length': stats.size,
  85. 'Content-Type': ctype,
  86. 'Last-Modified': stats.mtime.toUTCString(),
  87. };
  88. if (enc) headers['Content-Encoding'] = enc;
  89. if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  90. return headers;
  91. }
  92. module.exports = function (dir, opts={}) {
  93. dir = resolve(dir || '.');
  94. let isNotFound = opts.onNoMatch || is404;
  95. let setHeaders = opts.setHeaders || noop;
  96. let extensions = opts.extensions || ['html', 'htm'];
  97. let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
  98. let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
  99. const FILES = {};
  100. let fallback = '/';
  101. let isEtag = !!opts.etag;
  102. let isSPA = !!opts.single;
  103. if (typeof opts.single === 'string') {
  104. let idx = opts.single.lastIndexOf('.');
  105. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  106. }
  107. let ignores = [];
  108. if (opts.ignores !== false) {
  109. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
  110. if (opts.dotfiles) ignores.push(/\/\.\w/);
  111. else ignores.push(/\/\.well-known/);
  112. [].concat(opts.ignores || []).forEach(x => {
  113. ignores.push(new RegExp(x, 'i'));
  114. });
  115. }
  116. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  117. if (cc && opts.immutable) cc += ',immutable';
  118. else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
  119. if (!opts.dev) {
  120. list(dir, (name, abs, stats) => {
  121. if (/\.well-known[\\+\/]/.test(name)) {} // keep
  122. else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  123. let headers = toHeaders(name, stats, isEtag);
  124. if (cc) headers['Cache-Control'] = cc;
  125. FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
  126. });
  127. }
  128. let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
  129. return function (req, res, next) {
  130. let extns = [''];
  131. let pathname = parse(req).pathname;
  132. let val = req.headers['accept-encoding'] || '';
  133. if (gzips && val.includes('gzip')) extns.unshift(...gzips);
  134. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  135. extns.push(...extensions); // [...br, ...gz, orig, ...exts]
  136. if (pathname.indexOf('%') !== -1) {
  137. try { pathname = decodeURIComponent(pathname) }
  138. catch (err) { /* malform uri */ }
  139. }
  140. let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
  141. if (!data) return next ? next() : isNotFound(req, res);
  142. if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
  143. res.writeHead(304);
  144. return res.end();
  145. }
  146. if (gzips || brots) {
  147. res.setHeader('Vary', 'Accept-Encoding');
  148. }
  149. setHeaders(res, pathname, data.stats);
  150. send(req, res, data.abs, data.stats, data.headers);
  151. };
  152. }