@mahameru/diatrema 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +1 -0
  2. package/container-error.cjs +45 -0
  3. package/container-error.cjs.map +1 -0
  4. package/container-error.d.cts +7 -0
  5. package/container-error.d.ts +7 -0
  6. package/container-error.js +22 -0
  7. package/container-error.js.map +1 -0
  8. package/container.cjs +322 -0
  9. package/container.cjs.map +1 -0
  10. package/container.d.cts +62 -0
  11. package/container.d.ts +62 -0
  12. package/container.js +289 -0
  13. package/container.js.map +1 -0
  14. package/diatrema.cjs +130 -0
  15. package/diatrema.cjs.map +1 -0
  16. package/diatrema.d.cts +73 -0
  17. package/diatrema.d.ts +71 -0
  18. package/diatrema.js +107 -0
  19. package/diatrema.js.map +1 -0
  20. package/event-emitter.cjs +68 -0
  21. package/event-emitter.cjs.map +1 -0
  22. package/event-emitter.d.cts +11 -0
  23. package/event-emitter.d.ts +11 -0
  24. package/event-emitter.js +45 -0
  25. package/event-emitter.js.map +1 -0
  26. package/helpers.cjs +93 -0
  27. package/helpers.cjs.map +1 -0
  28. package/helpers.d.cts +22 -0
  29. package/helpers.d.ts +22 -0
  30. package/helpers.js +67 -0
  31. package/helpers.js.map +1 -0
  32. package/http-server-error.cjs +44 -0
  33. package/http-server-error.cjs.map +1 -0
  34. package/http-server-error.d.cts +7 -0
  35. package/http-server-error.d.ts +7 -0
  36. package/http-server-error.js +21 -0
  37. package/http-server-error.js.map +1 -0
  38. package/http-server.cjs +382 -0
  39. package/http-server.cjs.map +1 -0
  40. package/http-server.d.cts +81 -0
  41. package/http-server.d.ts +81 -0
  42. package/http-server.js +359 -0
  43. package/http-server.js.map +1 -0
  44. package/index.cjs +66 -0
  45. package/index.cjs.map +1 -0
  46. package/index.d.cts +19 -0
  47. package/index.d.ts +19 -0
  48. package/index.js +19 -0
  49. package/index.js.map +1 -0
  50. package/logger.cjs +52 -0
  51. package/logger.cjs.map +1 -0
  52. package/logger.d.cts +9 -0
  53. package/logger.d.ts +9 -0
  54. package/logger.js +29 -0
  55. package/logger.js.map +1 -0
  56. package/mahameru-error.cjs +42 -0
  57. package/mahameru-error.cjs.map +1 -0
  58. package/mahameru-error.d.cts +5 -0
  59. package/mahameru-error.d.ts +5 -0
  60. package/mahameru-error.js +19 -0
  61. package/mahameru-error.js.map +1 -0
  62. package/mahameru-request.cjs +79 -0
  63. package/mahameru-request.cjs.map +1 -0
  64. package/mahameru-request.d.cts +3 -0
  65. package/mahameru-request.d.ts +3 -0
  66. package/mahameru-request.js +56 -0
  67. package/mahameru-request.js.map +1 -0
  68. package/mahameru-response.cjs +71 -0
  69. package/mahameru-response.cjs.map +1 -0
  70. package/mahameru-response.d.cts +17 -0
  71. package/mahameru-response.d.ts +17 -0
  72. package/mahameru-response.js +48 -0
  73. package/mahameru-response.js.map +1 -0
  74. package/mahameru-server-error.cjs +54 -0
  75. package/mahameru-server-error.cjs.map +1 -0
  76. package/mahameru-server-error.d.cts +19 -0
  77. package/mahameru-server-error.d.ts +19 -0
  78. package/mahameru-server-error.js +31 -0
  79. package/mahameru-server-error.js.map +1 -0
  80. package/module-error.cjs +46 -0
  81. package/module-error.cjs.map +1 -0
  82. package/module-error.d.cts +12 -0
  83. package/module-error.d.ts +12 -0
  84. package/module-error.js +23 -0
  85. package/module-error.js.map +1 -0
  86. package/package.json +40 -0
  87. package/route.cjs +128 -0
  88. package/route.cjs.map +1 -0
  89. package/route.d.cts +46 -0
  90. package/route.d.ts +46 -0
  91. package/route.js +105 -0
  92. package/route.js.map +1 -0
  93. package/scripts/preinstall.js +9 -0
  94. package/types-BRwWYiUN.d.ts +108 -0
  95. package/types-CipcRmc9.d.cts +108 -0
  96. package/types.cjs +40 -0
  97. package/types.cjs.map +1 -0
  98. package/types.d.cts +3 -0
  99. package/types.d.ts +3 -0
  100. package/types.js +16 -0
  101. package/types.js.map +1 -0
