index.cjs 57 KB

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