@e22m4u/js-http-static-router 0.0.1 → 0.1.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.
@@ -0,0 +1,91 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import {escapeRegexp} from './utils/escape-regexp.js';
4
+ import {InvalidArgumentError} from '@e22m4u/js-format';
5
+
6
+ /**
7
+ * Static route.
8
+ */
9
+ export class StaticRoute {
10
+ /**
11
+ * Remote path.
12
+ *
13
+ * @type {string}
14
+ */
15
+ remotePath;
16
+
17
+ /**
18
+ * Resource path.
19
+ *
20
+ * @type {string}
21
+ */
22
+ resourcePath;
23
+
24
+ /**
25
+ * RegExp.
26
+ *
27
+ * @type {RegExp}
28
+ */
29
+ regexp;
30
+
31
+ /**
32
+ * Is file.
33
+ *
34
+ * @type {boolean}
35
+ */
36
+ isFile;
37
+
38
+ /**
39
+ * Constructor.
40
+ *
41
+ * @param {string} routeDef
42
+ */
43
+ constructor(routeDef) {
44
+ if (!routeDef || typeof routeDef !== 'object' || Array.isArray(routeDef)) {
45
+ throw new InvalidArgumentError(
46
+ 'Parameter "routeDef" must be an Object, but %v was given.',
47
+ routeDef,
48
+ );
49
+ }
50
+ // remotePath
51
+ if (typeof routeDef.remotePath !== 'string') {
52
+ throw new InvalidArgumentError(
53
+ 'Option "remotePath" must be a String, but %v was given.',
54
+ routeDef.remotePath,
55
+ );
56
+ }
57
+ if (!routeDef.remotePath.startsWith('/')) {
58
+ throw new InvalidArgumentError(
59
+ 'Option "remotePath" must starts with "/", but %v was given.',
60
+ routeDef.remotePath,
61
+ );
62
+ }
63
+ // resourcePath
64
+ if (typeof routeDef.resourcePath !== 'string') {
65
+ throw new InvalidArgumentError(
66
+ 'Option "resourcePath" must be a String, but %v was given.',
67
+ routeDef.resourcePath,
68
+ );
69
+ }
70
+ const resourcePath = path.resolve(routeDef.resourcePath);
71
+ let stats;
72
+ try {
73
+ stats = fs.statSync(resourcePath);
74
+ } catch (error) {
75
+ console.error(error);
76
+ throw new InvalidArgumentError(
77
+ 'Resource path %v does not exist.',
78
+ resourcePath,
79
+ );
80
+ }
81
+ const isFile = stats.isFile();
82
+ const escapedRemotePath = escapeRegexp(routeDef.remotePath);
83
+ const regexp = isFile
84
+ ? new RegExp(`^${escapedRemotePath}$`)
85
+ : new RegExp(`^${escapedRemotePath}(?:$|\\/)`);
86
+ this.remotePath = routeDef.remotePath;
87
+ this.resourcePath = resourcePath;
88
+ this.regexp = regexp;
89
+ this.isFile = isFile;
90
+ }
91
+ }
@@ -0,0 +1,7 @@
1
+
2
+ /**
3
+ * Get pathname from url.
4
+ *
5
+ * @param request
6
+ */
7
+ export declare function getPathnameFromUrl(url: string): string;
@@ -0,0 +1,27 @@
1
+ import {InvalidArgumentError} from '@e22m4u/js-format';
2
+
3
+ /**
4
+ * Host RegExp.
5
+ */
6
+ const HOST_RE = /^https?:\/\/[^/]+/;
7
+
8
+ /**
9
+ * Query string RegExp.
10
+ */
11
+ const QUERY_STRING_RE = /\?.*$/;
12
+
13
+ /**
14
+ * Get pathname from url.
15
+ *
16
+ * @param {string} url
17
+ * @returns {string}
18
+ */
19
+ export function getPathnameFromUrl(url) {
20
+ if (typeof url !== 'string') {
21
+ throw new InvalidArgumentError(
22
+ 'Parameter "url" must be a String, but %v was given.',
23
+ url,
24
+ );
25
+ }
26
+ return url.replace(HOST_RE, '').replace(QUERY_STRING_RE, '');
27
+ }
@@ -0,0 +1,37 @@
1
+ import {expect} from 'chai';
2
+ import {format} from '@e22m4u/js-format';
3
+ import {getPathnameFromUrl} from './get-pathname-from-url.js';
4
+
5
+ describe('getPathnameFromUrl', function () {
6
+ it('should require the parameter "request" to be a String', function () {
7
+ const throwable = v => () => getPathnameFromUrl(v);
8
+ const error = v =>
9
+ format('Parameter "url" must be a String, but %s was given.', v);
10
+ expect(throwable(10)).to.throw(error('10'));
11
+ expect(throwable(0)).to.throw(error('0'));
12
+ expect(throwable(true)).to.throw(error('true'));
13
+ expect(throwable(false)).to.throw(error('false'));
14
+ expect(throwable(null)).to.throw(error('null'));
15
+ expect(throwable({})).to.throw(error('Object'));
16
+ expect(throwable([])).to.throw(error('Array'));
17
+ expect(throwable(undefined)).to.throw(error('undefined'));
18
+ throwable('str')();
19
+ throwable('')();
20
+ });
21
+
22
+ it('should return a pathname without a query string', function () {
23
+ const res1 = getPathnameFromUrl('pathname?foo=bar');
24
+ const res2 = getPathnameFromUrl('/pathname?foo=bar');
25
+ const res3 = getPathnameFromUrl('http://example.com/pathname?foo=bar');
26
+ expect(res1).to.be.eq('pathname');
27
+ expect(res2).to.be.eq('/pathname');
28
+ expect(res3).to.be.eq('/pathname');
29
+ });
30
+
31
+ it('should preserve a trailing slash', function () {
32
+ const res1 = getPathnameFromUrl('/pathname/');
33
+ expect(res1).to.be.eq('/pathname/');
34
+ const res2 = getPathnameFromUrl('/pathname/?foo=bar');
35
+ expect(res2).to.be.eq('/pathname/');
36
+ });
37
+ });
@@ -1,2 +1,2 @@
1
1
  export * from './escape-regexp.js';
