index.cjs 55 KB

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