@e22m4u/js-http-static-router 0.0.7

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.
package/.c8rc ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "all": true,
3
+ "include": [
4
+ "src/**/*.ts"
5
+ ],
6
+ "exclude": [
7
+ "src/**/*.spec.ts"
8
+ ]
9
+ }
package/.commitlintrc ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": [
3
+ "@commitlint/config-conventional"
4
+ ]
5
+ }
package/.editorconfig ADDED
@@ -0,0 +1,13 @@
1
+ # EditorConfig is awesome: https://EditorConfig.org
2
+
3
+ # top-most EditorConfig file
4
+ root = true
5
+
6
+ # Unix-style newlines with a newline ending every file
7
+ [*]
8
+ end_of_line = lf
9
+ insert_final_newline = true
10
+ charset = utf-8
11
+ indent_style = space
12
+ indent_size = 2
13
+ max_line_length = 80
@@ -0,0 +1 @@
1
+ npx --no -- commitlint --edit $1
@@ -0,0 +1,6 @@
1
+ npm run lint:fix
2
+ npm run format
3
+ npm run test
4
+ npm run build
5
+
6
+ git add -A
package/.mocharc.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extension": ["ts"],
3
+ "spec": "src/**/*.spec.ts",
4
+ "require": ["tsx"]
5
+ }
package/.prettierrc ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "bracketSpacing": false,
3
+ "singleQuote": true,
4
+ "printWidth": 80,
5
+ "trailingComma": "all",
6
+ "arrowParens": "avoid"
7
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2025 Mikhail Evstropov <e22m4u@yandex.ru>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ ## @e22m4u/js-http-static-router
2
+
3
+ HTTP-маршрутизатор статичных ресурсов.
4
+
5
+ ## Установка
6
+
7
+ ```bash
8
+ npm install @e22m4u/js-http-static-router
9
+ ```
10
+
11
+ ## Использование
12
+
13
+ ```ts
14
+ import http from 'http';
15
+ import {HttpStaticRouter} from '@e22m4u/js-http-static-router';
16
+
17
+ // обертка инициализации в асинхронную функцию
18
+ async function main() {
19
+ // создание экземпляра маршрутизатора
20
+ const staticRouter = new HttpStaticRouter();
21
+
22
+ // добавление маршрутов:
23
+ // (Promise.all для параллельной и быстрой инициализации)
24
+ await Promise.all([
25
+ // объявление содержимого папки "../static"
26
+ // доступным по URL "/static"
27
+ staticRouter.addRoute(
28
+ '/static', // путь маршрута
29
+ `${import.meta.dirname}/../static`, // файловый путь
30
+ ),
31
+ // объявление отдельного файла
32
+ staticRouter.addRoute(
33
+ '/favicon.ico',
34
+ `${import.meta.dirname}/../static/favicon.ico`,
35
+ ),
36
+ ]);
37
+
38
+ // создание HTTP сервера и подключение обработчика
39
+ const server = new http.Server();
40
+ server.on('request', (req, res) => {
41
+ // если статический маршрут найден,
42
+ // выполняется поиск и отдача файла
43
+ const staticRoute = staticRouter.matchRoute(req);
44
+ if (staticRoute) staticRouter.sendFileByRoute(staticRoute, req, res);
45
+ // в противном случае запрос обрабатывается
46
+ // основной логикой приложения
47
+ res.writeHead(200, {'Content-Type': 'text/plain'});
48
+ res.end('Hello from App!');
49
+ });
50
+
51
+ server.listen(3000, () => {
52
+ console.log('Server is running on http://localhost:3000');
53
+ console.log('Try to open:');
54
+ console.log('http://localhost:3000/static/');
55
+ console.log('http://localhost:3000/favicon.ico');
56
+ });
57
+ }
58
+
59
+ // запуск
60
+ main().catch(error => {
61
+ console.error('Failed to start the server:', error);
62
+ process.exit(1);
63
+ });
64
+ ```
65
+
66
+ ## Тесты
67
+
68
+ ```bash
69
+ npm run test
70
+ ```
71
+
72
+ ## Лицензия
73
+
74
+ MIT
package/build-cjs.js ADDED
@@ -0,0 +1,16 @@
1
+ import * as esbuild from 'esbuild';
2
+ import packageJson from './package.json' with {type: 'json'};
3
+
4
+ await esbuild.build({
5
+ entryPoints: ['dist/esm/index.js'],
6
+ outfile: 'dist/cjs/index.cjs',
7
+ format: 'cjs',
8
+ platform: 'node',
9
+ target: ['node12'],
10
+ bundle: true,
11
+ keepNames: true,
12
+ external: [
13
+ ...Object.keys(packageJson.peerDependencies || {}),
14
+ ...Object.keys(packageJson.dependencies || {}),
15
+ ],
16
+ });
@@ -0,0 +1,196 @@
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
+
31
+ // dist/esm/index.js
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ HttpStaticRouter: () => HttpStaticRouter
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // dist/esm/http-static-router.js
39
+ var import_path = __toESM(require("path"), 1);
40
+ var fs = __toESM(require("fs/promises"), 1);
41
+ var import_mime_types = __toESM(require("mime-types"), 1);
42
+ var import_fs = require("fs");
43
+ var import_js_format = require("@e22m4u/js-format");
44
+
45
+ // dist/esm/services/debuggable-service.js
46
+ var import_js_service = require("@e22m4u/js-service");
47
+
48
+ // dist/esm/utils/to-camel-case.js
49
+ function toCamelCase(input) {
50
+ return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
51
+ }
52
+ __name(toCamelCase, "toCamelCase");
53
+
54
+ // dist/esm/services/debuggable-service.js
55
+ var import_js_debug = require("@e22m4u/js-debug");
56
+ var _DebuggableService = class _DebuggableService extends import_js_service.Service {
57
+ /**
58
+ * Debug.
59
+ */
60
+ debug;
61
+ /**
62
+ * Возвращает функцию-отладчик с сегментом пространства имен
63
+ * указанного в параметре метода.
64
+ *
65
+ * @param method
66
+ * @protected
67
+ */
68
+ getDebuggerFor(method) {
69
+ return this.debug.withHash().withNs(method.name);
70
+ }
71
+ /**
72
+ * Constructor.
73
+ *
74
+ * @param container
75
+ */
76
+ constructor(container) {
77
+ super(container);
78
+ const serviceName = toCamelCase(this.constructor.name);
79
+ this.debug = (0, import_js_debug.createDebugger)(serviceName).withoutEnvNs();
80
+ const debug = this.debug.withNs("constructor").withHash();
81
+ debug("Service created.");
82
+ }
83
+ };
84
+ __name(_DebuggableService, "DebuggableService");
85
+ var DebuggableService = _DebuggableService;
86
+
87
+ // dist/esm/http-static-router.js
88
+ var _HttpStaticRouter = class _HttpStaticRouter extends DebuggableService {
89
+ /**
90
+ * Routes.
91
+ *
92
+ * @protected
93
+ */
94
+ routes = [];
95
+ /**
96
+ * Add route.
97
+ *
98
+ * @param remotePath
99
+ * @param resourcePath
100
+ */
101
+ async addRoute(remotePath, resourcePath) {
102
+ const debug = this.getDebuggerFor(this.addRoute);
103
+ resourcePath = import_path.default.resolve(resourcePath);
104
+ debug("Adding a new route.");
105
+ debug("Resource path is %v.", resourcePath);
106
+ debug("Remote path is %v.", remotePath);
107
+ let stats;
108
+ try {
109
+ stats = await fs.stat(resourcePath);
110
+ } catch (error) {
111
+ console.error(error);
112
+ throw new import_js_format.Errorf("Static resource path does not exist %v.", resourcePath);
113
+ }
114
+ const isFile = stats.isFile();
115
+ debug("Resource type is %s.", isFile ? "File" : "Folder");
116
+ const regexp = new RegExp(`^${remotePath}`, "i");
117
+ const route = { remotePath, resourcePath, regexp, isFile };
118
+ this.routes.push(route);
119
+ return this;
120
+ }
121
+ /**
122
+ * Match route.
123
+ *
124
+ * @param req
125
+ */
126
+ matchRoute(req) {
127
+ const debug = this.getDebuggerFor(this.matchRoute);
128
+ debug("Matching route by incoming request.");
129
+ const url = req.url || "/";
130
+ debug("Incoming request is %s %v.", req.method, url);
131
+ debug("Walking through %v routes.", this.routes.length);
132
+ const route = this.routes.find((route2) => {
133
+ const res = route2.regexp.test(url);
134
+ const phrase = res ? "matched" : "not matched";
135
+ debug("Resource %v %s.", route2.resourcePath, phrase);
136
+ return res;
137
+ });
138
+ route ? debug("Resource %v matched.", route.resourcePath) : debug("No route matched.");
139
+ return route;
140
+ }
141
+ /**
142
+ * Send file by route.
143
+ *
144
+ * @param route
145
+ * @param req
146
+ * @param res
147
+ */
148
+ sendFileByRoute(route, req, res) {
149
+ const reqUrl = (req.url || "/").replace(/\?.*$/, "");
150
+ if (/[^/]$/.test(route.remotePath) && reqUrl === route.remotePath) {
151
+ res.writeHead(302, { location: `${reqUrl}/` });
152
+ res.end();
153
+ return;
154
+ }
155
+ let filePath = route.resourcePath;
156
+ if (!route.isFile) {
157
+ let relativePath = reqUrl.replace(new RegExp(`^${route.remotePath}`), "");
158
+ if (!relativePath || relativePath === "/")
159
+ relativePath = "/index.html";
160
+ filePath = import_path.default.join(route.resourcePath, relativePath);
161
+ }
162
+ const resolvedPath = import_path.default.resolve(filePath);
163
+ const resourceRoot = import_path.default.resolve(route.resourcePath);
164
+ if (!resolvedPath.startsWith(resourceRoot)) {
165
+ res.writeHead(403, { "content-type": "text/plain" });
166
+ res.end("403 Forbidden");
167
+ return;
168
+ }
169
+ const extname = import_path.default.extname(resolvedPath);
170
+ const contentType = import_mime_types.default.contentType(extname) || "application/octet-stream";
171
+ const fileStream = (0, import_fs.createReadStream)(resolvedPath);
172
+ fileStream.on("error", (error) => {
173
+ if (res.headersSent)
174
+ return;
175
+ if ("code" in error && error.code === "ENOENT") {
176
+ res.writeHead(404, { "content-type": "text/plain" });
177
+ res.write("404 Not Found");
178
+ res.end();
179
+ } else {
180
+ res.writeHead(500, { "content-type": "text/plain" });
181
+ res.write("500 Internal Server Error");
182
+ res.end();
183
+ }
184
+ });
185
+ fileStream.on("open", () => {
186
+ res.writeHead(200, { "content-type": contentType });
187
+ fileStream.pipe(res);
188
+ });
189
+ }
190
+ };
191
+ __name(_HttpStaticRouter, "HttpStaticRouter");
192
+ var HttpStaticRouter = _HttpStaticRouter;
193
+ // Annotate the CommonJS export names for ESM import in node:
194
+ 0 && (module.exports = {
195
+ HttpStaticRouter
196
+ });
@@ -0,0 +1,45 @@
1
+ import { ServerResponse } from 'node:http';
2
+ import { IncomingMessage } from 'node:http';
3
+ import { DebuggableService } from './services/index.js';
4
+ /**
5
+ * Static file route.
6
+ */
7
+ type HttpStaticRoute = {
8
+ remotePath: string;
9
+ resourcePath: string;
10
+ regexp: RegExp;
11
+ isFile: boolean;
12
+ };
13
+ /**
14
+ * Http static router.
15
+ */
16
+ export declare class HttpStaticRouter extends DebuggableService {
17
+ /**
18
+ * Routes.
19
+ *
20
+ * @protected
21
+ */
22
+ protected routes: HttpStaticRoute[];
23
+ /**
24
+ * Add route.
25
+ *
26
+ * @param remotePath
27
+ * @param resourcePath
28
+ */
29
+ addRoute(remotePath: string, resourcePath: string): Promise<this>;
30
+ /**
31
+ * Match route.
32
+ *
33
+ * @param req
34
+ */
35
+ matchRoute(req: IncomingMessage): HttpStaticRoute | undefined;
36
+ /**
37
+ * Send file by route.
38
+ *
39
+ * @param route
40
+ * @param req
41
+ * @param res
42
+ */
43
+ sendFileByRoute(route: HttpStaticRoute, req: IncomingMessage, res: ServerResponse): void;
44
+ }
45
+ export {};
@@ -0,0 +1,141 @@
1
+ import path from 'path';
2
+ import * as fs from 'fs/promises';
3
+ import mimeTypes from 'mime-types';
4
+ import { createReadStream } from 'fs';
5
+ import { Errorf } from '@e22m4u/js-format';
6
+ import { DebuggableService } from './services/index.js';
7
+ /**
8
+ * Http static router.
9
+ */
10
+ export class HttpStaticRouter extends DebuggableService {
11
+ /**
12
+ * Routes.
13
+ *
14
+ * @protected
15
+ */
16
+ routes = [];
17
+ /**
18
+ * Add route.
19
+ *
20
+ * @param remotePath
21
+ * @param resourcePath
22
+ */
23
+ async addRoute(remotePath, resourcePath) {
24
+ const debug = this.getDebuggerFor(this.addRoute);
25
+ resourcePath = path.resolve(resourcePath);
26
+ debug('Adding a new route.');
27
+ debug('Resource path is %v.', resourcePath);
28
+ debug('Remote path is %v.', remotePath);
29
+ let stats;
30
+ try {
31
+ stats = await fs.stat(resourcePath);
32
+ }
33
+ catch (error) {
34
+ // если ресурс не существует в момент старта,
35
+ // это может быть ошибкой конфигурации
36
+ console.error(error);
37
+ throw new Errorf('Static resource path does not exist %v.', resourcePath);
38
+ }
39
+ const isFile = stats.isFile();
40
+ debug('Resource type is %s.', isFile ? 'File' : 'Folder');
41
+ const regexp = new RegExp(`^${remotePath}`, 'i');
42
+ const route = { remotePath, resourcePath, regexp, isFile };
43
+ this.routes.push(route);
44
+ return this;
45
+ }
46
+ /**
47
+ * Match route.
48
+ *
49
+ * @param req
50
+ */
51
+ matchRoute(req) {
52
+ const debug = this.getDebuggerFor(this.matchRoute);
53
+ debug('Matching route by incoming request.');
54
+ const url = req.url || '/';
55
+ debug('Incoming request is %s %v.', req.method, url);
56
+ debug('Walking through %v routes.', this.routes.length);
57
+ const route = this.routes.find(route => {
58
+ const res = route.regexp.test(url);
59
+ const phrase = res ? 'matched' : 'not matched';
60
+ debug('Resource %v %s.', route.resourcePath, phrase);
61
+ return res;
62
+ });
63
+ route
64
+ ? debug('Resource %v matched.', route.resourcePath)
65
+ : debug('No route matched.');
66
+ return route;
67
+ }
68
+ /**
69
+ * Send file by route.
70
+ *
71
+ * @param route
72
+ * @param req
73
+ * @param res
74
+ */
75
+ sendFileByRoute(route, req, res) {
76
+ const reqUrl = (req.url || '/').replace(/\?.*$/, '');
77
+ // так как в html обычно используются относительные
78
+ // пути, то адрес папки статических ресурсов должен
79
+ // завершаться косой чертой, что бы файлы стилей и
80
+ // изображений загружались именно из нее,
81
+ // а не обращались на уровень выше
82
+ if (/[^/]$/.test(route.remotePath) && reqUrl === route.remotePath) {
83
+ res.writeHead(302, { location: `${reqUrl}/` });
84
+ res.end();
85
+ return;
86
+ }
87
+ // если ресурс ссылается на папку, то из адреса
88
+ // запроса извлекается относительный путь до файла,
89
+ // и объединяется с адресом ресурса
90
+ let filePath = route.resourcePath;
91
+ if (!route.isFile) {
92
+ // формирование относительного пути до файла
93
+ // путем удаления из пути запроса той части,
94
+ // которая была указана при объявлении маршрута
95
+ let relativePath = reqUrl.replace(new RegExp(`^${route.remotePath}`), '');
96
+ // если относительный путь указывает
97
+ // на корень, то подставляется index.html
98
+ if (!relativePath || relativePath === '/')
99
+ relativePath = '/index.html';
100
+ // объединение адреса ресурса
101
+ // с относительным путем до файла
102
+ filePath = path.join(route.resourcePath, relativePath);
103
+ }
104
+ // если обнаружена попытка выхода за пределы
105
+ // корневой директории, то выбрасывается ошибка
106
+ const resolvedPath = path.resolve(filePath);
107
+ const resourceRoot = path.resolve(route.resourcePath);
108
+ if (!resolvedPath.startsWith(resourceRoot)) {
109
+ res.writeHead(403, { 'content-type': 'text/plain' });
110
+ res.end('403 Forbidden');
111
+ return;
112
+ }
113
+ // формирование заголовка "content-type"
114
+ // в зависимости от расширения файла
115
+ const extname = path.extname(resolvedPath);
116
+ const contentType = mimeTypes.contentType(extname) || 'application/octet-stream';
117
+ // файл читается и отправляется частями,
118
+ // что значительно снижает использование памяти
119
+ const fileStream = createReadStream(resolvedPath);
120
+ fileStream.on('error', error => {
121
+ if (res.headersSent)
122
+ return;
123
+ if ('code' in error && error.code === 'ENOENT') {
124
+ res.writeHead(404, { 'content-type': 'text/plain' });
125
+ res.write('404 Not Found');
126
+ res.end();
127
+ }
128
+ else {
129
+ res.writeHead(500, { 'content-type': 'text/plain' });
130
+ res.write('500 Internal Server Error');
131
+ res.end();
132
+ }
133
+ });
134
+ // отправка заголовка 200, только после
135
+ // этого начинается отдача файла
136
+ fileStream.on('open', () => {
137
+ res.writeHead(200, { 'content-type': contentType });
138
+ fileStream.pipe(res);
139
+ });
140
+ }
141
+ }
@@ -0,0 +1 @@
1
+ export * from './http-static-router.js';
@@ -0,0 +1 @@
1
+ export * from './http-static-router.js';
@@ -0,0 +1,27 @@
1
+ import { Callable } from '../types.js';
2
+ import { Debugger } from '@e22m4u/js-debug';
3
+ import { Service } from '@e22m4u/js-service';
4
+ import { ServiceContainer } from '@e22m4u/js-service';
5
+ /**
6
+ * Service.
7
+ */
8
+ export declare class DebuggableService extends Service {
9
+ /**
10
+ * Debug.
11
+ */
12
+ debug: Debugger;
13
+ /**
14
+ * Возвращает функцию-отладчик с сегментом пространства имен
15
+ * указанного в параметре метода.
16
+ *
17
+ * @param method
18
+ * @protected
19
+ */
20
+ protected getDebuggerFor(method: Callable): Debugger;
21
+ /**
22
+ * Constructor.
23
+ *
24
+ * @param container
25
+ */
26
+ constructor(container?: ServiceContainer);
27
+ }
@@ -0,0 +1,34 @@
1
+ import { Service } from '@e22m4u/js-service';
2
+ import { toCamelCase } from '../utils/index.js';
3
+ import { createDebugger } from '@e22m4u/js-debug';
4
+ /**
5
+ * Service.
6
+ */
7
+ export class DebuggableService extends Service {
8
+ /**
9
+ * Debug.
10
+ */
11
+ debug;
12
+ /**
13
+ * Возвращает функцию-отладчик с сегментом пространства имен
14
+ * указанного в параметре метода.
15
+ *
16
+ * @param method
17
+ * @protected
18
+ */
19
+ getDebuggerFor(method) {
20
+ return this.debug.withHash().withNs(method.name);
21
+ }
22
+ /**
23
+ * Constructor.
24
+ *
25
+ * @param container
26
+ */
27
+ constructor(container) {
28
+ super(container);
29
+ const serviceName = toCamelCase(this.constructor.name);
30
+ this.debug = createDebugger(serviceName).withoutEnvNs();
31
+ const debug = this.debug.withNs('constructor').withHash();
32
+ debug('Service created.');
33
+ }
34
+ }
@@ -0,0 +1 @@
1
+ export * from './debuggable-service.js';
@@ -0,0 +1 @@
1
+ export * from './debuggable-service.js';
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A callable type with the "new" operator
3
+ * that allows class and constructor types.
4
+ */
5
+ export interface Constructor<T = object> {
6
+ new (...args: any[]): T;
7
+ }
8
+ /**
9
+ * An object prototype that excludes
10
+ * function and scalar values.
11
+ */
12
+ export type Prototype<T = object> = T & object & {
13
+ bind?: never;
14
+ } & {
15
+ call?: never;
16
+ } & {
17
+ prototype?: object;
18
+ };
19
+ /**
20
+ * A function type without class and constructor.
21
+ */
22
+ export type Callable<T = unknown> = (...args: any[]) => T;
23
+ /**
24
+ * Makes a specific property of T as optional.
25
+ */
26
+ export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
27
+ /**
28
+ * A part of the Flatten type.
29
+ */
30
+ export type Identity<T> = T;
31
+ /**
32
+ * Makes T more human-readable.
33
+ */
34
+ export type Flatten<T> = Identity<{
35
+ [k in keyof T]: T[k];
36
+ }>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export * from './to-camel-case.js';
@@ -0,0 +1 @@
1
+ export * from './to-camel-case.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * To camel case.
3
+ *
4
+ * @param input
5
+ */
6
+ export declare function toCamelCase(input: string): string;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * To camel case.
3
+ *
4
+ * @param input
5
+ */
6
+ export function toCamelCase(input) {
7
+ return input
8
+ .replace(/(^\w|[A-Z]|\b\w)/g, c => c.toUpperCase())
9
+ .replace(/\W+/g, '')
10
+ .replace(/(^\w)/g, c => c.toLowerCase());
11
+ }
@@ -0,0 +1,42 @@
1
+ import globals from 'globals';
2
+ import eslintJs from '@eslint/js';
3
+ import eslintTypescript from 'typescript-eslint';
4
+ import eslintMochaPlugin from 'eslint-plugin-mocha';
5
+ import eslintPrettierConfig from 'eslint-config-prettier';
6
+ import eslintChaiExpectPlugin from 'eslint-plugin-chai-expect';
7
+
8
+ export default [
9
+ {
10
+ ignores: ['**/*.js'],
11
+ },
12
+ {
13
+ files: ['src/**/*.ts'],
14
+ languageOptions: {
15
+ globals: {
16
+ ...globals.node,
17
+ ...globals.es2021,
18
+ ...globals.mocha,
19
+ },
20
+ parser: eslintTypescript.parser,
21
+ parserOptions: {
22
+ projectService: true,
23
+ tsconfigRootDir: import.meta.dirname,
24
+ },
25
+ },
26
+ plugins: {
27
+ '@typescript-eslint': eslintTypescript.plugin,
28
+ 'mocha': eslintMochaPlugin,
29
+ 'chai-expect': eslintChaiExpectPlugin,
30
+ },
31
+ rules: {
32
+ ...eslintJs.configs.recommended.rules,
33
+ ...eslintPrettierConfig.rules,
34
+ ...eslintMochaPlugin.configs.recommended.rules,
35
+ ...eslintTypescript.configs.recommended.reduce(
36
+ (rules, config) => ({...rules, ...config.rules}),
37
+ {},
38
+ ),
39
+ '@typescript-eslint/no-unused-expressions': 0,
40
+ },
41
+ },
42
+ ];
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@e22m4u/js-http-static-router",
3
+ "version": "0.0.7",
4
+ "description": "HTTP-маршрутизатор статичных ресурсов",
5
+ "author": "Mikhail Evstropov <e22m4u@yandex.ru>",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "static",
9
+ "router",
10
+ "http"
11
+ ],
12
+ "homepage": "https://github.com/e22m4u/js-http-static-router",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/e22m4u/js-http-static-router.git"
16
+ },
17
+ "type": "module",
18
+ "types": "./dist/esm/index.d.ts",
19
+ "module": "./dist/esm/index.js",
20
+ "main": "./dist/cjs/index.cjs",
21
+ "exports": {
22
+ "types": "./dist/esm/index.d.ts",
23
+ "import": "./dist/esm/index.js",
24
+ "require": "./dist/cjs/index.cjs"
25
+ },
26
+ "engines": {
27
+ "node": ">=12"
28
+ },
29
+ "scripts": {
30
+ "build:esm": "tsc --build",
31
+ "build:cjs": "rimraf ./dist/cjs && node --no-warnings=ExperimentalWarning build-cjs.js",
32
+ "build": "rimraf dist && npm run build:esm && npm run build:cjs",
33
+ "postbuild": "rimraf ./dist/**/*.spec.* --glob ./dist/tsconfig.tsbuildinfo",
34
+ "lint": "eslint ./src",
35
+ "lint:fix": "eslint ./src --fix",
36
+ "format": "prettier --write \"./src/**/*.ts\"",
37
+ "test": "npm run lint && c8 --reporter=text-summary mocha --bail",
38
+ "test:coverage": "npm run lint && c8 --reporter=text mocha --bail",
39
+ "prepare": "husky"
40
+ },
41
+ "dependencies": {
42
+ "@e22m4u/js-debug": "~0.3.1",
43
+ "@e22m4u/js-format": "~0.2.0",
44
+ "@e22m4u/js-service": "~0.4.2",
45
+ "mime-types": "~3.0.1"
46
+ },
47
+ "devDependencies": {
48
+ "@commitlint/cli": "~20.1.0",
49
+ "@commitlint/config-conventional": "~20.0.0",
50
+ "@eslint/js": "~9.37.0",
51
+ "@types/chai": "~5.2.2",
52
+ "@types/mime-types": "^3.0.1",
53
+ "@types/mocha": "~10.0.10",
54
+ "@types/node": "~24.7.0",
55
+ "c8": "~10.1.3",
56
+ "chai": "~6.2.0",
57
+ "esbuild": "~0.25.10",
58
+ "eslint": "~9.37.0",
59
+ "eslint-config-prettier": "~10.1.8",
60
+ "eslint-plugin-chai-expect": "~3.1.0",
61
+ "eslint-plugin-mocha": "~11.2.0",
62
+ "globals": "~16.4.0",
63
+ "husky": "~9.1.7",
64
+ "mocha": "~11.7.4",
65
+ "prettier": "~3.6.2",
66
+ "rimraf": "~6.0.1",
67
+ "tsx": "~4.20.6",
68
+ "typescript": "~5.9.3",
69
+ "typescript-eslint": "~8.46.0"
70
+ }
71
+ }
@@ -0,0 +1,158 @@
1
+ import path from 'path';
2
+ import * as fs from 'fs/promises';
3
+ import mimeTypes from 'mime-types';
4
+ import {createReadStream} from 'fs';
5
+ import {ServerResponse} from 'node:http';
6
+ import {Errorf} from '@e22m4u/js-format';
7
+ import {IncomingMessage} from 'node:http';
8
+ import {DebuggableService} from './services/index.js';
9
+
10
+ /**
11
+ * Static file route.
12
+ */
13
+ type HttpStaticRoute = {
14
+ remotePath: string;
15
+ resourcePath: string;
16
+ regexp: RegExp;
17
+ isFile: boolean;
18
+ };
19
+
20
+ /**
21
+ * Http static router.
22
+ */
23
+ export class HttpStaticRouter extends DebuggableService {
24
+ /**
25
+ * Routes.
26
+ *
27
+ * @protected
28
+ */
29
+ protected routes: HttpStaticRoute[] = [];
30
+
31
+ /**
32
+ * Add route.
33
+ *
34
+ * @param remotePath
35
+ * @param resourcePath
36
+ */
37
+ async addRoute(remotePath: string, resourcePath: string): Promise<this> {
38
+ const debug = this.getDebuggerFor(this.addRoute);
39
+ resourcePath = path.resolve(resourcePath);
40
+ debug('Adding a new route.');
41
+ debug('Resource path is %v.', resourcePath);
42
+ debug('Remote path is %v.', remotePath);
43
+ let stats;
44
+ try {
45
+ stats = await fs.stat(resourcePath);
46
+ } catch (error) {
47
+ // если ресурс не существует в момент старта,
48
+ // это может быть ошибкой конфигурации
49
+ console.error(error);
50
+ throw new Errorf('Static resource path does not exist %v.', resourcePath);
51
+ }
52
+ const isFile = stats.isFile();
53
+ debug('Resource type is %s.', isFile ? 'File' : 'Folder');
54
+ const regexp = new RegExp(`^${remotePath}`, 'i');
55
+ const route = {remotePath, resourcePath, regexp, isFile};
56
+ this.routes.push(route);
57
+ return this;
58
+ }
59
+
60
+ /**
61
+ * Match route.
62
+ *
63
+ * @param req
64
+ */
65
+ matchRoute(req: IncomingMessage) {
66
+ const debug = this.getDebuggerFor(this.matchRoute);
67
+ debug('Matching route by incoming request.');
68
+ const url = req.url || '/';
69
+ debug('Incoming request is %s %v.', req.method, url);
70
+ debug('Walking through %v routes.', this.routes.length);
71
+ const route = this.routes.find(route => {
72
+ const res = route.regexp.test(url);
73
+ const phrase = res ? 'matched' : 'not matched';
74
+ debug('Resource %v %s.', route.resourcePath, phrase);
75
+ return res;
76
+ });
77
+ route
78
+ ? debug('Resource %v matched.', route.resourcePath)
79
+ : debug('No route matched.');
80
+ return route;
81
+ }
82
+
83
+ /**
84
+ * Send file by route.
85
+ *
86
+ * @param route
87
+ * @param req
88
+ * @param res
89
+ */
90
+ sendFileByRoute(
91
+ route: HttpStaticRoute,
92
+ req: IncomingMessage,
93
+ res: ServerResponse,
94
+ ) {
95
+ const reqUrl = (req.url || '/').replace(/\?.*$/, '');
96
+ // так как в html обычно используются относительные
97
+ // пути, то адрес папки статических ресурсов должен
98
+ // завершаться косой чертой, что бы файлы стилей и
99
+ // изображений загружались именно из нее,
100
+ // а не обращались на уровень выше
101
+ if (/[^/]$/.test(route.remotePath) && reqUrl === route.remotePath) {
102
+ res.writeHead(302, {location: `${reqUrl}/`});
103
+ res.end();
104
+ return;
105
+ }
106
+ // если ресурс ссылается на папку, то из адреса
107
+ // запроса извлекается относительный путь до файла,
108
+ // и объединяется с адресом ресурса
109
+ let filePath = route.resourcePath;
110
+ if (!route.isFile) {
111
+ // формирование относительного пути до файла
112
+ // путем удаления из пути запроса той части,
113
+ // которая была указана при объявлении маршрута
114
+ let relativePath = reqUrl.replace(new RegExp(`^${route.remotePath}`), '');
115
+ // если относительный путь указывает
116
+ // на корень, то подставляется index.html
117
+ if (!relativePath || relativePath === '/') relativePath = '/index.html';
118
+ // объединение адреса ресурса
119
+ // с относительным путем до файла
120
+ filePath = path.join(route.resourcePath, relativePath);
121
+ }
122
+ // если обнаружена попытка выхода за пределы
123
+ // корневой директории, то выбрасывается ошибка
124
+ const resolvedPath = path.resolve(filePath);
125
+ const resourceRoot = path.resolve(route.resourcePath);
126
+ if (!resolvedPath.startsWith(resourceRoot)) {
127
+ res.writeHead(403, {'content-type': 'text/plain'});
128
+ res.end('403 Forbidden');
129
+ return;
130
+ }
131
+ // формирование заголовка "content-type"
132
+ // в зависимости от расширения файла
133
+ const extname = path.extname(resolvedPath);
134
+ const contentType =
135
+ mimeTypes.contentType(extname) || 'application/octet-stream';
136
+ // файл читается и отправляется частями,
137
+ // что значительно снижает использование памяти
138
+ const fileStream = createReadStream(resolvedPath);
139
+ fileStream.on('error', error => {
140
+ if (res.headersSent) return;
141
+ if ('code' in error && error.code === 'ENOENT') {
142
+ res.writeHead(404, {'content-type': 'text/plain'});
143
+ res.write('404 Not Found');
144
+ res.end();
145
+ } else {
146
+ res.writeHead(500, {'content-type': 'text/plain'});
147
+ res.write('500 Internal Server Error');
148
+ res.end();
149
+ }
150
+ });
151
+ // отправка заголовка 200, только после
152
+ // этого начинается отдача файла
153
+ fileStream.on('open', () => {
154
+ res.writeHead(200, {'content-type': contentType});
155
+ fileStream.pipe(res);
156
+ });
157
+ }
158
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './http-static-router.js';
@@ -0,0 +1,17 @@
1
+ import {expect} from 'chai';
2
+ import {Service} from '@e22m4u/js-service';
3
+ import {DebuggableService} from './debuggable-service.js';
4
+
5
+ describe('DebuggableService', function () {
6
+ it('has the debug method', function () {
7
+ const res = new DebuggableService();
8
+ expect(typeof res.debug).to.be.eq('function');
9
+ });
10
+
11
+ describe('constructor', function () {
12
+ it('extends the Service class', function () {
13
+ const res = new DebuggableService();
14
+ expect(res).to.be.instanceof(Service);
15
+ });
16
+ });
17
+ });
@@ -0,0 +1,40 @@
1
+ import {Callable} from '../types.js';
2
+ import {Debugger} from '@e22m4u/js-debug';
3
+ import {Service} from '@e22m4u/js-service';
4
+ import {toCamelCase} from '../utils/index.js';
5
+ import {createDebugger} from '@e22m4u/js-debug';
6
+ import {ServiceContainer} from '@e22m4u/js-service';
7
+
8
+ /**
9
+ * Service.
10
+ */
11
+ export class DebuggableService extends Service {
12
+ /**
13
+ * Debug.
14
+ */
15
+ debug: Debugger;
16
+
17
+ /**
18
+ * Возвращает функцию-отладчик с сегментом пространства имен
19
+ * указанного в параметре метода.
20
+ *
21
+ * @param method
22
+ * @protected
23
+ */
24
+ protected getDebuggerFor(method: Callable) {
25
+ return this.debug.withHash().withNs(method.name);
26
+ }
27
+
28
+ /**
29
+ * Constructor.
30
+ *
31
+ * @param container
32
+ */
33
+ constructor(container?: ServiceContainer) {
34
+ super(container);
35
+ const serviceName = toCamelCase(this.constructor.name);
36
+ this.debug = createDebugger(serviceName).withoutEnvNs();
37
+ const debug = this.debug.withNs('constructor').withHash();
38
+ debug('Service created.');
39
+ }
40
+ }
@@ -0,0 +1 @@
1
+ export * from './debuggable-service.js';
package/src/types.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * A callable type with the "new" operator
3
+ * that allows class and constructor types.
4
+ */
5
+ export interface Constructor<T = object> {
6
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
+ new (...args: any[]): T;
8
+ }
9
+
10
+ /**
11
+ * An object prototype that excludes
12
+ * function and scalar values.
13
+ */
14
+ export type Prototype<T = object> = T &
15
+ object & {bind?: never} & {
16
+ call?: never;
17
+ } & {prototype?: object};
18
+
19
+ /**
20
+ * A function type without class and constructor.
21
+ */
22
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
+ export type Callable<T = unknown> = (...args: any[]) => T;
24
+
25
+ /**
26
+ * Makes a specific property of T as optional.
27
+ */
28
+ export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
29
+
30
+ /**
31
+ * A part of the Flatten type.
32
+ */
33
+ export type Identity<T> = T;
34
+
35
+ /**
36
+ * Makes T more human-readable.
37
+ */
38
+ export type Flatten<T> = Identity<{[k in keyof T]: T[k]}>;
@@ -0,0 +1 @@
1
+ export * from './to-camel-case.js';
@@ -0,0 +1,11 @@
1
+ import {expect} from 'chai';
2
+ import {toCamelCase} from './to-camel-case.js';
3
+
4
+ describe('toCamelCase', function () {
5
+ it('returns a camelCase string', function () {
6
+ expect(toCamelCase('TestString')).to.be.eq('testString');
7
+ expect(toCamelCase('test-string')).to.be.eq('testString');
8
+ expect(toCamelCase('test string')).to.be.eq('testString');
9
+ expect(toCamelCase('Test string')).to.be.eq('testString');
10
+ });
11
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * To camel case.
3
+ *
4
+ * @param input
5
+ */
6
+ export function toCamelCase(input: string): string {
7
+ return input
8
+ .replace(/(^\w|[A-Z]|\b\w)/g, c => c.toUpperCase())
9
+ .replace(/\W+/g, '')
10
+ .replace(/(^\w)/g, c => c.toLowerCase());
11
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "rootDir": "src",
4
+ "outDir": "dist/esm",
5
+ "target": "es2022",
6
+ "module": "NodeNext",
7
+ "moduleResolution": "NodeNext",
8
+ "esModuleInterop": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+ "strict": true,
11
+ "skipLibCheck": true,
12
+ "declaration": true,
13
+ "emitDecoratorMetadata": true,
14
+ "experimentalDecorators": true,
15
+ "resolveJsonModule": true,
16
+ "incremental": false
17
+ }
18
+ }