2
- export * from './normalize-path.js';
2
+ export * from './get-pathname-from-url.js';
@@ -1,2 +1,2 @@
1
1
  export * from './escape-regexp.js';
2
- export * from './normalize-path.js';
2
+ export * from './get-pathname-from-url.js';
@@ -1,10 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <title>Index Page</title>
5
- </head>
6
- <body>
7
- <h1>Index Page</h1>
8
- <p>at /static/nested/index.html</p>
9
- </body>
10
- </html>
package/src/types.d.ts DELETED
@@ -1,38 +0,0 @@
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]}>;
@@ -1,12 +0,0 @@
1
- /**
2
- * Normalize path.
3
- *
4
- * Заменяет любые повторяющиеся слеши на один.
5
- * Удаляет пробельные символы в начале и конце.
6
- * Удаляет слеш в конце строки.
7
- * Гарантирует слеш в начале строки (по умолчанию).
8
- *
9
- * @param value
10
- * @param noStartingSlash
11
- */
12
- export function normalizePath(value: string, noStartingSlash?: boolean): string;
@@ -1,22 +0,0 @@
1
- /**
2
- * Normalize path.
3
- *
4
- * Заменяет любые повторяющиеся слеши на один.
5
- * Удаляет пробельные символы в начале и конце.
6
- * Удаляет слеш в конце строки.
7
- * Гарантирует слеш в начале строки (по умолчанию).
8
- *
9
- * @param {string} value
10
- * @param {boolean} [noStartingSlash]
11
- * @returns {string}
12
- */
13
- export function normalizePath(value, noStartingSlash = false) {
14
- if (typeof value !== 'string') {
15
- return '/';
16
- }
17
- const res = value
18
- .trim()
19
- .replace(/\/+/g, '/')
20
- .replace(/(^\/|\/$)/g, '');
21
- return noStartingSlash ? res : '/' + res;
22
- }