serve-static.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. // src/serve-static.ts
  20. var serve_static_exports = {};
  21. __export(serve_static_exports, {
  22. serveStatic: () => serveStatic
  23. });
  24. module.exports = __toCommonJS(serve_static_exports);
  25. var import_mime = require("hono/utils/mime");
  26. var import_node_fs = require("fs");
  27. var import_node_path = require("path");
  28. var import_node_process = require("process");
  29. var import_node_stream = require("stream");
  30. var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
  31. var ENCODINGS = {
  32. br: ".br",
  33. zstd: ".zst",
  34. gzip: ".gz"
  35. };
  36. var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
  37. var pr54206Applied = () => {
  38. const [major, minor] = import_node_process.versions.node.split(".").map((component) => parseInt(component));
  39. return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
  40. };
  41. var useReadableToWeb = pr54206Applied();
  42. var createStreamBody = (stream) => {
  43. if (useReadableToWeb) {
  44. return import_node_stream.Readable.toWeb(stream);
  45. }
  46. const body = new ReadableStream({
  47. start(controller) {
  48. stream.on("data", (chunk) => {
  49. controller.enqueue(chunk);
  50. });
  51. stream.on("error", (err) => {
  52. controller.error(err);
  53. });
  54. stream.on("end", () => {
  55. controller.close();
  56. });
  57. },
  58. cancel() {
  59. stream.destroy();
  60. }
  61. });
  62. return body;
  63. };
  64. var getStats = (path) => {
  65. let stats;
  66. try {
  67. stats = (0, import_node_fs.statSync)(path);
  68. } catch {
  69. }
  70. return stats;
  71. };
  72. var tryDecode = (str, decoder) => {
  73. try {
  74. return decoder(str);
  75. } catch {
  76. return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
  77. try {
  78. return decoder(match);
  79. } catch {
  80. return match;
  81. }
  82. });
  83. }
  84. };
  85. var tryDecodeURI = (str) => tryDecode(str, decodeURI);
  86. var serveStatic = (options = { root: "" }) => {
  87. const root = options.root || "";
  88. const optionPath = options.path;
  89. if (root !== "" && !(0, import_node_fs.existsSync)(root)) {
  90. console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
  91. }
  92. return async (c, next) => {
  93. if (c.finalized) {
  94. return next();
  95. }
  96. let filename;
  97. if (optionPath) {
  98. filename = optionPath;
  99. } else {
  100. try {
  101. filename = tryDecodeURI(c.req.path);
  102. if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(filename)) {
  103. throw new Error();
  104. }
  105. } catch {
  106. await options.onNotFound?.(c.req.path, c);
  107. return next();
  108. }
  109. }
  110. let path = (0, import_node_path.join)(
  111. root,
  112. !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename
  113. );
  114. let stats = getStats(path);
  115. if (stats && stats.isDirectory()) {
  116. const indexFile = options.index ?? "index.html";
  117. path = (0, import_node_path.join)(path, indexFile);
  118. stats = getStats(path);
  119. }
  120. if (!stats) {
  121. await options.onNotFound?.(path, c);
  122. return next();
  123. }
  124. const mimeType = (0, import_mime.getMimeType)(path);
  125. c.header("Content-Type", mimeType || "application/octet-stream");
  126. if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
  127. const acceptEncodingSet = new Set(
  128. c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
  129. );
  130. for (const encoding of ENCODINGS_ORDERED_KEYS) {
  131. if (!acceptEncodingSet.has(encoding)) {
  132. continue;
  133. }
  134. const precompressedStats = getStats(path + ENCODINGS[encoding]);
  135. if (precompressedStats) {
  136. c.header("Content-Encoding", encoding);
  137. c.header("Vary", "Accept-Encoding", { append: true });
  138. stats = precompressedStats;
  139. path = path + ENCODINGS[encoding];
  140. break;
  141. }
  142. }
  143. }
  144. let result;
  145. const size = stats.size;
  146. const range = c.req.header("range") || "";
  147. if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
  148. c.header("Content-Length", size.toString());
  149. c.status(200);
  150. result = c.body(null);
  151. } else if (!range) {
  152. c.header("Content-Length", size.toString());
  153. result = c.body(createStreamBody((0, import_node_fs.createReadStream)(path)), 200);
  154. } else {
  155. c.header("Accept-Ranges", "bytes");
  156. c.header("Date", stats.birthtime.toUTCString());
  157. const parts = range.replace(/bytes=/, "").split("-", 2);
  158. const start = parseInt(parts[0], 10) || 0;
  159. let end = parseInt(parts[1], 10) || size - 1;
  160. if (size < end - start + 1) {
  161. end = size - 1;
  162. }
  163. const chunksize = end - start + 1;
  164. const stream = (0, import_node_fs.createReadStream)(path, { start, end });
  165. c.header("Content-Length", chunksize.toString());
  166. c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
  167. result = c.body(createStreamBody(stream), 206);
  168. }
  169. await options.onFound?.(path, c);
  170. return result;
  171. };
  172. };
  173. // Annotate the CommonJS export names for ESM import in node:
  174. 0 && (module.exports = {
  175. serveStatic
  176. });