index.cjs 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  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 rawTriePath = `${req.method.toUpperCase()}/${requestPath}`;
  1365. const triePath = rawTriePath.replace(/\/+/, "/");
  1366. const resolved = this._trie.match(triePath);
  1367. if (resolved) {
  1368. const route = resolved.value;
  1369. debug(
  1370. "The route %s %v was matched.",
  1371. route.method.toUpperCase(),
  1372. route.path
  1373. );
  1374. const paramNames = Object.keys(resolved.params);
  1375. if (paramNames.length) {
  1376. paramNames.forEach((name) => {
  1377. debug(
  1378. "The path parameter %v had the value %v.",
  1379. name,
  1380. resolved.params[name]
  1381. );
  1382. });
  1383. } else {
  1384. debug("No path parameters found.");
  1385. }
  1386. return { route, params: resolved.params };
  1387. }
  1388. debug(
  1389. "No matched route for the request %s %v.",
  1390. req.method.toUpperCase(),
  1391. requestPath
  1392. );
  1393. }
  1394. };
  1395. __name(_RouteRegistry, "RouteRegistry");
  1396. var RouteRegistry = _RouteRegistry;
  1397. // src/request-context.js
  1398. var import_js_format20 = require("@e22m4u/js-format");
  1399. var import_js_service3 = require("@e22m4u/js-service");
  1400. var import_js_service4 = require("@e22m4u/js-service");
  1401. var _RequestContext = class _RequestContext {
  1402. /**
  1403. * Service container.
  1404. *
  1405. * @type {import('@e22m4u/js-service').ServiceContainer}
  1406. */
  1407. container;
  1408. /**
  1409. * Request.
  1410. *
  1411. * @type {import('http').IncomingMessage}
  1412. */
  1413. req;
  1414. /**
  1415. * Response.
  1416. *
  1417. * @type {import('http').ServerResponse}
  1418. */
  1419. res;
  1420. /**
  1421. * Query.
  1422. *
  1423. * @type {object}
  1424. */
  1425. query = {};
  1426. /**
  1427. * Path parameters.
  1428. *
  1429. * @type {object}
  1430. */
  1431. params = {};
  1432. /**
  1433. * Headers.
  1434. *
  1435. * @type {object}
  1436. */
  1437. headers = {};
  1438. /**
  1439. * Parsed cookies.
  1440. *
  1441. * @type {object}
  1442. */
  1443. cookies = {};
  1444. /**
  1445. * Parsed body.
  1446. *
  1447. * @type {*}
  1448. */
  1449. body;
  1450. /**
  1451. * Method.
  1452. *
  1453. * @returns {string}
  1454. */
  1455. get method() {
  1456. return this.req.method.toUpperCase();
  1457. }
  1458. /**
  1459. * Path.
  1460. *
  1461. * @returns {string}
  1462. */
  1463. get path() {
  1464. return this.req.url;
  1465. }
  1466. /**
  1467. * Pathname.
  1468. *
  1469. * @type {string|undefined}
  1470. * @private
  1471. */
  1472. _pathname = void 0;
  1473. /**
  1474. * Pathname.
  1475. *
  1476. * @returns {string}
  1477. */
  1478. get pathname() {
  1479. if (this._pathname != null) return this._pathname;
  1480. this._pathname = getRequestPathname(this.req);
  1481. return this._pathname;
  1482. }
  1483. /**
  1484. * Constructor.
  1485. *
  1486. * @param {ServiceContainer} container
  1487. * @param {import('http').IncomingMessage} request
  1488. * @param {import('http').ServerResponse} response
  1489. */
  1490. constructor(container, request, response) {
  1491. if (!(0, import_js_service4.isServiceContainer)(container))
  1492. throw new import_js_format20.Errorf(
  1493. 'The parameter "container" of RequestContext.constructor should be an instance of ServiceContainer, but %v was given.',
  1494. container
  1495. );
  1496. this.container = container;
  1497. if (!request || typeof request !== "object" || Array.isArray(request) || !isReadableStream(request)) {
  1498. throw new import_js_format20.Errorf(
  1499. 'The parameter "request" of RequestContext.constructor should be an instance of IncomingMessage, but %v was given.',
  1500. request
  1501. );
  1502. }
  1503. this.req = request;
  1504. if (!response || typeof response !== "object" || Array.isArray(response) || !isWritableStream(response)) {
  1505. throw new import_js_format20.Errorf(
  1506. 'The parameter "response" of RequestContext.constructor should be an instance of ServerResponse, but %v was given.',
  1507. response
  1508. );
  1509. }
  1510. this.res = response;
  1511. }
  1512. };
  1513. __name(_RequestContext, "RequestContext");
  1514. var RequestContext = _RequestContext;
  1515. // src/trie-router.js
  1516. var import_js_service5 = require("@e22m4u/js-service");
  1517. var _TrieRouter = class _TrieRouter extends DebuggableService {
  1518. /**
  1519. * Define route.
  1520. *
  1521. * Example 1:
  1522. * ```
  1523. * const router = new TrieRouter();
  1524. * router.defineRoute({
  1525. * method: HttpMethod.GET, // Request method.
  1526. * path: '/', // Path template.
  1527. * handler: ctx => 'Hello world!', // Request handler.
  1528. * });
  1529. * ```
  1530. *
  1531. * Example 2:
  1532. * ```
  1533. * const router = new TrieRouter();
  1534. * router.defineRoute({
  1535. * method: HttpMethod.POST, // Request method.
  1536. * path: '/users/:id', // The path template may have parameters.
  1537. * preHandler(ctx) { ... }, // The "preHandler" executes before a route handler.
  1538. * handler(ctx) { ... }, // Request handler function.
  1539. * postHandler(ctx, data) { ... }, // The "postHandler" executes after a route handler.
  1540. * });
  1541. * ```
  1542. *
  1543. * @param {import('./route-registry.js').RouteDefinition} routeDef
  1544. * @returns {import('./route.js').Route}
  1545. */
  1546. defineRoute(routeDef) {
  1547. return this.getService(RouteRegistry).defineRoute(routeDef);
  1548. }
  1549. /**
  1550. * Request listener.
  1551. *
  1552. * Example:
  1553. * ```
  1554. * import http from 'http';
  1555. * import {TrieRouter} from '@e22m4u/js-trie-router';
  1556. *
  1557. * const router = new TrieRouter();
  1558. * const server = new http.Server();
  1559. * server.on('request', router.requestListener); // Sets the request listener.
  1560. * server.listen(3000); // Starts listening for connections.
  1561. * ```
  1562. *
  1563. * @returns {Function}
  1564. */
  1565. get requestListener() {
  1566. return this._handleRequest.bind(this);
  1567. }
  1568. /**
  1569. * Handle incoming request.
  1570. *
  1571. * @param {import('http').IncomingMessage} req
  1572. * @param {import('http').ServerResponse} res
  1573. * @returns {Promise<undefined>}
  1574. * @private
  1575. */
  1576. async _handleRequest(req, res) {
  1577. const debug = this.getDebuggerFor(this._handleRequest);
  1578. const requestPath = (req.url || "/").replace(/\?.*$/, "");
  1579. debug(
  1580. "Preparing to handle an incoming request %s %v.",
  1581. req.method,
  1582. requestPath
  1583. );
  1584. const resolved = this.getService(RouteRegistry).matchRouteByRequest(req);
  1585. if (!resolved) {
  1586. debug("No route for the request %s %v.", req.method, requestPath);
  1587. this.getService(ErrorSender).send404(req, res);
  1588. } else {
  1589. const { route, params } = resolved;
  1590. const container = new import_js_service5.ServiceContainer(this.container);
  1591. const context = new RequestContext(container, req, res);
  1592. container.set(RequestContext, context);
  1593. container.set(import_http5.IncomingMessage, req);
  1594. container.set(import_http4.ServerResponse, res);
  1595. context.params = params;
  1596. let data;
  1597. try {
  1598. const reqDataOrPromise = this.getService(RequestParser).parse(req);
  1599. if (isPromise(reqDataOrPromise)) {
  1600. const reqData = await reqDataOrPromise;
  1601. Object.assign(context, reqData);
  1602. } else {
  1603. Object.assign(context, reqDataOrPromise);
  1604. }
  1605. const hookInvoker = this.getService(HookInvoker);
  1606. data = hookInvoker.invokeAndContinueUntilValueReceived(
  1607. route,
  1608. HookType.PRE_HANDLER,
  1609. res,
  1610. context
  1611. );
  1612. if (isPromise(data)) data = await data;
  1613. if (!isResponseSent(res) && data == null) {
  1614. data = route.handle(context);
  1615. if (isPromise(data)) data = await data;
  1616. let postHandlerData = hookInvoker.invokeAndContinueUntilValueReceived(
  1617. route,
  1618. HookType.POST_HANDLER,
  1619. res,
  1620. context,
  1621. data
  1622. );
  1623. if (isPromise(postHandlerData))
  1624. postHandlerData = await postHandlerData;
  1625. if (postHandlerData != null) data = postHandlerData;
  1626. }
  1627. } catch (error) {
  1628. this.getService(ErrorSender).send(req, res, error);
  1629. return;
  1630. }
  1631. if (!isResponseSent(res)) {
  1632. this.getService(DataSender).send(res, data);
  1633. }
  1634. }
  1635. }
  1636. /**
  1637. * Add hook.
  1638. *
  1639. * Example:
  1640. * ```
  1641. * import {TrieRouter} from '@e22m4u/js-trie-router';
  1642. * import {HookType} from '@e22m4u/js-trie-router';
  1643. *
  1644. * // Router instance.
  1645. * const router = new TrieRouter();
  1646. *
  1647. * // Adds the "preHandler" hook for each route.
  1648. * router.addHook(
  1649. * HookType.PRE_HANDLER,
  1650. * ctx => { ... },
  1651. * );
  1652. *
  1653. * // Adds the "postHandler" hook for each route.
  1654. * router.addHook(
  1655. * HookType.POST_HANDLER,
  1656. * ctx => { ... },
  1657. * );
  1658. * ```
  1659. *
  1660. * @param {string} type
  1661. * @param {Function} hook
  1662. * @returns {this}
  1663. */
  1664. addHook(type, hook) {
  1665. this.getService(HookRegistry).addHook(type, hook);
  1666. return this;
  1667. }
  1668. };
  1669. __name(_TrieRouter, "TrieRouter");
  1670. var TrieRouter = _TrieRouter;
  1671. // Annotate the CommonJS export names for ESM import in node:
  1672. 0 && (module.exports = {
  1673. BodyParser,
  1674. CHARACTER_ENCODING_LIST,
  1675. CookiesParser,
  1676. DataSender,
  1677. EXPOSED_ERROR_PROPERTIES,
  1678. ErrorSender,
  1679. HookInvoker,
  1680. HookRegistry,
  1681. HookType,
  1682. HttpMethod,
  1683. METHODS_WITH_BODY,
  1684. QueryParser,
  1685. RequestContext,
  1686. RequestParser,
  1687. Route,
  1688. RouteRegistry,
  1689. RouterOptions,
  1690. TrieRouter,
  1691. UNPARSABLE_MEDIA_TYPES,
  1692. createCookiesString,
  1693. createDebugger,
  1694. createError,
  1695. createRequestMock,
  1696. createResponseMock,
  1697. fetchRequestBody,
  1698. getRequestPathname,
  1699. isPromise,
  1700. isReadableStream,
  1701. isResponseSent,
  1702. isWritableStream,
  1703. parseContentType,
  1704. parseCookies,
  1705. parseJsonBody,
  1706. toCamelCase
  1707. });