index.cjs 56 KB

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