@@ -0,0 +1,12 @@
1
+ declare class ModuleError extends Error {
2
+ readonly detail?: {
3
+ path: string;
4
+ moduleName: string;
5
+ };
6
+ constructor(message: string, detail?: {
7
+ path: string;
8
+ moduleName: string;
9
+ });
10
+ }
11
+
12
+ export { ModuleError };
@@ -0,0 +1,12 @@
1
+ declare class ModuleError extends Error {
2
+ readonly detail?: {
3
+ path: string;
4
+ moduleName: string;
5
+ };
6
+ constructor(message: string, detail?: {
7
+ path: string;
8
+ moduleName: string;
9
+ });
10
+ }
11
+
12
+ export { ModuleError };
@@ -0,0 +1,23 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ class ModuleError extends Error {
4
+ static {
5
+ __name(this, "ModuleError");
6
+ }
7
+ detail;
8
+ constructor(message, detail) {
9
+ super(message);
10
+ if (detail) {
11
+ this.detail = {
12
+ path: detail.path,
13
+ moduleName: detail.moduleName || "UNKNOWN"
14
+ };
15
+ }
16
+ Object.setPrototypeOf(this, ModuleError.prototype);
17
+ delete this.stack;
18
+ }
19
+ }
20
+ export {
21
+ ModuleError
22
+ };
23
+ //# sourceMappingURL=module-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/module-error.ts"],"sourcesContent":["export class ModuleError extends Error {\r\n public readonly detail?: {\r\n path: string;\r\n moduleName: string;\r\n };\r\n\r\n constructor(message: string, detail?: { path: string; moduleName: string }) {\r\n super(message);\r\n\r\n if (detail) {\r\n this.detail = {\r\n path: detail.path,\r\n moduleName: detail.moduleName || 'UNKNOWN'\r\n };\r\n }\r\n\r\n Object.setPrototypeOf(this, ModuleError.prototype);\r\n\r\n delete this.stack;\r\n }\r\n}\r\n"],"mappings":";;AAAO,MAAM,oBAAoB,MAAM;AAAA,EAAvC,OAAuC;AAAA;AAAA;AAAA,EACnB;AAAA,EAKhB,YAAY,SAAiB,QAA+C;AACxE,UAAM,OAAO;AAEb,QAAI,QAAQ;AACR,WAAK,SAAS;AAAA,QACV,MAAM,OAAO;AAAA,QACb,YAAY,OAAO,cAAc;AAAA,MACrC;AAAA,IACJ;AAEA,WAAO,eAAe,MAAM,YAAY,SAAS;AAEjD,WAAO,KAAK;AAAA,EAChB;AACJ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@mahameru/diatrema",
3
+ "version": "0.0.0",
4
+ "description": "The core engine of MahameruJS. Just like a volcanic diatreme, it serves as the essential conduit that powers and drives the entire framework ecosystem.",
5
+ "main": "./index.cjs",
6
+ "module": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "import": "./index.js",
13
+ "require": "./index.cjs"
14
+ }
15
+ },
16
+ "scripts": {
17
+ "typecheck": "tsc --noEmit --project tsconfig.json",
18
+ "build": "tsup --config tsup.config.ts && node ./scripts/post-build.js",
19
+ "dev": "cross-env NODE_ENV=development tsup --config tsup.config.ts && node ./scripts/post-build.js"
20
+ },
21
+ "keywords": [
22
+ "node",
23
+ "framework",
24
+ "mahameru",
25
+ "mahamerujs",
26
+ "core",
27
+ "diatrema",
28
+ "core-engine"
29
+ ],
30
+ "author": "Bintan <hello@bintvn.co>",
31
+ "license": "ISC",
32
+ "devDependencies": {
33
+ "@types/node": "^26.1.0",
34
+ "cross-env": "^10.1.0",
35
+ "esbuild-fix-imports-plugin": "^1.0.23",
36
+ "tsup": "^8.5.1",
37
+ "type-fest": "^5.8.0",
38
+ "typescript": "^6.0.3"
39
+ }
40
+ }
package/route.cjs ADDED
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var route_exports = {};
21
+ __export(route_exports, {
22
+ Route: () => Route
23
+ });
24
+ module.exports = __toCommonJS(route_exports);
25
+ var import_node_path = require("node:path");
26
+ class Route {
27
+ static {
28
+ __name(this, "Route");
29
+ }
30
+ options = {
31
+ dev: false,
32
+ routesPath: (0, import_node_path.join)(process.cwd(), ".mahameru", "routes")
33
+ };
34
+ dependencies;
35
+ constructor(arg1, arg2) {
36
+ if (typeof arg2 !== "undefined")
37
+ this.options = { ...this.options, ...arg1 };
38
+ if (typeof arg2 !== "undefined") {
39
+ this.dependencies = arg2;
40
+ } else {
41
+ this.dependencies = arg1;
42
+ }
43
+ }
44
+ normalizePathForMatching(path) {
45
+ if (path.length > 1 && path.endsWith("/")) {
46
+ return path.slice(0, -1);
47
+ }
48
+ return path;
49
+ }
50
+ findMatchedRoute(matchUrl) {
51
+ let matchedRoute = null;
52
+ let matchResult = null;
53
+ for (const route of this.dependencies.container.getRouteItems()) {
54
+ const result = route.regex.exec(matchUrl);
55
+ if (result) {
56
+ matchedRoute = route;
57
+ matchResult = result;
58
+ break;
59
+ }
60
+ }
61
+ return { matchedRoute, matchResult };
62
+ }
63
+ async runNotFoundHandler(request, method) {
64
+ if (!this.dependencies.container.notFoundHandler)
65
+ return void 0;
66
+ const handler = this.dependencies.container.notFoundHandler[method];
67
+ if (typeof handler !== "function") {
68
+ return void 0;
69
+ }
70
+ const response = await handler(request, this.dependencies.container, { params: {} });
71
+ return this.normalizeMahameruResponse(
72
+ response,
73
+ `Not found handler for method '${method}' must return a MahameruResponse instance.`
74
+ );
75
+ }
76
+ async resolveRoute(request) {
77
+ const rawReqPath = request.url.split("?")[0] || "/";
78
+ const rawReqUrl = rawReqPath.replace(/\/+/g, "/");
79
+ const matchUrl = this.normalizePathForMatching(rawReqUrl);
80
+ let { matchedRoute, matchResult } = this.findMatchedRoute(matchUrl);
81
+ if (!matchedRoute || !matchResult)
82
+ return {
83
+ matchedRoute: null,
84
+ matchResult: null,
85
+ notFoundResponse: await this.runNotFoundHandler(request, request.method) || this.dependencies.MahameruResponse.json(
86
+ { error: "Not Found" },
87
+ { status: 404 }
88
+ )
89
+ };
90
+ return { matchedRoute, matchResult };
91
+ }
92
+ isMahameruResponseLike(value) {
93
+ if (!value || typeof value !== "object") {
94
+ return false;
95
+ }
96
+ if (!("status" in value) || typeof value.status !== "number") {
97
+ return false;
98
+ }
99
+ if (!("body" in value)) {
100
+ return false;
101
+ }
102
+ if (!("headers" in value) || value.headers === void 0) {
103
+ return true;
104
+ }
105
+ if (value.headers instanceof Headers) {
106
+ return true;
107
+ }
108
+ return typeof value.headers === "object" && value.headers !== null && !Array.isArray(value.headers);
109
+ }
110
+ normalizeMahameruResponse(value, errorMessage) {
111
+ if (value instanceof this.dependencies.MahameruResponse) {
112
+ return value;
113
+ }
114
+ if (!this.isMahameruResponseLike(value)) {
115
+ throw new this.dependencies.HttpServerError(errorMessage);
116
+ }
117
+ const normalizedHeaders = value.headers instanceof Headers ? Object.fromEntries(value.headers.entries()) : value.headers;
118
+ return new this.dependencies.MahameruResponse(value.body, {
119
+ status: value.status,
120
+ headers: normalizedHeaders
121
+ });
122
+ }
123
+ }
124
+ // Annotate the CommonJS export names for ESM import in node:
125
+ 0 && (module.exports = {
126
+ Route
127
+ });
128
+ //# sourceMappingURL=route.cjs.map
package/route.cjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/route.ts"],"sourcesContent":["import { join } from 'node:path';\n\nimport type { MahameruRequest } from './mahameru-request';\nimport type { MahameruResponse } from './mahameru-response';\nimport type { Container } from './container';\nimport type { HttpServerError } from './http-server-error';\nimport type { HTTPMethod, RouteHandlerContext, RouteItem } from './types';\n\nexport type RouteOptions = {\n dev: boolean;\n routesPath: string;\n};\n\nexport type RouteDependencies = {\n container: Container;\n HttpServerError: typeof HttpServerError;\n MahameruResponse: typeof MahameruResponse;\n};\n\nexport class Route {\n public readonly options: RouteOptions = {\n dev: false,\n routesPath: join(process.cwd(), '.mahameru', 'routes')\n }\n protected dependencies: RouteDependencies;\n\n constructor(\n dependencies: RouteDependencies\n )\n constructor(\n options: Partial<RouteOptions>,\n dependencies: RouteDependencies\n )\n constructor(\n arg1: Partial<RouteOptions> | RouteDependencies,\n arg2?: RouteDependencies\n ) {\n if (typeof arg2 !== 'undefined')\n this.options = { ...this.options, ...arg1 as Partial<RouteOptions> };\n\n if (typeof arg2 !== 'undefined') {\n this.dependencies = arg2;\n } else {\n this.dependencies = arg1 as RouteDependencies;\n }\n }\n\n normalizePathForMatching(path: string): string {\n if (path.length > 1 && path.endsWith('/')) {\n return path.slice(0, -1);\n }\n\n return path;\n }\n\n findMatchedRoute(matchUrl: string) {\n let matchedRoute: RouteItem | null = null;\n let matchResult: RegExpExecArray | null = null;\n\n for (const route of this.dependencies.container.getRouteItems()) {\n const result = route.regex.exec(matchUrl);\n\n if (result) {\n matchedRoute = route;\n matchResult = result;\n\n break;\n }\n }\n\n return { matchedRoute, matchResult };\n }\n\n async runNotFoundHandler(request: MahameruRequest, method: HTTPMethod): Promise<MahameruResponse | undefined> {\n if (!this.dependencies.container.notFoundHandler)\n return undefined;\n\n const handler = this.dependencies.container.notFoundHandler[method];\n\n if (typeof handler !== 'function') {\n return undefined;\n }\n\n const response = await handler(request, this.dependencies.container, { params: {} } satisfies RouteHandlerContext);\n\n return this.normalizeMahameruResponse(\n response,\n `Not found handler for method '${method}' must return a MahameruResponse instance.`\n );\n }\n\n async resolveRoute(request: MahameruRequest) {\n const rawReqPath = request.url.split('?')[0] || '/';\n const rawReqUrl = rawReqPath.replace(/\\/+/g, '/');\n const matchUrl = this.normalizePathForMatching(rawReqUrl);\n\n let { matchedRoute, matchResult } = this.findMatchedRoute(matchUrl);\n\n if (!matchedRoute || !matchResult)\n return {\n matchedRoute: null,\n matchResult: null,\n notFoundResponse: await this.runNotFoundHandler(request, request.method) || this.dependencies.MahameruResponse.json(\n { error: 'Not Found' },\n { status: 404 }\n )\n };\n\n return { matchedRoute, matchResult };\n }\n\n protected isMahameruResponseLike(value: unknown): value is { body: unknown; status: number; headers?: Headers | Record<string, string> } {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n if (!('status' in value) || typeof value.status !== 'number') {\n return false;\n }\n\n if (!('body' in value)) {\n return false;\n }\n\n if (!('headers' in value) || value.headers === undefined) {\n return true;\n }\n\n if (value.headers instanceof Headers) {\n return true;\n }\n\n return typeof value.headers === 'object' && value.headers !== null && !Array.isArray(value.headers);\n }\n\n protected normalizeMahameruResponse(value: unknown, errorMessage: string): MahameruResponse {\n if (value instanceof this.dependencies.MahameruResponse) {\n return value;\n }\n\n if (!this.isMahameruResponseLike(value)) {\n throw new this.dependencies.HttpServerError(errorMessage);\n }\n\n const normalizedHeaders = value.headers instanceof Headers\n ? Object.fromEntries(value.headers.entries())\n : value.headers;\n\n return new this.dependencies.MahameruResponse(value.body, {\n status: value.status,\n headers: normalizedHeaders\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAqB;AAmBd,MAAM,MAAM;AAAA,EAnBnB,OAmBmB;AAAA;AAAA;AAAA,EACC,UAAwB;AAAA,IACpC,KAAK;AAAA,IACL,gBAAY,uBAAK,QAAQ,IAAI,GAAG,aAAa,QAAQ;AAAA,EACzD;AAAA,EACU;AAAA,EASV,YACI,MACA,MACF;AACE,QAAI,OAAO,SAAS;AAChB,WAAK,UAAU,EAAE,GAAG,KAAK,SAAS,GAAG,KAA8B;AAEvE,QAAI,OAAO,SAAS,aAAa;AAC7B,WAAK,eAAe;AAAA,IAC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Aa,iBAAiB;AAAA,UAC3G,EAAE,OAAO,YAAY;AAAA,UACrB,EAAE,QAAQ,IAAI;AAAA,QAClB;AAAA,MACJ;AAEJ,WAAO,EAAE,cAAc,YAAY;AAAA,EACvC;AAAA,EAEU,uBAAuB,OAAwG;AACrI,QAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACrC,aAAO;AAAA,IACX;AAEA,QAAI,EAAE,YAAY,UAAU,OAAO,MAAM,WAAW,UAAU;AAC1D,aAAO;AAAA,IACX;AAEA,QAAI,EAAE,UAAU,QAAQ;AACpB,aAAO;AAAA,IACX;AAEA,QAAI,EAAE,aAAa,UAAU,MAAM,YAAY,QAAW;AACtD,aAAO;AAAA,IACX;AAEA,QAAI,MAAM,mBAAmB,SAAS;AAClC,aAAO;AAAA,IACX;AAEA,WAAO,OAAO,MAAM,YAAY,YAAY,MAAM,YAAY,QAAQ,CAAC,MAAM,QAAQ,MAAM,OAAO;AAAA,EACtG;AAAA,EAEU,0BAA0B,OAAgB,cAAwC;AACxF,QAAI,iBAAiB,KAAK,aAAa,kBAAkB;AACrD,aAAO;AAAA,IACX;AAEA,QAAI,CAAC,KAAK,uBAAuB,KAAK,GAAG;AACrC,YAAM,IAAI,KAAK,aAAa,gBAAgB,YAAY;AAAA,IAC5D;AAEA,UAAM,oBAAoB,MAAM,mBAAmB,UAC7C,OAAO,YAAY,MAAM,QAAQ,QAAQ,CAAC,IAC1C,MAAM;AAEZ,WAAO,IAAI,KAAK,aAAa,iBAAiB,MAAM,MAAM;AAAA,MACtD,QAAQ,MAAM;AAAA,MACd,SAAS;AAAA,IACb,CAAC;AAAA,EACL;AACJ;","names":[]}
package/route.d.cts ADDED
@@ -0,0 +1,46 @@
1
+ import { p as RouteItem, j as MahameruRequest, H as HTTPMethod } from './types-CipcRmc9.cjs';
2
+ import { MahameruResponse } from './mahameru-response.cjs';
3
+ import { Container } from './container.cjs';
4
+ import { HttpServerError } from './http-server-error.cjs';
5
+ import 'node:http';
6
+ import './container-error.cjs';
7
+ import './module-error.cjs';
8
+
9
+ type RouteOptions = {
10
+ dev: boolean;
11
+ routesPath: string;
12
+ };
13
+ type RouteDependencies = {
14
+ container: Container;
15
+ HttpServerError: typeof HttpServerError;
16
+ MahameruResponse: typeof MahameruResponse;
17
+ };
18
+ declare class Route {
19
+ readonly options: RouteOptions;
20
+ protected dependencies: RouteDependencies;
21
+ constructor(dependencies: RouteDependencies);
22
+ constructor(options: Partial<RouteOptions>, dependencies: RouteDependencies);
23
+ normalizePathForMatching(path: string): string;
24
+ findMatchedRoute(matchUrl: string): {
25
+ matchedRoute: RouteItem | null;
26
+ matchResult: RegExpExecArray | null;
27
+ };
28
+ runNotFoundHandler(request: MahameruRequest, method: HTTPMethod): Promise<MahameruResponse | undefined>;
29
+ resolveRoute(request: MahameruRequest): Promise<{
30
+ matchedRoute: null;
31
+ matchResult: null;
32
+ notFoundResponse: MahameruResponse;
33
+ } | {
34
+ matchedRoute: RouteItem;
35
+ matchResult: RegExpExecArray;
36
+ notFoundResponse?: undefined;
37
+ }>;
38
+ protected isMahameruResponseLike(value: unknown): value is {
39
+ body: unknown;
40
+ status: number;
41
+ headers?: Headers | Record<string, string>;
42
+ };
43
+ protected normalizeMahameruResponse(value: unknown, errorMessage: string): MahameruResponse;
44
+ }
45
+
46
+ export { Route, type RouteDependencies, type RouteOptions };
package/route.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { p as RouteItem, j as MahameruRequest, H as HTTPMethod } from './types-BRwWYiUN.js';
2
+ import { MahameruResponse } from './mahameru-response.js';
3
+ import { Container } from './container.js';
4
+ import { HttpServerError } from './http-server-error.js';
5
+ import 'node:http';
6
+ import './container-error.js';
7
+ import './module-error.js';
8
+
9
+ type RouteOptions = {
10
+ dev: boolean;
11
+ routesPath: string;
12
+ };
13
+ type RouteDependencies = {
14
+ container: Container;
15
+ HttpServerError: typeof HttpServerError;
16
+ MahameruResponse: typeof MahameruResponse;
17
+ };
18
+ declare class Route {
19
+ readonly options: RouteOptions;
20
+ protected dependencies: RouteDependencies;
21
+ constructor(dependencies: RouteDependencies);
22
+ constructor(options: Partial<RouteOptions>, dependencies: RouteDependencies);
23
+ normalizePathForMatching(path: string): string;
24
+ findMatchedRoute(matchUrl: string): {
25
+ matchedRoute: RouteItem | null;
26
+ matchResult: RegExpExecArray | null;
27
+ };
28
+ runNotFoundHandler(request: MahameruRequest, method: HTTPMethod): Promise<MahameruResponse | undefined>;
29
+ resolveRoute(request: MahameruRequest): Promise<{
30
+ matchedRoute: null;
31
+ matchResult: null;
32
+ notFoundResponse: MahameruResponse;
33
+ } | {
34
+ matchedRoute: RouteItem;
35
+ matchResult: RegExpExecArray;
36
+ notFoundResponse?: undefined;
37
+ }>;
38
+ protected isMahameruResponseLike(value: unknown): value is {
39
+ body: unknown;
40
+ status: number;
41
+ headers?: Headers | Record<string, string>;
42
+ };
43
+ protected normalizeMahameruResponse(value: unknown, errorMessage: string): MahameruResponse;
44
+ }
45
+
46
+ export { Route, type RouteDependencies, type RouteOptions };
package/route.js ADDED
@@ -0,0 +1,105 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ import { join } from "node:path";
4
+ class Route {
5
+ static {
6
+ __name(this, "Route");
7
+ }
8
+ options = {
9
+ dev: false,
10
+ routesPath: join(process.cwd(), ".mahameru", "routes")
11
+ };
12
+ dependencies;
13
+ constructor(arg1, arg2) {
14
+ if (typeof arg2 !== "undefined")
15
+ this.options = { ...this.options, ...arg1 };
16
+ if (typeof arg2 !== "undefined") {
17
+ this.dependencies = arg2;
18
+ } else {
19
+ this.dependencies = arg1;
20
+ }
21
+ }
22
+ normalizePathForMatching(path) {
23
+ if (path.length > 1 && path.endsWith("/")) {
24
+ return path.slice(0, -1);
25
+ }
26
+ return path;
27
+ }
28
+ findMatchedRoute(matchUrl) {
29
+ let matchedRoute = null;
30
+ let matchResult = null;
31
+ for (const route of this.dependencies.container.getRouteItems()) {
32
+ const result = route.regex.exec(matchUrl);
33
+ if (result) {
34
+ matchedRoute = route;
35
+ matchResult = result;
36
+ break;
37
+ }
38
+ }
39
+ return { matchedRoute, matchResult };
40
+ }
41
+ async runNotFoundHandler(request, method) {
42
+ if (!this.dependencies.container.notFoundHandler)
43
+ return void 0;
44
+ const handler = this.dependencies.container.notFoundHandler[method];
45
+ if (typeof handler !== "function") {
46
+ return void 0;
47
+ }
48
+ const response = await handler(request, this.dependencies.container, { params: {} });
49
+ return this.normalizeMahameruResponse(
50
+ response,
51
+ `Not found handler for method '${method}' must return a MahameruResponse instance.`
52
+ );
53
+ }
54
+ async resolveRoute(request) {
55
+ const rawReqPath = request.url.split("?")[0] || "/";
56
+ const rawReqUrl = rawReqPath.replace(/\/+/g, "/");
57
+ const matchUrl = this.normalizePathForMatching(rawReqUrl);
58
+ let { matchedRoute, matchResult } = this.findMatchedRoute(matchUrl);
59
+ if (!matchedRoute || !matchResult)
60
+ return {
61
+ matchedRoute: null,
62
+ matchResult: null,
63
+ notFoundResponse: await this.runNotFoundHandler(request, request.method) || this.dependencies.MahameruResponse.json(
64
+ { error: "Not Found" },
65
+ { status: 404 }
66
+ )
67
+ };
68
+ return { matchedRoute, matchResult };
69
+ }
70
+ isMahameruResponseLike(value) {
71
+ if (!value || typeof value !== "object") {
72
+ return false;
73
+ }
74
+ if (!("status" in value) || typeof value.status !== "number") {
75
+ return false;
76
+ }
77
+ if (!("body" in value)) {
78
+ return false;
79
+ }
80
+ if (!("headers" in value) || value.headers === void 0) {
81
+ return true;
82
+ }
83
+ if (value.headers instanceof Headers) {
84
+ return true;
85
+ }
86
+ return typeof value.headers === "object" && value.headers !== null && !Array.isArray(value.headers);
87
+ }
88
+ normalizeMahameruResponse(value, errorMessage) {
89
+ if (value instanceof this.dependencies.MahameruResponse) {
90
+ return value;
91
+ }
92
+ if (!this.isMahameruResponseLike(value)) {
93
+ throw new this.dependencies.HttpServerError(errorMessage);
94
+ }
95
+ const normalizedHeaders = value.headers instanceof Headers ? Object.fromEntries(value.headers.entries()) : value.headers;
96
+ return new this.dependencies.MahameruResponse(value.body, {
97
+ status: value.status,
98
+ headers: normalizedHeaders
99
+ });
100
+ }
101
+ }
102
+ export {
103
+ Route
104
+ };
105
+ //# sourceMappingURL=route.js.map
package/route.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/route.ts"],"sourcesContent":["import { join } from 'node:path';\n\nimport type { MahameruRequest } from './mahameru-request';\nimport type { MahameruResponse } from './mahameru-response';\nimport type { Container } from './container';\nimport type { HttpServerError } from './http-server-error';\nimport type { HTTPMethod, RouteHandlerContext, RouteItem } from './types';\n\nexport type RouteOptions = {\n dev: boolean;\n routesPath: string;\n};\n\nexport type RouteDependencies = {\n container: Container;\n HttpServerError: typeof HttpServerError;\n MahameruResponse: typeof MahameruResponse;\n};\n\nexport class Route {\n public readonly options: RouteOptions = {\n dev: false,\n routesPath: join(process.cwd(), '.mahameru', 'routes')\n }\n protected dependencies: RouteDependencies;\n\n constructor(\n dependencies: RouteDependencies\n )\n constructor(\n options: Partial<RouteOptions>,\n dependencies: RouteDependencies\n )\n constructor(\n arg1: Partial<RouteOptions> | RouteDependencies,\n arg2?: RouteDependencies\n ) {\n if (typeof arg2 !== 'undefined')\n this.options = { ...this.options, ...arg1 as Partial<RouteOptions> };\n\n if (typeof arg2 !== 'undefined') {\n this.dependencies = arg2;\n } else {\n this.dependencies = arg1 as RouteDependencies;\n }\n }\n\n normalizePathForMatching(path: string): string {\n if (path.length > 1 && path.endsWith('/')) {\n return path.slice(0, -1);\n }\n\n return path;\n }\n\n findMatchedRoute(matchUrl: string) {\n let matchedRoute: RouteItem | null = null;\n let matchResult: RegExpExecArray | null = null;\n\n for (const route of this.dependencies.container.getRouteItems()) {\n const result = route.regex.exec(matchUrl);\n\n if (result) {\n matchedRoute = route;\n matchResult = result;\n\n break;\n }\n }\n\n return { matchedRoute, matchResult };\n }\n\n async runNotFoundHandler(request: MahameruRequest, method: HTTPMethod): Promise<MahameruResponse | undefined> {\n if (!this.dependencies.container.notFoundHandler)\n return undefined;\n\n const handler = this.dependencies.container.notFoundHandler[method];\n\n if (typeof handler !== 'function') {\n return undefined;\n }\n\n const response = await handler(request, this.dependencies.container, { params: {} } satisfies RouteHandlerContext);\n\n return this.normalizeMahameruResponse(\n response,\n `Not found handler for method '${method}' must return a MahameruResponse instance.`\n );\n }\n\n async resolveRoute(request: MahameruRequest) {\n const rawReqPath = request.url.split('?')[0] || '/';\n const rawReqUrl = rawReqPath.replace(/\\/+/g, '/');\n const matchUrl = this.normalizePathForMatching(rawReqUrl);\n\n let { matchedRoute, matchResult } = this.findMatchedRoute(matchUrl);\n\n if (!matchedRoute || !matchResult)\n return {\n matchedRoute: null,\n matchResult: null,\n notFoundResponse: await this.runNotFoundHandler(request, request.method) || this.dependencies.MahameruResponse.json(\n { error: 'Not Found' },\n { status: 404 }\n )\n };\n\n return { matchedRoute, matchResult };\n }\n\n protected isMahameruResponseLike(value: unknown): value is { body: unknown; status: number; headers?: Headers | Record<string, string> } {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n if (!('status' in value) || typeof value.status !== 'number') {\n return false;\n }\n\n if (!('body' in value)) {\n return false;\n }\n\n if (!('headers' in value) || value.headers === undefined) {\n return true;\n }\n\n if (value.headers instanceof Headers) {\n return true;\n }\n\n return typeof value.headers === 'object' && value.headers !== null && !Array.isArray(value.headers);\n }\n\n protected normalizeMahameruResponse(value: unknown, errorMessage: string): MahameruResponse {\n if (value instanceof this.dependencies.MahameruResponse) {\n return value;\n }\n\n if (!this.isMahameruResponseLike(value)) {\n throw new this.dependencies.HttpServerError(errorMessage);\n }\n\n const normalizedHeaders = value.headers instanceof Headers\n ? Object.fromEntries(value.headers.entries())\n : value.headers;\n\n return new this.dependencies.MahameruResponse(value.body, {\n status: value.status,\n headers: normalizedHeaders\n });\n }\n}\n"],"mappings":";;AAAA,SAAS,YAAY;AAmBd,MAAM,MAAM;AAAA,EAnBnB,OAmBmB;AAAA;AAAA;AAAA,EACC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AAA,MACd,SAAS;AAAA,IACb,CAAC;AAAA,EACL;AACJ;","names":[]}
@@ -0,0 +1,9 @@
1
+ if (process.env.npm_config_global === 'true' || process.env.npm_config_global === '1') {
2
+ console.error('\x1b[31m%s\x1b[0m', '==================================================================');
3
+ console.error('\x1b[31m%s\x1b[0m', ' Error: The "@mahameru/core" package cannot be installed globally!');
4
+ console.error('\x1b[31m%s\x1b[0m', ' Please install it locally within your project using:');
5
+ console.error('\x1b[33m%s\x1b[0m', ' npm install @mahameru/core');
6
+ console.error('\x1b[31m%s\x1b[0m', '==================================================================');
7
+
8
+ process.exit(1);
9
+ }
@@ -0,0 +1,108 @@
1
+ import { IncomingHttpHeaders, IncomingMessage } from 'node:http';
2
+ import { MahameruResponse } from './mahameru-response.js';
3
+
4
+ declare class MahameruRequest {
5
+ method: HTTPMethod;
6
+ url: string;
7
+ headers: IncomingHttpHeaders;
8
+ query: URLSearchParams;
9
+ path: string;
10
+ ipAddress?: string;
11
+ /**
12
+ * Parsed Authorization Bearer header
13
+ * @returns {string | undefined}
14
+ */
15
+ authorization?: string;
16
+ protected rawRequest: IncomingMessage;
17
+ constructor(request: IncomingMessage);
18
+ json(): Promise<any>;
19
+ }
20
+
21
+ declare enum HTTPMethodEnum {
22
+ GET = "GET",
23
+ HEAD = "HEAD",
24
+ POST = "POST",
25
+ PUT = "PUT",
26
+ DELETE = "DELETE",
27
+ CONNECT = "CONNECT",
28
+ OPTIONS = "OPTIONS",
29
+ TRACE = "TRACE",
30
+ PATCH = "PATCH"
31
+ }
32
+ type HTTPMethod = `${HTTPMethodEnum}`;
33
+ type RouteObject<T extends string = string> = {
34
+ path: T;
35
+ methods: HTTPMethod[];
36
+ };
37
+ interface RegisterRoutes {
38
+ }
39
+ type ProtectedRoute = RegisterRoutes extends {
40
+ routes: infer R;
41
+ } ? R[] : (string | RouteObject<string>)[];
42
+ type RequestParams = {
43
+ [key: string]: string;
44
+ };
45
+ type RouteHandlerContext = {
46
+ params: RequestParams;
47
+ };
48
+ type RouteHandler = (request: MahameruRequest, container: MahameruContainer, context: RouteHandlerContext) => Promise<MahameruResponse> | MahameruResponse;
49
+ interface RouteItem {
50
+ path: string;
51
+ regex: RegExp;
52
+ paramNames: (keyof RequestParams)[];
53
+ routeHandlers: RouteHandlers;
54
+ pathFS: string;
55
+ }
56
+ type RouteHandlers = Record<HTTPMethod, RouteHandler>;
57
+ type MahameruNext = () => Promise<MahameruResponse>;
58
+ interface MahameruMiddlewareContext {
59
+ request: MahameruRequest;
60
+ container: MahameruContainer;
61
+ params: Record<string, string>;
62
+ path: string;
63
+ method: HTTPMethod;
64
+ status: number;
65
+ }
66
+ type MahameruMiddleware = (context: MahameruMiddlewareContext, isProtectedRoute: boolean, next: MahameruNext) => Promise<MahameruResponse> | MahameruResponse;
67
+ type ErrorHandlerContext = MahameruMiddlewareContext & {
68
+ error: unknown;
69
+ };
70
+ type ErrorHandler = (context: ErrorHandlerContext, next: MahameruNext) => Promise<MahameruResponse> | MahameruResponse;
71
+ interface Modules {
72
+ }
73
+ interface Instances {
74
+ }
75
+ interface MahameruContainer extends Modules, Instances {
76
+ }
77
+ type ClassConstructor<T = unknown> = new (mahameruContainer: MahameruContainer) => T;
78
+ type ContainerItemID = string;
79
+ type ContainerItem = {
80
+ name: string;
81
+ path: string;
82
+ type: 'module-service';
83
+ item: unknown;
84
+ } | {
85
+ name: string;
86
+ path: string;
87
+ type: 'module-controller';
88
+ item: unknown;
89
+ } | {
90
+ name: string;
91
+ path: string;
92
+ type: 'route';
93
+ item: RouteItem;
94
+ } | {
95
+ name: string;
96
+ path: string;
97
+ type: 'instance';
98
+ item: Instances;
99
+ } | {
100
+ name: string;
101
+ path: string;
102
+ type: 'middleware';
103
+ item: MahameruMiddleware;
104
+ };
105
+ type ContainerRegistry = Map<ContainerItemID, ContainerItem>;
106
+ type InitiatorHandler = () => Promise<Instances>;
107
+
108
+ export { type ClassConstructor as C, type ErrorHandler as E, type HTTPMethod as H, type InitiatorHandler as I, type MahameruContainer as M, type ProtectedRoute as P, type RegisterRoutes as R, type ContainerItem as a, type ContainerItemID as b, type ContainerRegistry as c, type ErrorHandlerContext as d, HTTPMethodEnum as e, type Instances as f, type MahameruMiddleware as g, type MahameruMiddlewareContext as h, type MahameruNext as i, MahameruRequest as j, type Modules as k, type RequestParams as l, type RouteHandler as m, type RouteHandlerContext as n, type RouteHandlers as o, type RouteItem as p, type RouteObject as q };