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. HttpMethod: () => HttpMethod,
  42. METHODS_WITH_BODY: () => METHODS_WITH_BODY,
  43. QueryParser: () => QueryParser,
  44. RequestContext: () => RequestContext,
  45. RequestParser: () => RequestParser,
  46. Route: () => Route,
  47. RouteRegistry: () => RouteRegistry,
  48. RouterHookType: () => RouterHookType,
  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. var import_js_debug = require("@e22m4u/js-debug");
  72. // src/hooks/hook-invoker.js
  73. var import_js_format13 = require("@e22m4u/js-format");
  74. // src/utils/is-promise.js
  75. function isPromise(value) {
  76. if (!value) return false;
  77. if (typeof value !== "object") return false;
  78. return typeof value.then === "function";
  79. }
  80. __name(isPromise, "isPromise");
  81. // src/utils/create-error.js
  82. var import_js_format = require("@e22m4u/js-format");
  83. var import_js_format2 = require("@e22m4u/js-format");
  84. function createError(errorCtor, message, ...args) {
  85. if (typeof errorCtor !== "function")
  86. throw new import_js_format2.Errorf(
  87. 'The first argument of "createError" should be a constructor, but %v was given.',
  88. errorCtor
  89. );
  90. if (message != null && typeof message !== "string")
  91. throw new import_js_format2.Errorf(
  92. 'The second argument of "createError" should be a String, but %v was given.',
  93. message
  94. );
  95. if (message == null) return new errorCtor();
  96. const interpolatedMessage = (0, import_js_format.format)(message, ...args);
  97. return new errorCtor(interpolatedMessage);
  98. }
  99. __name(createError, "createError");
  100. // src/utils/parse-cookies.js
  101. var import_js_format3 = require("@e22m4u/js-format");
  102. function parseCookies(input) {
  103. if (typeof input !== "string")
  104. throw new import_js_format3.Errorf(
  105. 'The first parameter of "parseCookies" should be a String, but %v was given.',
  106. input
  107. );
  108. return input.split(";").filter((v) => v !== "").map((v) => v.split("=")).reduce((cookies, tuple) => {
  109. const key = decodeURIComponent(tuple[0]).trim();
  110. const value = tuple[1] !== void 0 ? decodeURIComponent(tuple[1]).trim() : "";
  111. cookies[key] = value;
  112. return cookies;
  113. }, {});
  114. }
  115. __name(parseCookies, "parseCookies");
  116. // src/utils/to-camel-case.js
  117. var import_js_format4 = require("@e22m4u/js-format");
  118. function toCamelCase(input) {
  119. if (typeof input !== "string")
  120. throw new import_js_format4.Errorf(
  121. 'The first argument of "toCamelCase" should be a String, but %v was given.',
  122. input
  123. );
  124. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  125. }
  126. __name(toCamelCase, "toCamelCase");
  127. // src/utils/create-debugger.js
  128. var import_debug = __toESM(require("debug"), 1);
  129. var import_js_format5 = require("@e22m4u/js-format");
  130. function createDebugger(name) {
  131. if (typeof name !== "string")
  132. throw new import_js_format5.Errorf(
  133. 'The first argument of "createDebugger" should be a String, but %v was given.',
  134. name
  135. );
  136. const debug = (0, import_debug.default)(`jsTrieRouter:${name}`);
  137. return function(message, ...args) {
  138. const interpolatedMessage = (0, import_js_format5.format)(message, ...args);
  139. return debug(interpolatedMessage);
  140. };
  141. }
  142. __name(createDebugger, "createDebugger");
  143. // src/utils/is-response-sent.js
  144. var import_js_format6 = require("@e22m4u/js-format");
  145. function isResponseSent(res) {
  146. if (!res || typeof res !== "object" || Array.isArray(res) || typeof res.headersSent !== "boolean") {
  147. throw new import_js_format6.Errorf(
  148. 'The first argument of "isResponseSent" should be an instance of ServerResponse, but %v was given.',
  149. res
  150. );
  151. }
  152. return res.headersSent;
  153. }
  154. __name(isResponseSent, "isResponseSent");
  155. // src/utils/is-readable-stream.js
  156. function isReadableStream(value) {
  157. if (!value || typeof value !== "object") return false;
  158. return typeof value.pipe === "function";
  159. }
  160. __name(isReadableStream, "isReadableStream");
  161. // src/utils/parse-content-type.js
  162. var import_js_format7 = require("@e22m4u/js-format");
  163. function parseContentType(input) {
  164. if (typeof input !== "string")
  165. throw new import_js_format7.Errorf(
  166. 'The parameter "input" of "parseContentType" should be a String, but %v was given.',
  167. input
  168. );
  169. const res = { mediaType: void 0, charset: void 0, boundary: void 0 };
  170. const re = /^\s*([^\s;/]+\/[^\s;/]+)(?:;\s*charset=([^\s;]+))?(?:;\s*boundary=([^\s;]+))?.*$/i;
  171. const matches = re.exec(input);
  172. if (matches && matches[1]) {
  173. res.mediaType = matches[1];
  174. if (matches[2]) res.charset = matches[2];
  175. if (matches[3]) res.boundary = matches[3];
  176. }
  177. return res;
  178. }
  179. __name(parseContentType, "parseContentType");
  180. // src/utils/is-writable-stream.js
  181. function isWritableStream(value) {
  182. if (!value || typeof value !== "object") return false;
  183. return typeof value.end === "function";
  184. }
  185. __name(isWritableStream, "isWritableStream");
  186. // src/utils/fetch-request-body.js
  187. var import_http_errors = __toESM(require("http-errors"), 1);
  188. var import_http = require("http");
  189. var import_js_format8 = require("@e22m4u/js-format");
  190. var CHARACTER_ENCODING_LIST = [
  191. "ascii",
  192. "utf8",
  193. "utf-8",
  194. "utf16le",
  195. "utf-16le",
  196. "ucs2",
  197. "ucs-2",
  198. "latin1"
  199. ];
  200. function fetchRequestBody(req, bodyBytesLimit = 0) {
  201. if (!(req instanceof import_http.IncomingMessage))
  202. throw new import_js_format8.Errorf(
  203. 'The first parameter of "fetchRequestBody" should be an IncomingMessage instance, but %v was given.',
  204. req
  205. );
  206. if (typeof bodyBytesLimit !== "number")
  207. throw new import_js_format8.Errorf(
  208. 'The parameter "bodyBytesLimit" of "fetchRequestBody" should be a number, but %v was given.',
  209. bodyBytesLimit
  210. );
  211. return new Promise((resolve, reject) => {
  212. const contentLength = parseInt(req.headers["content-length"] || "0", 10);
  213. if (bodyBytesLimit && contentLength && contentLength > bodyBytesLimit)
  214. throw createError(
  215. import_http_errors.default.PayloadTooLarge,
  216. "Request body limit is %s bytes, but %s bytes given.",
  217. bodyBytesLimit,
  218. contentLength
  219. );
  220. let encoding = "utf-8";
  221. const contentType = req.headers["content-type"] || "";
  222. if (contentType) {
  223. const parsedContentType = parseContentType(contentType);
  224. if (parsedContentType && parsedContentType.charset) {
  225. encoding = parsedContentType.charset.toLowerCase();
  226. if (!CHARACTER_ENCODING_LIST.includes(encoding))
  227. throw createError(
  228. import_http_errors.default.UnsupportedMediaType,
  229. "Request encoding %v is not supported.",
  230. encoding
  231. );
  232. }
  233. }
  234. const data = [];
  235. let receivedLength = 0;
  236. const onData = /* @__PURE__ */ __name((chunk) => {
  237. receivedLength += chunk.length;
  238. if (bodyBytesLimit && receivedLength > bodyBytesLimit) {
  239. req.removeAllListeners();
  240. const error = createError(
  241. import_http_errors.default.PayloadTooLarge,
  242. "Request body limit is %v bytes, but %v bytes given.",
  243. bodyBytesLimit,
  244. receivedLength
  245. );
  246. reject(error);
  247. return;
  248. }
  249. data.push(chunk);
  250. }, "onData");
  251. const onEnd = /* @__PURE__ */ __name(() => {
  252. req.removeAllListeners();
  253. if (contentLength && contentLength !== receivedLength) {
  254. const error = createError(
  255. import_http_errors.default.BadRequest,
  256. 'Received bytes do not match the "content-length" header.'
  257. );
  258. reject(error);
  259. return;
  260. }
  261. const buffer = Buffer.concat(data);
  262. const body = buffer.toString(encoding);
  263. resolve(body || void 0);
  264. }, "onEnd");
  265. const onError = /* @__PURE__ */ __name((error) => {
  266. req.removeAllListeners();
  267. reject((0, import_http_errors.default)(400, error));
  268. }, "onError");
  269. req.on("data", onData);
  270. req.on("end", onEnd);
  271. req.on("error", onError);
  272. req.resume();
  273. });
  274. }
  275. __name(fetchRequestBody, "fetchRequestBody");
  276. // src/utils/create-request-mock.js
  277. var import_net = require("net");
  278. var import_tls = require("tls");
  279. var import_http2 = require("http");
  280. var import_querystring = __toESM(require("querystring"), 1);
  281. var import_js_format10 = require("@e22m4u/js-format");
  282. // src/utils/create-cookies-string.js
  283. var import_js_format9 = require("@e22m4u/js-format");
  284. function createCookiesString(data) {
  285. if (!data || typeof data !== "object" || Array.isArray(data))
  286. throw new import_js_format9.Errorf(
  287. 'The first parameter of "createCookiesString" should be an Object, but %v was given.',
  288. data
  289. );
  290. let cookies = "";
  291. for (const key in data) {
  292. if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
  293. const val = data[key];
  294. if (val == null) continue;
  295. cookies += `${key}=${val}; `;
  296. }
  297. return cookies.trim();
  298. }
  299. __name(createCookiesString, "createCookiesString");
  300. // src/utils/create-request-mock.js
  301. function createRequestMock(patch) {
  302. if (patch != null && typeof patch !== "object" || Array.isArray(patch)) {
  303. throw new import_js_format10.Errorf(
  304. 'The first parameter of "createRequestMock" should be an Object, but %v was given.',
  305. patch
  306. );
  307. }
  308. patch = patch || {};
  309. if (patch.host != null && typeof patch.host !== "string")
  310. throw new import_js_format10.Errorf(
  311. 'The parameter "host" of "createRequestMock" should be a String, but %v was given.',
  312. patch.host
  313. );
  314. if (patch.method != null && typeof patch.method !== "string")
  315. throw new import_js_format10.Errorf(
  316. 'The parameter "method" of "createRequestMock" should be a String, but %v was given.',
  317. patch.method
  318. );
  319. if (patch.secure != null && typeof patch.secure !== "boolean")
  320. throw new import_js_format10.Errorf(
  321. 'The parameter "secure" of "createRequestMock" should be a Boolean, but %v was given.',
  322. patch.secure
  323. );
  324. if (patch.path != null && typeof patch.path !== "string")
  325. throw new import_js_format10.Errorf(
  326. 'The parameter "path" of "createRequestMock" should be a String, but %v was given.',
  327. patch.path
  328. );
  329. if (patch.query != null && typeof patch.query !== "object" && typeof patch.query !== "string" || Array.isArray(patch.query)) {
  330. throw new import_js_format10.Errorf(
  331. 'The parameter "query" of "createRequestMock" should be a String or Object, but %v was given.',
  332. patch.query
  333. );
  334. }
  335. if (patch.cookies != null && typeof patch.cookies !== "string" && typeof patch.cookies !== "object" || Array.isArray(patch.cookies)) {
  336. throw new import_js_format10.Errorf(
  337. 'The parameter "cookies" of "createRequestMock" should be a String or Object, but %v was given.',
  338. patch.cookies
  339. );
  340. }
  341. if (patch.headers != null && typeof patch.headers !== "object" || Array.isArray(patch.headers)) {
  342. throw new import_js_format10.Errorf(
  343. 'The parameter "headers" of "createRequestMock" should be an Object, but %v was given.',
  344. patch.headers
  345. );
  346. }
  347. if (patch.stream != null && !isReadableStream(patch.stream))
  348. throw new import_js_format10.Errorf(
  349. 'The parameter "stream" of "createRequestMock" should be a Stream, but %v was given.',
  350. patch.stream
  351. );
  352. if (patch.encoding != null) {
  353. if (typeof patch.encoding !== "string")
  354. throw new import_js_format10.Errorf(
  355. 'The parameter "encoding" of "createRequestMock" should be a String, but %v was given.',
  356. patch.encoding
  357. );
  358. if (!CHARACTER_ENCODING_LIST.includes(patch.encoding))
  359. throw new import_js_format10.Errorf(
  360. "Character encoding %v is not supported.",
  361. patch.encoding
  362. );
  363. }
  364. if (patch.stream) {
  365. if (patch.secure != null)
  366. throw new import_js_format10.Errorf(
  367. 'The "createRequestMock" does not allow specifying the "stream" and "secure" options simultaneously.'
  368. );
  369. if (patch.body != null)
  370. throw new import_js_format10.Errorf(
  371. 'The "createRequestMock" does not allow specifying the "stream" and "body" options simultaneously.'
  372. );
  373. if (patch.encoding != null)
  374. throw new import_js_format10.Errorf(
  375. 'The "createRequestMock" does not allow specifying the "stream" and "encoding" options simultaneously.'
  376. );
  377. }
  378. const req = patch.stream || createRequestStream(patch.secure, patch.body, patch.encoding);
  379. req.url = createRequestUrl(patch.path || "/", patch.query);
  380. req.headers = createRequestHeaders(
  381. patch.host,
  382. patch.secure,
  383. patch.body,
  384. patch.cookies,
  385. patch.encoding,
  386. patch.headers
  387. );
  388. req.method = (patch.method || "get").toUpperCase();
  389. return req;
  390. }
  391. __name(createRequestMock, "createRequestMock");
  392. function createRequestStream(secure, body, encoding) {
  393. if (encoding != null && typeof encoding !== "string")
  394. throw new import_js_format10.Errorf(
  395. 'The parameter "encoding" of "createRequestStream" should be a String, but %v was given.',
  396. encoding
  397. );
  398. encoding = encoding || "utf-8";
  399. let socket = new import_net.Socket();
  400. if (secure) socket = new import_tls.TLSSocket(socket);
  401. const req = new import_http2.IncomingMessage(socket);
  402. if (body != null) {
  403. if (typeof body === "string") {
  404. req.push(body, encoding);
  405. } else if (Buffer.isBuffer(body)) {
  406. req.push(body);
  407. } else {
  408. req.push(JSON.stringify(body));
  409. }
  410. }
  411. req.push(null);
  412. return req;
  413. }
  414. __name(createRequestStream, "createRequestStream");
  415. function createRequestUrl(path, query) {
  416. if (typeof path !== "string")
  417. throw new import_js_format10.Errorf(
  418. 'The parameter "path" of "createRequestUrl" should be a String, but %v was given.',
  419. path
  420. );
  421. if (query != null && typeof query !== "string" && typeof query !== "object" || Array.isArray(query)) {
  422. throw new import_js_format10.Errorf(
  423. 'The parameter "query" of "createRequestUrl" should be a String or Object, but %v was given.',
  424. query
  425. );
  426. }
  427. let url = ("/" + path).replace("//", "/");
  428. if (typeof query === "object") {
  429. const qs = import_querystring.default.stringify(query);
  430. if (qs) url += `?${qs}`;
  431. } else if (typeof query === "string") {
  432. url += `?${query.replace(/^\?/, "")}`;
  433. }
  434. return url;
  435. }
  436. __name(createRequestUrl, "createRequestUrl");
  437. function createRequestHeaders(host, secure, body, cookies, encoding, headers) {
  438. if (host != null && typeof host !== "string")
  439. throw new import_js_format10.Errorf(
  440. 'The parameter "host" of "createRequestHeaders" a non-empty String, but %v was given.',
  441. host
  442. );
  443. host = host || "localhost";
  444. if (secure != null && typeof secure !== "boolean")
  445. throw new import_js_format10.Errorf(
  446. 'The parameter "secure" of "createRequestHeaders" should be a String, but %v was given.',
  447. secure
  448. );
  449. secure = Boolean(secure);
  450. if (cookies != null && typeof cookies !== "object" && typeof cookies !== "string" || Array.isArray(cookies)) {
  451. throw new import_js_format10.Errorf(
  452. 'The parameter "cookies" of "createRequestHeaders" should be a String or Object, but %v was given.',
  453. cookies
  454. );
  455. }
  456. if (headers != null && typeof headers !== "object" || Array.isArray(headers)) {
  457. throw new import_js_format10.Errorf(
  458. 'The parameter "headers" of "createRequestHeaders" should be an Object, but %v was given.',
  459. headers
  460. );
  461. }
  462. headers = headers || {};
  463. if (encoding != null && typeof encoding !== "string")
  464. throw new import_js_format10.Errorf(
  465. 'The parameter "encoding" of "createRequestHeaders" should be a String, but %v was given.',
  466. encoding
  467. );
  468. encoding = encoding || "utf-8";
  469. const obj = { ...headers };
  470. obj["host"] = host;
  471. if (secure) obj["x-forwarded-proto"] = "https";
  472. if (cookies != null) {
  473. if (typeof cookies === "string") {
  474. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  475. obj["cookie"] += obj["cookie"] ? `; ${cookies}` : cookies;
  476. } else if (typeof cookies === "object") {
  477. obj["cookie"] = obj["cookie"] ? obj["cookie"] : "";
  478. const newCookies = createCookiesString(cookies);
  479. obj["cookie"] += obj["cookie"] ? `; ${newCookies}` : newCookies;
  480. }
  481. }
  482. if (obj["content-type"] == null) {
  483. if (typeof body === "string") {
  484. obj["content-type"] = "text/plain";
  485. } else if (Buffer.isBuffer(body)) {
  486. obj["content-type"] = "application/octet-stream";
  487. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  488. obj["content-type"] = "application/json";
  489. }
  490. }
  491. if (body != null && obj["content-length"] == null) {
  492. if (typeof body === "string") {
  493. const length = Buffer.byteLength(body, encoding);
  494. obj["content-length"] = String(length);
  495. } else if (Buffer.isBuffer(body)) {
  496. const length = Buffer.byteLength(body);
  497. obj["content-length"] = String(length);
  498. } else if (typeof body === "object" || typeof body === "boolean" || typeof body === "number") {
  499. const json = JSON.stringify(body);
  500. const length = Buffer.byteLength(json, encoding);
  501. obj["content-length"] = String(length);
  502. }
  503. }
  504. return obj;
  505. }
  506. __name(createRequestHeaders, "createRequestHeaders");
  507. // src/utils/create-response-mock.js
  508. var import_stream = require("stream");
  509. function createResponseMock() {
  510. const res = new import_stream.PassThrough();
  511. patchEncoding(res);
  512. patchHeaders(res);
  513. patchBody(res);
  514. return res;
  515. }
  516. __name(createResponseMock, "createResponseMock");
  517. function patchEncoding(res) {
  518. Object.defineProperty(res, "_encoding", {
  519. configurable: true,
  520. writable: true,
  521. value: void 0
  522. });
  523. Object.defineProperty(res, "setEncoding", {
  524. configurable: true,
  525. value: /* @__PURE__ */ __name(function(enc) {
  526. this._encoding = enc;
  527. return this;
  528. }, "value")
  529. });
  530. Object.defineProperty(res, "getEncoding", {
  531. configurable: true,
  532. value: /* @__PURE__ */ __name(function() {
  533. return this._encoding;
  534. }, "value")
  535. });
  536. }
  537. __name(patchEncoding, "patchEncoding");
  538. function patchHeaders(res) {
  539. Object.defineProperty(res, "_headersSent", {
  540. configurable: true,
  541. writable: true,
  542. value: false
  543. });
  544. Object.defineProperty(res, "headersSent", {
  545. configurable: true,
  546. get() {
  547. return this._headersSent;
  548. }
  549. });
  550. Object.defineProperty(res, "_headers", {
  551. configurable: true,
  552. writable: true,
  553. value: {}
  554. });
  555. Object.defineProperty(res, "setHeader", {
  556. configurable: true,
  557. value: /* @__PURE__ */ __name(function(name, value) {
  558. if (this.headersSent)
  559. throw new Error(
  560. "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"
  561. );
  562. const key = name.toLowerCase();
  563. this._headers[key] = String(value);
  564. return this;
  565. }, "value")
  566. });
  567. Object.defineProperty(res, "getHeader", {
  568. configurable: true,
  569. value: /* @__PURE__ */ __name(function(name) {
  570. return this._headers[name.toLowerCase()];
  571. }, "value")
  572. });
  573. Object.defineProperty(res, "getHeaders", {
  574. configurable: true,
  575. value: /* @__PURE__ */ __name(function() {
  576. return JSON.parse(JSON.stringify(this._headers));
  577. }, "value")
  578. });
  579. }
  580. __name(patchHeaders, "patchHeaders");
  581. function patchBody(res) {
  582. let resolve, reject;
  583. const promise = new Promise((res2, rej) => {
  584. resolve = res2;
  585. reject = rej;
  586. });
  587. const data = [];
  588. res.on("data", (c) => data.push(c));
  589. res.on("error", (e) => reject(e));
  590. res.on("end", () => {
  591. res._headersSent = true;
  592. resolve(Buffer.concat(data));
  593. });
  594. Object.defineProperty(res, "getBody", {
  595. configurable: true,
  596. value: /* @__PURE__ */ __name(function() {
  597. return promise.then((buffer) => {
  598. const enc = this.getEncoding();
  599. const str = buffer.toString(enc);
  600. return data.length ? str : void 0;
  601. });
  602. }, "value")
  603. });
  604. }
  605. __name(patchBody, "patchBody");
  606. // src/utils/get-request-pathname.js
  607. var import_js_format11 = require("@e22m4u/js-format");
  608. function getRequestPathname(req) {
  609. if (!req || typeof req !== "object" || Array.isArray(req) || typeof req.url !== "string") {
  610. throw new import_js_format11.Errorf(
  611. 'The first argument of "getRequestPathname" should be an instance of IncomingMessage, but %v was given.',
  612. req
  613. );
  614. }
  615. return (req.url || "/").replace(/\?.*$/, "");
  616. }
  617. __name(getRequestPathname, "getRequestPathname");
  618. // src/hooks/hook-registry.js
  619. var import_js_format12 = require("@e22m4u/js-format");
  620. var RouterHookType = {
  621. PRE_HANDLER: "preHandler",
  622. POST_HANDLER: "postHandler"
  623. };
  624. var _HookRegistry = class _HookRegistry {
  625. /**
  626. * Hooks.
  627. *
  628. * @type {Map<string, Function[]>}
  629. * @private
  630. */
  631. _hooks = /* @__PURE__ */ new Map();
  632. /**
  633. * Add hook.
  634. *
  635. * @param {string} type
  636. * @param {Function} hook
  637. * @returns {this}
  638. */
  639. addHook(type, hook) {
  640. if (!type || typeof type !== "string")
  641. throw new import_js_format12.Errorf("The hook type is required, but %v was given.", type);
  642. if (!Object.values(RouterHookType).includes(type))
  643. throw new import_js_format12.Errorf("The hook type %v is not supported.", type);
  644. if (!hook || typeof hook !== "function")
  645. throw new import_js_format12.Errorf(
  646. "The hook %v should be a Function, but %v was given.",
  647. type,
  648. hook
  649. );
  650. const hooks = this._hooks.get(type) || [];
  651. hooks.push(hook);
  652. this._hooks.set(type, hooks);
  653. return this;
  654. }
  655. /**
  656. * Has hook.
  657. *
  658. * @param {string} type
  659. * @param {Function} hook
  660. * @returns {boolean}
  661. */
  662. hasHook(type, hook) {
  663. if (!type || typeof type !== "string")
  664. throw new import_js_format12.Errorf("The hook type is required, but %v was given.", type);
  665. if (!Object.values(RouterHookType).includes(type))
  666. throw new import_js_format12.Errorf("The hook type %v is not supported.", type);
  667. if (!hook || typeof hook !== "function")
  668. throw new import_js_format12.Errorf(
  669. "The hook %v should be a Function, but %v was given.",
  670. type,
  671. hook
  672. );
  673. const hooks = this._hooks.get(type) || [];
  674. return hooks.indexOf(hook) > -1;
  675. }
  676. /**
  677. * Get hooks.
  678. *
  679. * @param {string} type
  680. * @returns {Function[]}
  681. */
  682. getHooks(type) {
  683. if (!type || typeof type !== "string")
  684. throw new import_js_format12.Errorf("The hook type is required, but %v was given.", type);
  685. if (!Object.values(RouterHookType).includes(type))
  686. throw new import_js_format12.Errorf("The hook type %v is not supported.", type);
  687. return this._hooks.get(type) || [];
  688. }
  689. };
  690. __name(_HookRegistry, "HookRegistry");
  691. var HookRegistry = _HookRegistry;
  692. // src/debuggable-service.js
  693. var import_js_service = require("@e22m4u/js-service");
  694. var MODULE_DEBUG_NAMESPACE = "jsTrieRouter";
  695. var _DebuggableService = class _DebuggableService extends import_js_service.DebuggableService {
  696. /**
  697. * Constructor.
  698. *
  699. * @param {ServiceContainer} container
  700. */
  701. constructor(container = void 0) {
  702. super(container, {
  703. namespace: MODULE_DEBUG_NAMESPACE,
  704. noEnvironmentNamespace: true
  705. });
  706. }
  707. };
  708. __name(_DebuggableService, "DebuggableService");
  709. var DebuggableService = _DebuggableService;
  710. // src/hooks/hook-invoker.js
  711. var _HookInvoker = class _HookInvoker extends DebuggableService {
  712. /**
  713. * Invoke and continue until value received.
  714. *
  715. * @param {Route} route
  716. * @param {string} hookType
  717. * @param {import('http').ServerResponse} response
  718. * @param {*[]} args
  719. * @returns {Promise<*>|*}
  720. */
  721. invokeAndContinueUntilValueReceived(route, hookType, response, ...args) {
  722. if (!route || !(route instanceof Route))
  723. throw new import_js_format13.Errorf(
  724. 'The parameter "route" of the HookInvoker.invokeAndContinueUntilValueReceived should be a Route instance, but %v was given.',
  725. route
  726. );
  727. if (!hookType || typeof hookType !== "string")
  728. throw new import_js_format13.Errorf(
  729. 'The parameter "hookType" of the HookInvoker.invokeAndContinueUntilValueReceived should be a non-empty String, but %v was given.',
  730. hookType
  731. );
  732. if (!Object.values(RouterHookType).includes(hookType))
  733. throw new import_js_format13.Errorf("The hook type %v is not supported.", hookType);
  734. if (!response || typeof response !== "object" || Array.isArray(response) || typeof response.headersSent !== "boolean") {
  735. throw new import_js_format13.Errorf(
  736. 'The parameter "response" of the HookInvoker.invokeAndContinueUntilValueReceived should be a ServerResponse instance, but %v was given.',
  737. response
  738. );
  739. }
  740. const hooks = [
  741. ...this.getService(HookRegistry).getHooks(hookType),
  742. ...route.hookRegistry.getHooks(hookType)
  743. ];
  744. let result = void 0;
  745. for (const hook of hooks) {
  746. if (isResponseSent(response)) {
  747. result = response;
  748. break;
  749. }
  750. if (result == null) {
  751. result = hook(...args);
  752. } else if (isPromise(result)) {
  753. result = result.then((prevVal) => {
  754. if (isResponseSent(response)) {
  755. return;
  756. }
  757. if (prevVal != null) return prevVal;
  758. return hook(...args);
  759. });
  760. } else {
  761. break;
  762. }
  763. }
  764. return result;
  765. }
  766. };
  767. __name(_HookInvoker, "HookInvoker");
  768. var HookInvoker = _HookInvoker;
  769. // src/route.js
  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(RouterHookType.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(RouterHookType.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. RouterHookType.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. RouterHookType.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 {RouterHookType} 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. * RouterHookType.PRE_HANDLER,
  1650. * ctx => { ... },
  1651. * );
  1652. *
  1653. * // Adds the "postHandler" hook for each route.
  1654. * router.addHook(
  1655. * RouterHookType.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. HttpMethod,
  1682. METHODS_WITH_BODY,
  1683. QueryParser,
  1684. RequestContext,
  1685. RequestParser,
  1686. Route,
  1687. RouteRegistry,
  1688. RouterHookType,
  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. });