index.cjs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  9. var __export = (target, all) => {
  10. for (var name in all)
  11. __defProp(target, name, { get: all[name], enumerable: true });
  12. };
  13. var __copyProps = (to, from, except, desc) => {
  14. if (from && typeof from === "object" || typeof from === "function") {
  15. for (let key of __getOwnPropNames(from))
  16. if (!__hasOwnProp.call(to, key) && key !== except)
  17. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  18. }
  19. return to;
  20. };
  21. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  22. // If the importer is in node compatibility mode or this is not an ESM
  23. // file that has been converted to a CommonJS file using a Babel-
  24. // compatible transform (i.e. "__esModule" has not been set), then set
  25. // "default" to the CommonJS "module.exports" for node compatibility.
  26. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  27. mod
  28. ));
  29. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  30. // src/index.js
  31. var index_exports = {};
  32. __export(index_exports, {
  33. BodyParser: () => BodyParser,
  34. CHARACTER_ENCODING_LIST: () => CHARACTER_ENCODING_LIST,
  35. CookiesParser: () => CookiesParser,
  36. DataSender: () => DataSender,
  37. EXPOSED_ERROR_PROPERTIES: () => EXPOSED_ERROR_PROPERTIES,
  38. ErrorSender: () => ErrorSender,
  39. HookInvoker: () => HookInvoker,
  40. HookRegistry: () => HookRegistry,
  41. HookType: () => HookType,
  42. HttpMethod: () => HttpMethod,
  43. METHODS_WITH_BODY: () => METHODS_WITH_BODY,
  44. QueryParser: () => QueryParser,
  45. RequestContext: () => RequestContext,
  46. RequestParser: () => RequestParser,
  47. Route: () => Route,
  48. RouteRegistry: () => RouteRegistry,
  49. RouterOptions: () => RouterOptions,
  50. TrieRouter: () => TrieRouter,
  51. UNPARSABLE_MEDIA_TYPES: () => UNPARSABLE_MEDIA_TYPES,
  52. createCookiesString: () => createCookiesString,
  53. createDebugger: () => createDebugger,
  54. createError: () => createError,
  55. createRequestMock: () => createRequestMock,
  56. createResponseMock: () => createResponseMock,
  57. fetchRequestBody: () => fetchRequestBody,
  58. getRequestPathname: () => getRequestPathname,
  59. isPromise: () => isPromise,
  60. isReadableStream: () => isReadableStream,
  61. isResponseSent: () => isResponseSent,
  62. isWritableStream: () => isWritableStream,
  63. parseContentType: () => parseContentType,
  64. parseCookies: () => parseCookies,
  65. parseJsonBody: () => parseJsonBody,
  66. toCamelCase: () => toCamelCase
  67. });
  68. module.exports = __toCommonJS(index_exports);
  69. // src/route.js
  70. var import_js_format14 = require("@e22m4u/js-format");
  71. // src/hooks/hook-invoker.js
  72. var import_js_format13 = require("@e22m4u/js-format");
  73. // src/utils/is-promise.js
  74. function isPromise(value) {
  75. if (!value) return false;
  76. if (typeof value !== "object") return false;
  77. return typeof value.then === "function";
  78. }
  79. __name(isPromise, "isPromise");
  80. // src/utils/create-error.js
  81. var import_js_format = require("@e22m4u/js-format");
  82. var import_js_format2 = require("@e22m4u/js-format");
  83. function createError(errorCtor, message, ...args) {
  84. if (typeof errorCtor !== "function")
  85. throw new import_js_format2.Errorf(
  86. 'The first argument of "createError" should be a constructor, but %v was given.',
  87. errorCtor
  88. );
  89. if (message != null && typeof message !== "string")
  90. throw new import_js_format2.Errorf(
  91. 'The second argument of "createError" should be a String, but %v was given.',
  92. message
  93. );
  94. if (message == null) return new errorCtor();
  95. const interpolatedMessage = (0, import_js_format.format)(message, ...args);
  96. return new errorCtor(interpolatedMessage);
  97. }
  98. __name(createError, "createError");
  99. // src/utils/parse-cookies.js
  100. var import_js_format3 = require("@e22m4u/js-format");
  101. function parseCookies(input) {
  102. if (typeof input !== "string")
  103. throw new import_js_format3.Errorf(
  104. 'The first parameter of "parseCookies" should be a String, but %v was given.',
  105. input
  106. );
  107. return input.split(";").filter((v) => v !== "").map((v) => v.split("=")).reduce((cookies, tuple) => {
  108. const key = decodeURIComponent(tuple[0]).trim();
  109. const value = tuple[1] !== void 0 ? decodeURIComponent(tuple[1]).trim() : "";
  110. cookies[key] = value;
  111. return cookies;
  112. }, {});
  113. }
  114. __name(parseCookies, "parseCookies");
  115. // src/utils/to-camel-case.js
  116. var import_js_format4 = require("@e22m4u/js-format");
  117. function toCamelCase(input) {
  118. if (typeof input !== "string")
  119. throw new import_js_format4.Errorf(
  120. 'The first argument of "toCamelCase" should be a String, but %v was given.',
  121. input
  122. );
  123. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  124. }
  125. __name(toCamelCase, "toCamelCase");
  126. // src/utils/create-debugger.js
  127. var import_debug = __toESM(require("debug"), 1);
  128. var import_js_format5 = require("@e22m4u/js-format");
  129. function createDebugger(name) {
  130. if (typeof name !== "string")
  131. throw new import_js_format5.Errorf(
  132. 'The first argument of "createDebugger" should be a String, but %v was given.',
  133. name
  134. );
  135. const debug = (0, import_debug.default)(`jsTrieRouter:${name}`);
  136. return function(message, ...args) {
  137. const interpolatedMessage = (0, import_js_format5.format)(message, ...args);
  138. return debug(interpolatedMessage);
  139. };
  140. }
  141. __name(createDebugger, "createDebugger");
  142. // src/utils/is-response-sent.js
  143. var import_js_format6 = require("@e22m4u/js-format");
  144. function isResponseSent(res) {
  145. if (!res || typeof res !== "object" || Array.isArray(res) || typeof res.headersSent !== "boolean") {
  146. throw new import_js_format6.Errorf(
  147. 'The first argument of "isResponseSent" should be an instance of ServerResponse, but %v was given.',
  148. res
  149. );
  150. }
  151. return res.headersSent;
  152. }
  153. __name(isResponseSent, "isResponseSent");
  154. // src/utils/is-readable-stream.js
  155. function isReadableStream(value) {
  156. if (!value || typeof value !== "object") return false;
  157. return typeof value.pipe === "function";
  158. }
  159. __name(isReadableStream, "isReadableStream");
  160. // src/utils/parse-content-type.js
  161. var import_js_format7 = require("@e22m4u/js-format");
  162. function parseContentType(input) {
  163. if (typeof input !== "string")
  164. throw new import_js_format7.Errorf(
  165. 'The parameter "input" of "parseContentType" should be a String, but %v was given.',
  166. input
  167. );
  168. const res = { mediaType: void 0, charset: void 0, boundary: void 0 };
  169. const re = /^\s*([^\s;/]+\/[^\s;/]+)(?:;\s*charset=([^\s;]+))?(?:;\s*boundary=([^\s;]+))?.*$/i;
  170. const matches = re.exec(input);
  171. if (matches && matches[1]) {
  172. res.mediaType = matches[1];
  173. if (matches[2]) res.charset = matches[2];
  174. if (matches[3]) res.boundary = matches[3];
  175. }
  176. return res;
  177. }
  178. __name(parseContentType, "parseContentType");
  179. // src/utils/is-writable-stream.js
  180. function isWritableStream(value) {
  181. if (!value || typeof value !== "object") return false;
  182. return typeof value.end === "function";
  183. }
  184. __name(isWritableStream, "isWritableStream");
  185. // src/utils/fetch-request-body.js
  186. var import_http_errors = __toESM(require("http-errors"), 1);
  187. var import_http = require("http");
  188. var import_js_format8 = require("@e22m4u/js-format");
  189. var CHARACTER_ENCODING_LIST = [
  190. "ascii",
  191. "utf8",
  192. "utf-8",
  193. "utf16le",
  194. "utf-16le",
  195. "ucs2",
  196. "ucs-2",
  197. "latin1"
  198. ];
  199. function fetchRequestBody(req, bodyBytesLimit = 0) {
  200. if (!(req instanceof import_http.IncomingMessage))
  201. throw new import_js_format8.Errorf(
  202. 'The first parameter of "fetchRequestBody" should be an IncomingMessage instance, but %v was given.',
  203. req
  204. );
  205. if (typeof bodyBytesLimit !== "number")
  206. throw new import_js_format8.Errorf(
  207. 'The parameter "bodyBytesLimit" of "fetchRequestBody" should be a number, but %v was given.',
  208. bodyBytesLimit
  209. );
  210. return new Promise((resolve, reject) => {
  211. const contentLength = parseInt(req.headers["content-length"] || "0", 10);
  212. if (bodyBytesLimit && contentLength && contentLength > bodyBytesLimit)
  213. throw createError(
  214. import_http_errors.default.PayloadTooLarge,
  215. "Request body limit is %s bytes, but %s bytes given.",
  216. bodyBytesLimit,
  217. contentLength
  218. );
  219. let encoding = "utf-8";
  220. const contentType = req.headers["content-type"] || "";
  221. if (contentType) {
  222. const parsedContentType = parseContentType(contentType);
  223. if (parsedContentType && parsedContentType.charset) {
  224. encoding = parsedContentType.charset.toLowerCase();
  225. if (!CHARACTER_ENCODING_LIST.includes(encoding))
  226. throw createError(
  227. import_http_errors.default.UnsupportedMediaType,
  228. "Request encoding %v is not supported.",
  229. encoding
  230. );
  231. }
  232. }
  233. const data = [];
  234. let receivedLength = 0;
  235. const onData = /* @__PURE__ */ __name((chunk) => {
  236. receivedLength += chunk.length;
  237. if (bodyBytesLimit && receivedLength > bodyBytesLimit) {
  238. req.removeAllListeners();
  239. const error = createError(
  240. import_http_errors.default.PayloadTooLarge,
  241. "Request body limit is %v bytes, but %v bytes given.",
  242. bodyBytesLimit,
  243. receivedLength
  244. );
  245. reject(error);
  246. return;
  247. }
  248. data.push(chunk);
  249. }, "onData");
  250. const onEnd = /* @__PURE__ */ __name(() => {
  251. req.removeAllListeners();
  252. if (contentLength && contentLength !== receivedLength) {
  253. const error = createError(
  254. import_http_errors.default.BadRequest,
  255. 'Received bytes do not match the "content-length" header.'
  256. );
  257. reject(error);
  258. return;
  259. }
  260. const buffer = Buffer.concat(data);
  261. const body = buffer.toString(encoding);
  262. resolve(body || void 0);
  263. }, "onEnd");
  264. const onError = /* @__PURE__ */ __name((error) => {
  265. req.removeAllListeners();
  266. reject((0, import_http_errors.default)(400, error));
  267. }, "onError");
  268. req.on("data", onData);
  269. req.on("end", onEnd);
  270. req.on("error", onError);
  271. req.resume();
  272. });
  273. }
  274. __name(fetchRequestBody, "fetchRequestBody");
  275. // src/utils/create-request-mock.js
  276. var import_net = require("net");
  277. var import_tls = require("tls");
  278. var import_http2 = require("http");
  279. var import_querystring = __toESM(require("querystring"), 1);
  280. var import_js_format10 = require("@e22m4u/js-format");
  281. // src/utils/create-cookies-string.js
  282. var import_js_format9 = require("@e22m4u/js-format");
  283. function createCookiesString(data) {
  284. if (!data || typeof data !== "object" || Array.isArray(data))
  285. throw new import_js_format9.Errorf(
  286. 'The first parameter of "createCookiesString" should be an Object, but %v was given.',
  287. data
  288. );
  289. let cookies = "";
  290. for (const key in data) {
  291. if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
  292. const val = data[key];
  293. if (val == null) continue;
  294. cookies += `${key}=${val}; `;
  295. }
  296. return cookies.trim();
  297. }
  298. __name(createCookiesString, "createCookiesString");
  299. // src/utils/create-request-mock.js
  300. function createRequestMock(patch) {
  301. if (patch != null && typeof patch !== "object" || Array.isArray(patch)) {
  302. throw new import_js_format10.Errorf(
  303. 'The first parameter of "createRequestMock" should be an Object, but %v was given.',
  304. patch
  305. );
  306. }
  307. patch = patch || {};
  308. if (patch.host != null && typeof patch.host !== "string")
  309. throw new import_js_format10.Errorf(
  310. 'The parameter "host" of "createRequestMock" should be a String, but %v was given.',
  311. patch.host
  312. );
  313. if (patch.method != null && typeof patch.method !== "string")
  314. throw new import_js_format10.Errorf(
  315. 'The parameter "method" of "createRequestMock" should be a String, but %v was given.',
  316. patch.method
  317. );
  318. if (patch.secure != null && typeof patch.secure !== "boolean")
  319. throw new import_js_format10.Errorf(
  320. 'The parameter "secure" of "createRequestMock" should be a Boolean, but %v was given.',
  321. patch.secure
  322. );
  323. if (patch.path != null && typeof patch.path !== "string")
  324. throw new import_js_format10.Errorf(
  325. 'The parameter "path" of "createRequestMock" should be a String, but %v was given.',
  326. patch.path
  327. );
  328. if (patch.query != null && typeof patch.query !== "object" && typeof patch.query !== "string" || Array.isArray(patch.query)) {
  329. throw new import_js_format10.Errorf(
  330. 'The parameter "query" of "createRequestMock" should be a String or Object, but %v was given.',
  331. patch.query
  332. );
  333. }
  334. if (patch.cookies != null && typeof patch.cookies !== "string" && typeof patch.cookies !== "object" || Array.isArray(patch.cookies)) {
  335. throw new import_js_format10.Errorf(
  336. 'The parameter "cookies" of "createRequestMock" should be a String or Object, but %v was given.',
  337. patch.cookies
  338. );
  339. }
  340. if (patch.headers != null && typeof patch.headers !== "object" || Array.isArray(patch.headers)) {
  341. throw new import_js_format10.Errorf(
  342. 'The parameter "headers" of "createRequestMock" should be an Object, but %v was given.',
  343. patch.headers
  344. );
  345. }
  346. if (patch.stream != null && !isReadableStream(patch.stream))
  347. throw new import_js_format10.Errorf(
  348. 'The parameter "stream" of "createRequestMock" should be a Stream, but %v was given.',
  349. patch.stream
  350. );
  351. if (patch.encoding != null) {
  352. if (typeof patch.encoding !== "string")
  353. throw new import_js_format10.Errorf(
  354. 'The parameter "encoding" of "createRequestMock" should be a String, but %v was given.',
  355. patch.encoding
  356. );
  357. if (!CHARACTER_ENCODING_LIST.includes(patch.encoding))
  358. throw new import_js_format10.Errorf(
  359. "Character encoding %v is not supported.",
  360. patch.encoding
  361. );
  362. }
  363. if (patch.stream) {
  364. if (patch.secure != null)
  365. throw new import_js_format10.Errorf(
  366. 'The "createRequestMock" does not allow specifying the "stream" and "secure" options simultaneously.'
  367. );
  368. if (patch.body != null)
  369. throw new import_js_format10.Errorf(
  370. 'The "createRequestMock" does not allow specifying the "stream" and "body" options simultaneously.'
  371. );
  372. if (patch.encoding != null)
  373. throw new import_js_format10.Errorf(
  374. 'The "createRequestMock" does not allow specifying the "stream" and "encoding" options simultaneously.'
  375. );
  376. }
  377. const req = patch.stream || createRequestStream(patch.secure, patch.body, patch.encoding);
  378. req.url = createRequestUrl(patch.path || "/", patch.query);
  379. req.headers = createRequestHeaders(
  380. patch.host,
  381. patch.secure,
  382. patch.body,
  383. patch.cookies,
  384. patch.encoding,
  385. patch.headers
  386. );
  387. req.method = (patch.method || "get").toUpperCase();
  388. return req;
  389. }
  390. __name(createRequestMock, "createRequestMock");
  391. function createRequestStream(secure, body, encoding) {
  392. if (encoding != null && typeof encoding !== "string")
  393. throw new import_js_format10.Errorf(
  394. 'The parameter "encoding" of "createRequestStream" should be a String, but %v was given.',
  395. encoding
  396. );
  397. encoding = encoding || "utf-8";
  398. let socket = new import_net.Socket();
  399. if (secure) socket = new import_tls.TLSSocket(socket);
  400. const req = new import_http2.IncomingMessage(socket);
  401. if (body != null) {
  402. if (typeof body === "string") {
  403. req.push(body, encoding);
  404. } else if (Buffer.isBuffer(body)) {
  405. req.push(body);
  406. } else {
  407. req.push(JSON.stringify(body));
  408. }
  409. }
  410. req.push(null);
  411. return req;
  412. }
  413. __name(createRequestStream, "createRequestStream");
  414. function createRequestUrl(path, query) {
  415. if (typeof path !== "string")
  416. throw new import_js_format10.Errorf(
  417. 'The parameter "path" of "createRequestUrl" should be a String, but %v was given.',
  418. path
  419. );
  420. if (query != null && typeof query !== "string" && typeof query !== "object" || Array.isArray(query)) {
  421. throw new import_js_format10.Errorf(
  422. 'The parameter "query" of "createRequestUrl" should be a String or Object, but %v was given.',
  423. query
  424. );
  425. }
  426. let url = ("/" + path).replace("//", "/");
  427. if (typeof query === "object") {
  428. const qs = import_querystring.default.stringify(query);
  429. if (qs) url += `?${qs}`;
  430. } else if (typeof query === "string") {
  431. url += `?${query.replace(/^\?/, "")}`;
  432. }
  433. return url;
  434. }
  435. __name(createRequestUrl, "createRequestUrl");
  436. function createRequestHeaders(host, secure, body, cookies, encoding, headers) {
  437. if (host != null && typeof host !== "string")
  438. throw new import_js_format10.Errorf(
  439. 'The parameter "host" of "createRequestHeaders" a non-empty String, but %v was given.',
  440. host
  441. );
  442. host = host || "localhost";
  443. if (secure != null && typeof secure !== "boolean")
  444. throw new import_js_format10.Errorf(
  445. 'The parameter "secure" of "createRequestHeaders" should be a String, but %v was given.',
  446. secure
  447. );
  448. secure = Boolean(secure);
  449. if (cookies != null && typeof cookies !== "object" && typeof cookies !== "string" || Array.isArray(cookies)) {
  450. throw new import_js_format10.Errorf(
  451. 'The parameter "cookies" of "createRequestHeaders" should be a String or Object, but %v was given.',
  452. cookies
  453. );
  454. }
  455. if (headers != null && typeof headers !== "object" || Array.isArray(headers)) {
  456. throw new import_js_format10.Errorf(
  457. 'The parameter "headers" of "createRequestHeaders" should be an Object, but %v was given.',
  458. headers
  459. );
  460. }
  461. headers = headers || {};
  462. if (encoding != null && typeof encoding !== "string")
  463. throw new import_js_format10.Errorf(
  464. 'The parameter "encoding" of "createRequestHeaders" should be a String, but %v was given.',
  465. encoding
  466. );
  467. encoding = encoding || "utf-8";
  468. const obj = { ...headers };
  469. obj["host"] = host;
  470. if (secure) obj["x-forwarded-proto"] = "https";
  471. if (cookies != null) {
  472. if (typeof cookies === "string") {
  473. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  474. obj["cookie"] += obj["cookie"] ? `; ${cookies}` : cookies;
  475. } else if (typeof cookies === "object") {
  476. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  477. const newCookies = createCookiesString(cookies);
  478. obj["cookie"] += obj["cookie"] ? `; ${newCookies}` : newCookies;
  479. }
  480. }
  481. if (obj["content-type"] == null) {
  482. if (typeof body === "string") {
  483. obj["content-type"] = "text/plain";
  484. } else if (Buffer.isBuffer(body)) {
  485. obj["content-type"] = "application/octet-stream";
  486. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  487. obj["content-type"] = "application/json";
  488. }
  489. }
  490. if (body != null && obj["content-length"] == null) {
  491. if (typeof body === "string") {
  492. const length = Buffer.byteLength(body, encoding);
  493. obj["content-length"] = String(length);
  494. } else if (Buffer.isBuffer(body)) {
  495. const length = Buffer.byteLength(body);
  496. obj["content-length"] = String(length);
  497. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  498. const json = JSON.stringify(body);
  499. const length = Buffer.byteLength(json, encoding);
  500. obj["content-length"] = String(length);
  501. }
  502. }
  503. return obj;
  504. }
  505. __name(createRequestHeaders, "createRequestHeaders");
  506. // src/utils/create-response-mock.js
  507. var import_stream = require("stream");
  508. function createResponseMock() {
  509. const res = new import_stream.PassThrough();
  510. patchEncoding(res);
  511. patchHeaders(res);
  512. patchBody(res);
  513. return res;
  514. }
  515. __name(createResponseMock, "createResponseMock");
  516. function patchEncoding(res) {
  517. Object.defineProperty(res, "_encoding", {
  518. configurable: true,
  519. writable: true,
  520. value: void 0
  521. });
  522. Object.defineProperty(res, "setEncoding", {
  523. configurable: true,
  524. value: /* @__PURE__ */ __name(function(enc) {
  525. this._encoding = enc;
  526. return this;
  527. }, "value")
  528. });
  529. Object.defineProperty(res, "getEncoding", {
  530. configurable: true,
  531. value: /* @__PURE__ */ __name(function() {
  532. return this._encoding;
  533. }, "value")
  534. });
  535. }
  536. __name(patchEncoding, "patchEncoding");
  537. function patchHeaders(res) {
  538. Object.defineProperty(res, "_headersSent", {
  539. configurable: true,
  540. writable: true,
  541. value: false
  542. });
  543. Object.defineProperty(res, "headersSent", {
  544. configurable: true,
  545. get() {
  546. return this._headersSent;
  547. }
  548. });
  549. Object.defineProperty(res, "_headers", {
  550. configurable: true,
  551. writable: true,
  552. value: {}
  553. });
  554. Object.defineProperty(res, "setHeader", {
  555. configurable: true,
  556. value: /* @__PURE__ */ __name(function(name, value) {
  557. if (this.headersSent)
  558. throw new Error(
  559. "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"
  560. );
  561. const key = name.toLowerCase();
  562. this._headers[key] = String(value);
  563. return this;
  564. }, "value")
  565. });
  566. Object.defineProperty(res, "getHeader", {
  567. configurable: true,
  568. value: /* @__PURE__ */ __name(function(name) {
  569. return this._headers[name.toLowerCase()];
  570. }, "value")
  571. });
  572. Object.defineProperty(res, "getHeaders", {
  573. configurable: true,
  574. value: /* @__PURE__ */ __name(function() {
  575. return JSON.parse(JSON.stringify(this._headers));
  576. }, "value")
  577. });
  578. }
  579. __name(patchHeaders, "patchHeaders");
  580. function patchBody(res) {
  581. let resolve, reject;
  582. const promise = new Promise((res2, rej) => {
  583. resolve = res2;
  584. reject = rej;
  585. });
  586. const data = [];
  587. res.on("data", (c) => data.push(c));
  588. res.on("error", (e) => reject(e));
  589. res.on("end", () => {
  590. res._headersSent = true;
  591. resolve(Buffer.concat(data));
  592. });
  593. Object.defineProperty(res, "getBody", {
  594. configurable: true,
  595. value: /* @__PURE__ */ __name(function() {
  596. return promise.then((buffer) => {
  597. const enc = this.getEncoding();
  598. const str = buffer.toString(enc);
  599. return data.length ? str : void 0;
  600. });
  601. }, "value")
  602. });
  603. }
  604. __name(patchBody, "patchBody");
  605. // src/utils/get-request-pathname.js
  606. var import_js_format11 = require("@e22m4u/js-format");
  607. function getRequestPathname(req) {
  608. if (!req || typeof req !== "object" || Array.isArray(req) || typeof req.url !== "string") {
  609. throw new import_js_format11.Errorf(
  610. 'The first argument of "getRequestPathname" should be an instance of IncomingMessage, but %v was given.',
  611. req
  612. );
  613. }
  614. return (req.url || "/").replace(/\?.*$/, "");
  615. }
  616. __name(getRequestPathname, "getRequestPathname");
  617. // src/hooks/hook-registry.js
  618. var import_js_format12 = require("@e22m4u/js-format");
  619. var HookType = {
  620. PRE_HANDLER: "preHandler",
  621. POST_HANDLER: "postHandler"
  622. };
  623. var _HookRegistry = class _HookRegistry {
  624. /**
  625. * Hooks.
  626. *
  627. * @type {Map<string, Function[]>}
  628. * @private
  629. */
  630. _hooks = /* @__PURE__ */ new Map();
  631. /**
  632. * Add hook.
  633. *
  634. * @param {string} type
  635. * @param {Function} hook
  636. * @returns {this}
  637. */
  638. addHook(type, hook) {
  639. if (!type || typeof type !== "string")
  640. throw new import_js_format12.Errorf("The hook type is required, but %v was given.", type);
  641. if (!Object.values(HookType).includes(type))
  642. throw new import_js_format12.Errorf("The hook type %v is not supported.", type);
  643. if (!hook || typeof hook !== "function")
  644. throw new import_js_format12.Errorf(
  645. "The hook %v should be a Function, but %v was given.",
  646. type,
  647. hook
  648. );
  649. const hooks = this._hooks.get(type) || [];
  650. hooks.push(hook);
  651. this._hooks.set(type, hooks);
  652. return this;
  653. }
  654. /**
  655. * Has hook.
  656. *
  657. * @param {string} type
  658. * @param {Function} hook
  659. * @returns {boolean}
  660. */
  661. hasHook(type, hook) {
  662. if (!type || typeof type !== "string")
  663. throw new import_js_format12.Errorf("The hook type is required, but %v was given.", type);
  664. if (!Object.values(HookType).includes(type))
  665. throw new import_js_format12.Errorf("The hook type %v is not supported.", type);
  666. if (!hook || typeof hook !== "function")
  667. throw new import_js_format12.Errorf(
  668. "The hook %v should be a Function, but %v was given.",
  669. type,
  670. hook
  671. );
  672. const hooks = this._hooks.get(type) || [];
  673. return hooks.indexOf(hook) > -1;
  674. }
  675. /**
  676. * Get hooks.
  677. *
  678. * @param {string} type
  679. * @returns {Function[]}
  680. */
  681. getHooks(type) {
  682. if (!type || typeof type !== "string")
  683. throw new import_js_format12.Errorf("The hook type is required, but %v was given.", type);
  684. if (!Object.values(HookType).includes(type))
  685. throw new import_js_format12.Errorf("The hook type %v is not supported.", type);
  686. return this._hooks.get(type) || [];
  687. }
  688. };
  689. __name(_HookRegistry, "HookRegistry");
  690. var HookRegistry = _HookRegistry;
  691. // src/debuggable-service.js
  692. var import_js_service = require("@e22m4u/js-service");
  693. var MODULE_DEBUG_NAMESPACE = "jsTrieRouter";
  694. var _DebuggableService = class _DebuggableService extends import_js_service.DebuggableService {
  695. /**
  696. * Constructor.
  697. *
  698. * @param {ServiceContainer} container
  699. */
  700. constructor(container = void 0) {
  701. super(container, {
  702. namespace: MODULE_DEBUG_NAMESPACE,
  703. noEnvironmentNamespace: true
  704. });
  705. }
  706. };
  707. __name(_DebuggableService, "DebuggableService");
  708. var DebuggableService = _DebuggableService;
  709. // src/hooks/hook-invoker.js
  710. var _HookInvoker = class _HookInvoker extends DebuggableService {
  711. /**
  712. * Invoke and continue until value received.
  713. *
  714. * @param {Route} route
  715. * @param {string} hookType
  716. * @param {import('http').ServerResponse} response
  717. * @param {*[]} args
  718. * @returns {Promise<*>|*}
  719. */
  720. invokeAndContinueUntilValueReceived(route, hookType, response, ...args) {
  721. if (!route || !(route instanceof Route))
  722. throw new import_js_format13.Errorf(
  723. 'The parameter "route" of the HookInvoker.invokeAndContinueUntilValueReceived should be a Route instance, but %v was given.',
  724. route
  725. );
  726. if (!hookType || typeof hookType !== "string")
  727. throw new import_js_format13.Errorf(
  728. 'The parameter "hookType" of the HookInvoker.invokeAndContinueUntilValueReceived should be a non-empty String, but %v was given.',
  729. hookType
  730. );
  731. if (!Object.values(HookType).includes(hookType))
  732. throw new import_js_format13.Errorf("The hook type %v is not supported.", hookType);
  733. if (!response || typeof response !== "object" || Array.isArray(response) || typeof response.headersSent !== "boolean") {
  734. throw new import_js_format13.Errorf(
  735. 'The parameter "response" of the HookInvoker.invokeAndContinueUntilValueReceived should be a ServerResponse instance, but %v was given.',
  736. response
  737. );
  738. }
  739. const hooks = [
  740. ...this.getService(HookRegistry).getHooks(hookType),
  741. ...route.hookRegistry.getHooks(hookType)
  742. ];
  743. let result = void 0;
  744. for (const hook of hooks) {
  745. if (isResponseSent(response)) {
  746. result = response;
  747. break;
  748. }
  749. if (result == null) {
  750. result = hook(...args);
  751. } else if (isPromise(result)) {
  752. result = result.then((prevVal) => {
  753. if (isResponseSent(response)) {
  754. return;
  755. }
  756. if (prevVal != null) return prevVal;
  757. return hook(...args);
  758. });
  759. } else {
  760. break;
  761. }
  762. }
  763. return result;
  764. }
  765. };
  766. __name(_HookInvoker, "HookInvoker");
  767. var HookInvoker = _HookInvoker;
  768. // src/route.js
  769. var import_js_debug = require("@e22m4u/js-debug");
  770. var HttpMethod = {
  771. GET: "GET",
  772. POST: "POST",
  773. PUT: "PUT",
  774. PATCH: "PATCH",
  775. DELETE: "DELETE"
  776. };
  777. var _Route = class _Route extends import_js_debug.Debuggable {
  778. /**
  779. * Method.
  780. *
  781. * @type {string}
  782. * @private
  783. */
  784. _method;
  785. /**
  786. * Getter of the method.
  787. *
  788. * @returns {string}
  789. */
  790. get method() {
  791. return this._method;
  792. }
  793. /**
  794. * Path template.
  795. *
  796. * @type {string}
  797. * @private
  798. */
  799. _path;
  800. /**
  801. * Getter of the path.
  802. *
  803. * @returns {string}
  804. */
  805. get path() {
  806. return this._path;
  807. }
  808. /**
  809. * Handler.
  810. *
  811. * @type {RouteHandler}
  812. * @private
  813. */
  814. _handler;
  815. /**
  816. * Getter of the handler.
  817. *
  818. * @returns {*}
  819. */
  820. get handler() {
  821. return this._handler;
  822. }
  823. /**
  824. * Hook registry.
  825. *
  826. * @type {HookRegistry}
  827. * @private
  828. */
  829. _hookRegistry = new HookRegistry();
  830. /**
  831. * Getter of the hook registry.
  832. *
  833. * @returns {HookRegistry}
  834. */
  835. get hookRegistry() {
  836. return this._hookRegistry;
  837. }
  838. /**
  839. * Constructor.
  840. *
  841. * @param {RouteDefinition} routeDef
  842. */
  843. constructor(routeDef) {
  844. super({
  845. namespace: MODULE_DEBUG_NAMESPACE,
  846. noEnvironmentNamespace: true,
  847. noInstantiationMessage: true
  848. });
  849. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  850. throw new import_js_format14.Errorf(
  851. "The first parameter of Route.constructor should be an Object, but %v was given.",
  852. routeDef
  853. );
  854. if (!routeDef.method || typeof routeDef.method !== "string")
  855. throw new import_js_format14.Errorf(
  856. 'The option "method" of the Route should be a non-empty String, but %v was given.',
  857. routeDef.method
  858. );
  859. this._method = routeDef.method.toUpperCase();
  860. if (typeof routeDef.path !== "string")
  861. throw new import_js_format14.Errorf(
  862. 'The option "path" of the Route should be a String, but %v was given.',
  863. routeDef.path
  864. );
  865. this._path = routeDef.path;
  866. if (typeof routeDef.handler !== "function")
  867. throw new import_js_format14.Errorf(
  868. 'The option "handler" of the Route should be a Function, but %v was given.',
  869. routeDef.handler
  870. );
  871. this._handler = routeDef.handler;
  872. if (routeDef.preHandler != null) {
  873. const preHandlerHooks = Array.isArray(routeDef.preHandler) ? routeDef.preHandler : [routeDef.preHandler];
  874. preHandlerHooks.forEach((hook) => {
  875. this._hookRegistry.addHook(HookType.PRE_HANDLER, hook);
  876. });
  877. }
  878. if (routeDef.postHandler != null) {
  879. const postHandlerHooks = Array.isArray(routeDef.postHandler) ? routeDef.postHandler : [routeDef.postHandler];
  880. postHandlerHooks.forEach((hook) => {
  881. this._hookRegistry.addHook(HookType.POST_HANDLER, hook);
  882. });
  883. }
  884. this.ctorDebug("A new route %s %v was created.", this._method, this._path);
  885. }
  886. /**
  887. * Handle request.
  888. *
  889. * @param {RequestContext} context
  890. * @returns {*}
  891. */
  892. handle(context) {
  893. const debug = this.getDebuggerFor(this.handle);
  894. const requestPath = getRequestPathname(context.req);
  895. debug(
  896. "Invoking the Route handler for the request %s %v.",
  897. this.method.toUpperCase(),
  898. requestPath
  899. );
  900. return this._handler(context);
  901. }
  902. };
  903. __name(_Route, "Route");
  904. var Route = _Route;
  905. // src/trie-router.js
  906. var import_http4 = require("http");
  907. var import_http5 = require("http");
  908. // src/senders/data-sender.js
  909. var import_js_format15 = require("@e22m4u/js-format");
  910. var _DataSender = class _DataSender extends DebuggableService {
  911. /**
  912. * Send.
  913. *
  914. * @param {import('http').ServerResponse} res
  915. * @param {*} data
  916. * @returns {undefined}
  917. */
  918. send(res, data) {
  919. const debug = this.getDebuggerFor(this.send);
  920. if (data === res || res.headersSent) {
  921. debug(
  922. "Response sending was skipped because its headers where sent already."
  923. );
  924. return;
  925. }
  926. if (data == null) {
  927. res.statusCode = 204;
  928. res.end();
  929. debug("The empty response was sent.");
  930. return;
  931. }
  932. if (isReadableStream(data)) {
  933. res.setHeader("Content-Type", "application/octet-stream");
  934. data.pipe(res);
  935. debug("The stream response was sent.");
  936. return;
  937. }
  938. let debugMsg;
  939. switch (typeof data) {
  940. case "object":
  941. case "boolean":
  942. case "number":
  943. if (Buffer.isBuffer(data)) {
  944. res.setHeader("content-type", "application/octet-stream");
  945. debugMsg = "The Buffer was sent as binary data.";
  946. } else {
  947. res.setHeader("content-type", "application/json");
  948. debugMsg = (0, import_js_format15.format)("The %v was sent as JSON.", typeof data);
  949. data = JSON.stringify(data);
  950. }
  951. break;
  952. default:
  953. res.setHeader("content-type", "text/plain");
  954. debugMsg = "The response data was sent as plain text.";
  955. data = String(data);
  956. break;
  957. }
  958. res.end(data);
  959. debug(debugMsg);
  960. }
  961. };
  962. __name(_DataSender, "DataSender");
  963. var DataSender = _DataSender;
  964. // src/senders/error-sender.js
  965. var import_util = require("util");
  966. var import_statuses = __toESM(require("statuses"), 1);
  967. var EXPOSED_ERROR_PROPERTIES = ["code", "details"];
  968. var _ErrorSender = class _ErrorSender extends DebuggableService {
  969. /**
  970. * Handle.
  971. *
  972. * @param {import('http').IncomingMessage} req
  973. * @param {import('http').ServerResponse} res
  974. * @param {Error} error
  975. * @returns {undefined}
  976. */
  977. send(req, res, error) {
  978. const debug = this.getDebuggerFor(this.send);
  979. let safeError = {};
  980. if (error) {
  981. if (typeof error === "object") {
  982. safeError = error;
  983. } else {
  984. safeError = { message: String(error) };
  985. }
  986. }
  987. const statusCode = error.statusCode || error.status || 500;
  988. const body = { error: {} };
  989. if (safeError.message && typeof safeError.message === "string") {
  990. body.error.message = safeError.message;
  991. } else {
  992. body.error.message = (0, import_statuses.default)(statusCode);
  993. }
  994. EXPOSED_ERROR_PROPERTIES.forEach((name) => {
  995. if (name in safeError) body.error[name] = safeError[name];
  996. });
  997. const requestData = {
  998. url: req.url,
  999. method: req.method,
  1000. headers: req.headers
  1001. };
  1002. const inspectOptions = {
  1003. showHidden: false,
  1004. depth: null,
  1005. colors: true,
  1006. compact: false
  1007. };
  1008. console.warn((0, import_util.inspect)(requestData, inspectOptions));
  1009. console.warn((0, import_util.inspect)(body, inspectOptions));
  1010. if (error.stack) {
  1011. console.log(error.stack);
  1012. } else {
  1013. console.error(error);
  1014. }
  1015. res.statusCode = statusCode;
  1016. res.setHeader("content-type", "application/json; charset=utf-8");
  1017. res.end(JSON.stringify(body, null, 2), "utf-8");
  1018. debug(
  1019. "The %s error was sent for the request %s %v.",
  1020. statusCode,
  1021. req.method,
  1022. getRequestPathname(req)
  1023. );
  1024. }
  1025. /**
  1026. * Send 404.
  1027. *
  1028. * @param {import('http').IncomingMessage} req
  1029. * @param {import('http').ServerResponse} res
  1030. * @returns {undefined}
  1031. */
  1032. send404(req, res) {
  1033. const debug = this.getDebuggerFor(this.send404);
  1034. res.statusCode = 404;
  1035. res.setHeader("content-type", "text/plain; charset=utf-8");
  1036. res.end("404 Not Found", "utf-8");
  1037. debug(
  1038. "The 404 error was sent for the request %s %v.",
  1039. req.method,
  1040. getRequestPathname(req)
  1041. );
  1042. }
  1043. };
  1044. __name(_ErrorSender, "ErrorSender");
  1045. var ErrorSender = _ErrorSender;
  1046. // src/parsers/body-parser.js
  1047. var import_http_errors2 = __toESM(require("http-errors"), 1);
  1048. var import_js_format17 = require("@e22m4u/js-format");
  1049. // src/router-options.js
  1050. var import_js_format16 = require("@e22m4u/js-format");
  1051. var _RouterOptions = class _RouterOptions extends DebuggableService {
  1052. /**
  1053. * Request body bytes limit.
  1054. *
  1055. * @type {number}
  1056. * @private
  1057. */
  1058. _requestBodyBytesLimit = 512e3;
  1059. // 512kb
  1060. /**
  1061. * Getter of request body bytes limit.
  1062. *
  1063. * @returns {number}
  1064. */
  1065. get requestBodyBytesLimit() {
  1066. return this._requestBodyBytesLimit;
  1067. }
  1068. /**
  1069. * Set request body bytes limit.
  1070. *
  1071. * @param {number} input
  1072. * @returns {RouterOptions}
  1073. */
  1074. setRequestBodyBytesLimit(input) {
  1075. if (typeof input !== "number" || input < 0)
  1076. throw new import_js_format16.Errorf(
  1077. 'The option "requestBodyBytesLimit" must be a positive Number or 0, but %v was given.',
  1078. input
  1079. );
  1080. this._requestBodyBytesLimit = input;
  1081. return this;
  1082. }
  1083. };
  1084. __name(_RouterOptions, "RouterOptions");
  1085. var RouterOptions = _RouterOptions;
  1086. // src/parsers/body-parser.js
  1087. var METHODS_WITH_BODY = ["POST", "PUT", "PATCH", "DELETE"];
  1088. var UNPARSABLE_MEDIA_TYPES = ["multipart/form-data"];
  1089. var _BodyParser = class _BodyParser extends DebuggableService {
  1090. /**
  1091. * Parsers.
  1092. *
  1093. * @type {{[mime: string]: Function}}
  1094. */
  1095. _parsers = {
  1096. "text/plain": /* @__PURE__ */ __name((v) => String(v), "text/plain"),
  1097. "application/json": parseJsonBody
  1098. };
  1099. /**
  1100. * Set parser.
  1101. *
  1102. * @param {string} mediaType
  1103. * @param {Function} parser
  1104. * @returns {this}
  1105. */
  1106. defineParser(mediaType, parser) {
  1107. if (!mediaType || typeof mediaType !== "string")
  1108. throw new import_js_format17.Errorf(
  1109. 'The parameter "mediaType" of BodyParser.defineParser should be a non-empty String, but %v was given.',
  1110. mediaType
  1111. );
  1112. if (!parser || typeof parser !== "function")
  1113. throw new import_js_format17.Errorf(
  1114. 'The parameter "parser" of BodyParser.defineParser should be a Function, but %v was given.',
  1115. parser
  1116. );
  1117. this._parsers[mediaType] = parser;
  1118. return this;
  1119. }
  1120. /**
  1121. * Has parser.
  1122. *
  1123. * @param {string} mediaType
  1124. * @returns {boolean}
  1125. */
  1126. hasParser(mediaType) {
  1127. if (!mediaType || typeof mediaType !== "string")
  1128. throw new import_js_format17.Errorf(
  1129. 'The parameter "mediaType" of BodyParser.hasParser should be a non-empty String, but %v was given.',
  1130. mediaType
  1131. );
  1132. return Boolean(this._parsers[mediaType]);
  1133. }
  1134. /**
  1135. * Delete parser.
  1136. *
  1137. * @param {string} mediaType
  1138. * @returns {this}
  1139. */
  1140. deleteParser(mediaType) {
  1141. if (!mediaType || typeof mediaType !== "string")
  1142. throw new import_js_format17.Errorf(
  1143. 'The parameter "mediaType" of BodyParser.deleteParser should be a non-empty String, but %v was given.',
  1144. mediaType
  1145. );
  1146. const parser = this._parsers[mediaType];
  1147. if (!parser) throw new import_js_format17.Errorf("The parser of %v is not found.", mediaType);
  1148. delete this._parsers[mediaType];
  1149. return this;
  1150. }
  1151. /**
  1152. * Parse.
  1153. *
  1154. * @param {import('http').IncomingMessage} req
  1155. * @returns {Promise<*>|undefined}
  1156. */
  1157. parse(req) {
  1158. const debug = this.getDebuggerFor(this.parse);
  1159. if (!METHODS_WITH_BODY.includes(req.method.toUpperCase())) {
  1160. debug(
  1161. "Body parsing was skipped for the %s request.",
  1162. req.method.toUpperCase()
  1163. );
  1164. return;
  1165. }
  1166. const contentType = (req.headers["content-type"] || "").replace(
  1167. /^([^;]+);.*$/,
  1168. "$1"
  1169. );
  1170. if (!contentType) {
  1171. debug(
  1172. "Body parsing was skipped because the request had no content type."
  1173. );
  1174. return;
  1175. }
  1176. const { mediaType } = parseContentType(contentType);
  1177. if (!mediaType)
  1178. throw createError(
  1179. import_http_errors2.default.BadRequest,
  1180. 'Unable to parse the "content-type" header.'
  1181. );
  1182. const parser = this._parsers[mediaType];
  1183. if (!parser) {
  1184. if (UNPARSABLE_MEDIA_TYPES.includes(mediaType)) {
  1185. debug("Body parsing was skipped for %v.", mediaType);
  1186. return;
  1187. }
  1188. throw createError(
  1189. import_http_errors2.default.UnsupportedMediaType,
  1190. "Media type %v is not supported.",
  1191. mediaType
  1192. );
  1193. }
  1194. const bodyBytesLimit = this.getService(RouterOptions).requestBodyBytesLimit;
  1195. return fetchRequestBody(req, bodyBytesLimit).then((rawBody) => {
  1196. if (rawBody != null) return parser(rawBody);
  1197. return rawBody;
  1198. });
  1199. }
  1200. };
  1201. __name(_BodyParser, "BodyParser");
  1202. var BodyParser = _BodyParser;
  1203. function parseJsonBody(input) {
  1204. if (typeof input !== "string") return void 0;
  1205. try {
  1206. return JSON.parse(input);
  1207. } catch (error) {
  1208. throw createError(import_http_errors2.default.BadRequest, error.message);
  1209. }
  1210. }
  1211. __name(parseJsonBody, "parseJsonBody");
  1212. // src/parsers/query-parser.js
  1213. var import_querystring2 = __toESM(require("querystring"), 1);
  1214. var _QueryParser = class _QueryParser extends DebuggableService {
  1215. /**
  1216. * Parse
  1217. *
  1218. * @param {import('http').IncomingMessage} req
  1219. * @returns {object}
  1220. */
  1221. parse(req) {
  1222. const debug = this.getDebuggerFor(this.parse);
  1223. const queryStr = req.url.replace(/^[^?]*\??/, "");
  1224. const query = queryStr ? import_querystring2.default.parse(queryStr) : {};
  1225. const queryKeys = Object.keys(query);
  1226. if (queryKeys.length) {
  1227. queryKeys.forEach((key) => {
  1228. debug("The query parameter %v had the value %v.", key, query[key]);
  1229. });
  1230. } else {
  1231. debug(
  1232. "The request %s %v had no query parameters.",
  1233. req.method,
  1234. getRequestPathname(req)
  1235. );
  1236. }
  1237. return query;
  1238. }
  1239. };
  1240. __name(_QueryParser, "QueryParser");
  1241. var QueryParser = _QueryParser;
  1242. // src/parsers/cookies-parser.js
  1243. var _CookiesParser = class _CookiesParser extends DebuggableService {
  1244. /**
  1245. * Parse
  1246. *
  1247. * @param {import('http').IncomingMessage} req
  1248. * @returns {object}
  1249. */
  1250. parse(req) {
  1251. const debug = this.getDebuggerFor(this.parse);
  1252. const cookiesString = req.headers["cookie"] || "";
  1253. const cookies = parseCookies(cookiesString);
  1254. const cookiesKeys = Object.keys(cookies);
  1255. if (cookiesKeys.length) {
  1256. cookiesKeys.forEach((key) => {
  1257. debug("The cookie %v had the value %v.", key, cookies[key]);
  1258. });
  1259. } else {
  1260. debug(
  1261. "The request %s %v had no cookies.",
  1262. req.method,
  1263. getRequestPathname(req)
  1264. );
  1265. }
  1266. return cookies;
  1267. }
  1268. };
  1269. __name(_CookiesParser, "CookiesParser");
  1270. var CookiesParser = _CookiesParser;
  1271. // src/parsers/request-parser.js
  1272. var import_http3 = require("http");
  1273. var import_js_format18 = require("@e22m4u/js-format");
  1274. var _RequestParser = class _RequestParser extends DebuggableService {
  1275. /**
  1276. * Parse.
  1277. *
  1278. * @param {IncomingMessage} req
  1279. * @returns {Promise<object>|object}
  1280. */
  1281. parse(req) {
  1282. if (!(req instanceof import_http3.IncomingMessage))
  1283. throw new import_js_format18.Errorf(
  1284. "The first argument of RequestParser.parse should be an instance of IncomingMessage, but %v was given.",
  1285. req
  1286. );
  1287. const data = {};
  1288. const promises = [];
  1289. const parsedQuery = this.getService(QueryParser).parse(req);
  1290. if (isPromise(parsedQuery)) {
  1291. promises.push(parsedQuery.then((v) => data.query = v));
  1292. } else {
  1293. data.query = parsedQuery;
  1294. }
  1295. const parsedCookies = this.getService(CookiesParser).parse(req);
  1296. if (isPromise(parsedCookies)) {
  1297. promises.push(parsedCookies.then((v) => data.cookies = v));
  1298. } else {
  1299. data.cookies = parsedCookies;
  1300. }
  1301. const parsedBody = this.getService(BodyParser).parse(req);
  1302. if (isPromise(parsedBody)) {
  1303. promises.push(parsedBody.then((v) => data.body = v));
  1304. } else {
  1305. data.body = parsedBody;
  1306. }
  1307. data.headers = Object.assign({}, req.headers);
  1308. return promises.length ? Promise.all(promises).then(() => data) : data;
  1309. }
  1310. };
  1311. __name(_RequestParser, "RequestParser");
  1312. var RequestParser = _RequestParser;
  1313. // src/route-registry.js
  1314. var import_js_format19 = require("@e22m4u/js-format");
  1315. var import_js_path_trie = require("@e22m4u/js-path-trie");
  1316. var import_js_service2 = require("@e22m4u/js-service");
  1317. var _RouteRegistry = class _RouteRegistry extends DebuggableService {
  1318. /**
  1319. * Constructor.
  1320. *
  1321. * @param {ServiceContainer} container
  1322. */
  1323. constructor(container) {
  1324. super(container);
  1325. this._trie = new import_js_path_trie.PathTrie();
  1326. }
  1327. /**
  1328. * Define route.
  1329. *
  1330. * @param {import('./route.js').RouteDefinition} routeDef
  1331. * @returns {Route}
  1332. */
  1333. defineRoute(routeDef) {
  1334. const debug = this.getDebuggerFor(this.defineRoute);
  1335. if (!routeDef || typeof routeDef !== "object" || Array.isArray(routeDef))
  1336. throw new import_js_format19.Errorf(
  1337. "The route definition should be an Object, but %v was given.",
  1338. routeDef
  1339. );
  1340. const route = new Route(routeDef);
  1341. const triePath = `${route.method}/${route.path}`;
  1342. this._trie.add(triePath, route);
  1343. debug(
  1344. "The route %s %v was registered.",
  1345. route.method.toUpperCase(),
  1346. route.path
  1347. );
  1348. return route;
  1349. }
  1350. /**
  1351. * Match route by request.
  1352. *
  1353. * @param {import('http').IncomingRequest} req
  1354. * @returns {ResolvedRoute|undefined}
  1355. */
  1356. matchRouteByRequest(req) {
  1357. const debug = this.getDebuggerFor(this.matchRouteByRequest);
  1358. const requestPath = (req.url || "/").replace(/\?.*$/, "");
  1359. debug(
  1360. "Matching routes with the request %s %v.",
  1361. req.method.toUpperCase(),
  1362. requestPath
  1363. );
  1364. const triePath = `${req.method.toUpperCase()}/${requestPath}`;
  1365. const resolved = this._trie.match(triePath);
  1366. if (resolved) {
  1367. const route = resolved.value;
  1368. debug(
  1369. "The route %s %v was matched.",
  1370. route.method.toUpperCase(),
  1371. route.path
  1372. );
  1373. const paramNames = Object.keys(resolved.params);
  1374. if (paramNames.length) {
  1375. paramNames.forEach((name) => {
  1376. debug(
  1377. "The path parameter %v had the value %v.",
  1378. name,
  1379. resolved.params[name]
  1380. );
  1381. });
  1382. } else {
  1383. debug("No path parameters found.");
  1384. }
  1385. return { route, params: resolved.params };
  1386. }
  1387. debug(
  1388. "No matched route for the request %s %v.",
  1389. req.method.toUpperCase(),
  1390. requestPath
  1391. );
  1392. }
  1393. };
  1394. __name(_RouteRegistry, "RouteRegistry");
  1395. var RouteRegistry = _RouteRegistry;
  1396. // src/request-context.js
  1397. var import_js_format20 = require("@e22m4u/js-format");
  1398. var import_js_service3 = require("@e22m4u/js-service");
  1399. var import_js_service4 = require("@e22m4u/js-service");
  1400. var _RequestContext = class _RequestContext {
  1401. /**
  1402. * Service container.
  1403. *
  1404. * @type {import('@e22m4u/js-service').ServiceContainer}
  1405. */
  1406. container;
  1407. /**
  1408. * Request.
  1409. *
  1410. * @type {import('http').IncomingMessage}
  1411. */
  1412. req;
  1413. /**
  1414. * Response.
  1415. *
  1416. * @type {import('http').ServerResponse}
  1417. */
  1418. res;
  1419. /**
  1420. * Query.
  1421. *
  1422. * @type {object}
  1423. */
  1424. query = {};
  1425. /**
  1426. * Path parameters.
  1427. *
  1428. * @type {object}
  1429. */
  1430. params = {};
  1431. /**
  1432. * Headers.
  1433. *
  1434. * @type {object}
  1435. */
  1436. headers = {};
  1437. /**
  1438. * Parsed cookies.
  1439. *
  1440. * @type {object}
  1441. */
  1442. cookies = {};
  1443. /**
  1444. * Parsed body.
  1445. *
  1446. * @type {*}
  1447. */
  1448. body;
  1449. /**
  1450. * Method.
  1451. *
  1452. * @returns {string}
  1453. */
  1454. get method() {
  1455. return this.req.method.toUpperCase();
  1456. }
  1457. /**
  1458. * Path.
  1459. *
  1460. * @returns {string}
  1461. */
  1462. get path() {
  1463. return this.req.url;
  1464. }
  1465. /**
  1466. * Pathname.
  1467. *
  1468. * @type {string|undefined}
  1469. * @private
  1470. */
  1471. _pathname = void 0;
  1472. /**
  1473. * Pathname.
  1474. *
  1475. * @returns {string}
  1476. */
  1477. get pathname() {
  1478. if (this._pathname != null) return this._pathname;
  1479. this._pathname = getRequestPathname(this.req);
  1480. return this._pathname;
  1481. }
  1482. /**
  1483. * Constructor.
  1484. *
  1485. * @param {ServiceContainer} container
  1486. * @param {import('http').IncomingMessage} request
  1487. * @param {import('http').ServerResponse} response
  1488. */
  1489. constructor(container, request, response) {
  1490. if (!(0, import_js_service4.isServiceContainer)(container))
  1491. throw new import_js_format20.Errorf(
  1492. 'The parameter "container" of RequestContext.constructor should be an instance of ServiceContainer, but %v was given.',
  1493. container
  1494. );
  1495. this.container = container;
  1496. if (!request || typeof request !== "object" || Array.isArray(request) || !isReadableStream(request)) {
  1497. throw new import_js_format20.Errorf(
  1498. 'The parameter "request" of RequestContext.constructor should be an instance of IncomingMessage, but %v was given.',
  1499. request
  1500. );
  1501. }
  1502. this.req = request;
  1503. if (!response || typeof response !== "object" || Array.isArray(response) || !isWritableStream(response)) {
  1504. throw new import_js_format20.Errorf(
  1505. 'The parameter "response" of RequestContext.constructor should be an instance of ServerResponse, but %v was given.',
  1506. response
  1507. );
  1508. }
  1509. this.res = response;
  1510. }
  1511. };
  1512. __name(_RequestContext, "RequestContext");
  1513. var RequestContext = _RequestContext;
  1514. // src/trie-router.js
  1515. var import_js_service5 = require("@e22m4u/js-service");
  1516. var _TrieRouter = class _TrieRouter extends DebuggableService {
  1517. /**
  1518. * Define route.
  1519. *
  1520. * Example 1:
  1521. * ```
  1522. * const router = new TrieRouter();
  1523. * router.defineRoute({
  1524. * method: HttpMethod.GET, // Request method.
  1525. * path: '/', // Path template.
  1526. * handler: ctx => 'Hello world!', // Request handler.
  1527. * });
  1528. * ```
  1529. *
  1530. * Example 2:
  1531. * ```
  1532. * const router = new TrieRouter();
  1533. * router.defineRoute({
  1534. * method: HttpMethod.POST, // Request method.
  1535. * path: '/users/:id', // The path template may have parameters.
  1536. * preHandler(ctx) { ... }, // The "preHandler" executes before a route handler.
  1537. * handler(ctx) { ... }, // Request handler function.
  1538. * postHandler(ctx, data) { ... }, // The "postHandler" executes after a route handler.
  1539. * });
  1540. * ```
  1541. *
  1542. * @param {import('./route-registry.js').RouteDefinition} routeDef
  1543. * @returns {import('./route.js').Route}
  1544. */
  1545. defineRoute(routeDef) {
  1546. return this.getService(RouteRegistry).defineRoute(routeDef);
  1547. }
  1548. /**
  1549. * Request listener.
  1550. *
  1551. * Example:
  1552. * ```
  1553. * import http from 'http';
  1554. * import {TrieRouter} from '@e22m4u/js-trie-router';
  1555. *
  1556. * const router = new TrieRouter();
  1557. * const server = new http.Server();
  1558. * server.on('request', router.requestListener); // Sets the request listener.
  1559. * server.listen(3000); // Starts listening for connections.
  1560. * ```
  1561. *
  1562. * @returns {Function}
  1563. */
  1564. get requestListener() {
  1565. return this._handleRequest.bind(this);
  1566. }
  1567. /**
  1568. * Handle incoming request.
  1569. *
  1570. * @param {import('http').IncomingMessage} req
  1571. * @param {import('http').ServerResponse} res
  1572. * @returns {Promise<undefined>}
  1573. * @private
  1574. */
  1575. async _handleRequest(req, res) {
  1576. const debug = this.getDebuggerFor(this._handleRequest);
  1577. const requestPath = (req.url || "/").replace(/\?.*$/, "");
  1578. debug(
  1579. "Preparing to handle an incoming request %s %v.",
  1580. req.method,
  1581. requestPath
  1582. );
  1583. const resolved = this.getService(RouteRegistry).matchRouteByRequest(req);
  1584. if (!resolved) {
  1585. debug("No route for the request %s %v.", req.method, requestPath);
  1586. this.getService(ErrorSender).send404(req, res);
  1587. } else {
  1588. const { route, params } = resolved;
  1589. const container = new import_js_service5.ServiceContainer(this.container);
  1590. const context = new RequestContext(container, req, res);
  1591. container.set(RequestContext, context);
  1592. container.set(import_http5.IncomingMessage, req);
  1593. container.set(import_http4.ServerResponse, res);
  1594. context.params = params;
  1595. let data;
  1596. try {
  1597. const reqDataOrPromise = this.getService(RequestParser).parse(req);
  1598. if (isPromise(reqDataOrPromise)) {
  1599. const reqData = await reqDataOrPromise;
  1600. Object.assign(context, reqData);
  1601. } else {
  1602. Object.assign(context, reqDataOrPromise);
  1603. }
  1604. const hookInvoker = this.getService(HookInvoker);
  1605. data = hookInvoker.invokeAndContinueUntilValueReceived(
  1606. route,
  1607. HookType.PRE_HANDLER,
  1608. res,
  1609. context
  1610. );
  1611. if (isPromise(data)) data = await data;
  1612. if (!isResponseSent(res) && data == null) {
  1613. data = route.handle(context);
  1614. if (isPromise(data)) data = await data;
  1615. let postHandlerData = hookInvoker.invokeAndContinueUntilValueReceived(
  1616. route,
  1617. HookType.POST_HANDLER,
  1618. res,
  1619. context,
  1620. data
  1621. );
  1622. if (isPromise(postHandlerData))
  1623. postHandlerData = await postHandlerData;
  1624. if (postHandlerData != null) data = postHandlerData;
  1625. }
  1626. } catch (error) {
  1627. this.getService(ErrorSender).send(req, res, error);
  1628. return;
  1629. }
  1630. if (!isResponseSent(res)) {
  1631. this.getService(DataSender).send(res, data);
  1632. }
  1633. }
  1634. }
  1635. /**
  1636. * Add hook.
  1637. *
  1638. * Example:
  1639. * ```
  1640. * import {TrieRouter} from '@e22m4u/js-trie-router';
  1641. * import {HookType} from '@e22m4u/js-trie-router';
  1642. *
  1643. * // Router instance.
  1644. * const router = new TrieRouter();
  1645. *
  1646. * // Adds the "preHandler" hook for each route.
  1647. * router.addHook(
  1648. * HookType.PRE_HANDLER,
  1649. * ctx => { ... },
  1650. * );
  1651. *
  1652. * // Adds the "postHandler" hook for each route.
  1653. * router.addHook(
  1654. * HookType.POST_HANDLER,
  1655. * ctx => { ... },
  1656. * );
  1657. * ```
  1658. *
  1659. * @param {string} type
  1660. * @param {Function} hook
  1661. * @returns {this}
  1662. */
  1663. addHook(type, hook) {
  1664. this.getService(HookRegistry).addHook(type, hook);
  1665. return this;
  1666. }
  1667. };
  1668. __name(_TrieRouter, "TrieRouter");
  1669. var TrieRouter = _TrieRouter;
  1670. // Annotate the CommonJS export names for ESM import in node:
  1671. 0 && (module.exports = {
  1672. BodyParser,
  1673. CHARACTER_ENCODING_LIST,
  1674. CookiesParser,
  1675. DataSender,
  1676. EXPOSED_ERROR_PROPERTIES,
  1677. ErrorSender,
  1678. HookInvoker,
  1679. HookRegistry,
  1680. HookType,
  1681. HttpMethod,
  1682. METHODS_WITH_BODY,
  1683. QueryParser,
  1684. RequestContext,
  1685. RequestParser,
  1686. Route,
  1687. RouteRegistry,
  1688. RouterOptions,
  1689. TrieRouter,
  1690. UNPARSABLE_MEDIA_TYPES,
  1691. createCookiesString,
  1692. createDebugger,
  1693. createError,
  1694. createRequestMock,
  1695. createResponseMock,
  1696. fetchRequestBody,
  1697. getRequestPathname,
  1698. isPromise,
  1699. isReadableStream,
  1700. isResponseSent,
  1701. isWritableStream,
  1702. parseContentType,
  1703. parseCookies,
  1704. parseJsonBody,
  1705. toCamelCase
  1706. });