index.cjs 57 KB

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