index.cjs 55 KB

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