webhoster 0.1.0 → 0.3.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 (86) hide show
  1. package/.eslintrc.json +74 -58
  2. package/.github/copilot-instructions.md +100 -0
  3. package/.github/workflows/test-matrix.yml +37 -0
  4. package/.test/benchmark.js +28 -0
  5. package/.test/constants.js +4 -0
  6. package/{test → .test}/http2server.js +1 -1
  7. package/{test → .test}/httpserver.js +1 -1
  8. package/{test → .test}/index.js +178 -192
  9. package/.test/multipromise.js +32 -0
  10. package/{test → .test}/tls.js +3 -3
  11. package/{test → .test}/urlencoded.js +3 -0
  12. package/.vscode/launch.json +24 -3
  13. package/README.md +116 -90
  14. package/data/CookieObject.js +14 -14
  15. package/errata/socketio.js +6 -11
  16. package/examples/starter.js +11 -0
  17. package/helpers/HeadersParser.js +7 -8
  18. package/helpers/HttpListener.js +387 -42
  19. package/helpers/RequestHeaders.js +43 -36
  20. package/helpers/RequestReader.js +27 -26
  21. package/helpers/ResponseHeaders.js +47 -36
  22. package/jsconfig.json +1 -1
  23. package/lib/HttpHandler.js +447 -277
  24. package/lib/HttpRequest.js +383 -39
  25. package/lib/HttpResponse.js +316 -52
  26. package/lib/HttpTransaction.js +146 -0
  27. package/middleware/AutoHeadersMiddleware.js +73 -0
  28. package/middleware/CORSMiddleware.js +45 -47
  29. package/middleware/CaseInsensitiveHeadersMiddleware.js +5 -11
  30. package/middleware/ContentDecoderMiddleware.js +81 -35
  31. package/middleware/ContentEncoderMiddleware.js +179 -132
  32. package/middleware/ContentLengthMiddleware.js +66 -43
  33. package/middleware/ContentWriterMiddleware.js +5 -11
  34. package/middleware/HashMiddleware.js +68 -40
  35. package/middleware/HeadMethodMiddleware.js +24 -22
  36. package/middleware/MethodMiddleware.js +29 -36
  37. package/middleware/PathMiddleware.js +49 -66
  38. package/middleware/ReadFormData.js +99 -0
  39. package/middleware/SendHeadersMiddleware.js +0 -2
  40. package/middleware/SendJsonMiddleware.js +131 -0
  41. package/middleware/SendStringMiddleware.js +87 -0
  42. package/package.json +38 -29
  43. package/polyfill/FormData.js +164 -0
  44. package/rollup.config.js +0 -1
  45. package/scripts/test-all-sync.sh +6 -0
  46. package/scripts/test-all.sh +7 -0
  47. package/templates/starter.js +53 -0
  48. package/test/fixtures/stream.js +68 -0
  49. package/test/helpers/HttpListener/construct.js +18 -0
  50. package/test/helpers/HttpListener/customOptions.js +22 -0
  51. package/test/helpers/HttpListener/doubleCreate.js +40 -0
  52. package/test/helpers/HttpListener/events.js +77 -0
  53. package/test/helpers/HttpListener/http.js +31 -0
  54. package/test/helpers/HttpListener/http2.js +41 -0
  55. package/test/helpers/HttpListener/https.js +38 -0
  56. package/test/helpers/HttpListener/startAll.js +31 -0
  57. package/test/helpers/HttpListener/stopNotStarted.js +23 -0
  58. package/test/lib/HttpHandler/class.js +8 -0
  59. package/test/lib/HttpHandler/handleRequest.js +11 -0
  60. package/test/lib/HttpHandler/middleware.js +941 -0
  61. package/test/lib/HttpHandler/parse.js +41 -0
  62. package/test/lib/HttpRequest/class.js +8 -0
  63. package/test/lib/HttpRequest/downstream.js +171 -0
  64. package/test/lib/HttpRequest/properties.js +101 -0
  65. package/test/lib/HttpRequest/read.js +518 -0
  66. package/test/lib/HttpResponse/class.js +8 -0
  67. package/test/lib/HttpResponse/properties.js +59 -0
  68. package/test/lib/HttpResponse/send.js +275 -0
  69. package/test/lib/HttpTransaction/class.js +8 -0
  70. package/test/lib/HttpTransaction/ping.js +50 -0
  71. package/test/lib/HttpTransaction/push.js +89 -0
  72. package/test/middleware/SendJsonMiddleware.js +222 -0
  73. package/test/sanity.js +10 -0
  74. package/test/templates/starter.js +93 -0
  75. package/tsconfig.json +12 -0
  76. package/types/index.js +61 -34
  77. package/types/typings.d.ts +8 -9
  78. package/utils/AsyncObject.js +6 -3
  79. package/utils/CaseInsensitiveObject.js +2 -3
  80. package/utils/function.js +1 -7
  81. package/utils/headers.js +42 -0
  82. package/utils/qualityValues.js +1 -1
  83. package/utils/stream.js +4 -20
  84. package/index.cjs +0 -3200
  85. package/test/constants.js +0 -4
  86. /package/{test → .test}/cookietester.js +0 -0
@@ -0,0 +1,131 @@
1
+ /** @typedef {import('../types').IMiddleware} IMiddleware */
2
+ /** @typedef {import('../types').MiddlewareResponseFunction} MiddlewareResponseFunction */
3
+ /** @typedef {import('../types').MiddlewareFunction} MiddlewareFunction */
4
+ /** @typedef {import('../types/index.js').ResponseFinalizer} ResponseFinalizer */
5
+
6
+ /**
7
+ * @typedef {Object} SendJsonMiddlewareOptions
8
+ * @prop {string} [defaultCharset='utf-8']
9
+ * @prop {boolean} [setCharset=true]
10
+ * Automatically applies charset in `Content-Type`
11
+ * @prop {boolean} [setMediaType=true]
12
+ * Automatically applies `application/json` mediatype in `Content-Type`
13
+ */
14
+
15
+ /* eslint-disable unicorn/text-encoding-identifier-case */
16
+
17
+ export default class SendJsonMiddleware {
18
+ /** @type {SendJsonMiddleware} */
19
+ static #defaultInstance;
20
+
21
+ /**
22
+ * @param {string} charset
23
+ * @return {BufferEncoding}
24
+ */
25
+ static charsetAsBufferEncoding(charset) {
26
+ switch (charset) {
27
+ case 'iso-8859-1':
28
+ case 'ascii':
29
+ case 'binary':
30
+ case 'latin1':
31
+ return 'latin1';
32
+ case 'utf-16le':
33
+ case 'ucs-2':
34
+ case 'ucs2':
35
+ case 'utf16le':
36
+ return 'utf16le';
37
+ case 'base64':
38
+ case 'hex':
39
+ return /** @type {BufferEncoding} */ (charset);
40
+ case 'utf-8':
41
+ case 'utf8':
42
+ default:
43
+ return 'utf-8';
44
+ }
45
+ }
46
+
47
+ /** @type {MiddlewareResponseFunction} */
48
+ static Execute({ response }) {
49
+ if (!SendJsonMiddleware.#defaultInstance) {
50
+ SendJsonMiddleware.#defaultInstance = new SendJsonMiddleware({
51
+ defaultCharset: 'utf-8',
52
+ setCharset: true,
53
+ setMediaType: true,
54
+ });
55
+ }
56
+ response.finalizers.push(SendJsonMiddleware.#defaultInstance.finalizeResponse);
57
+ }
58
+
59
+ /** @param {SendJsonMiddlewareOptions} [options] */
60
+ constructor(options = {}) {
61
+ this.options = {
62
+ defaultCharset: options.defaultCharset || 'utf-8',
63
+ setCharset: options.setCharset !== false,
64
+ setMediaType: options.setMediaType !== false,
65
+ };
66
+ // Single shared function instead of one per response
67
+ this.finalizeResponse = this.finalizeResponse.bind(this);
68
+ }
69
+
70
+ /** @type {ResponseFinalizer} */
71
+ finalizeResponse(response) {
72
+ if (response.isStreaming
73
+ || response.body == null
74
+ || typeof response.body !== 'object'
75
+ || Buffer.isBuffer(response.body)) return;
76
+
77
+ // TODO: Check response.request.headers.accepts
78
+
79
+ let charset;
80
+ const contentType = /** @type {string} */ (response.headers['content-type']);
81
+ if (contentType) {
82
+ const newDirectives = [];
83
+ for (const directive of contentType.split(';')) {
84
+ const [key, value] = directive.split('=');
85
+ if (key?.trim().toLowerCase() !== 'charset') {
86
+ newDirectives.push(directive);
87
+ continue;
88
+ }
89
+ charset = value?.trim().toLowerCase();
90
+ const firstQuote = charset.indexOf('"');
91
+ const lastQuote = charset.lastIndexOf('"');
92
+ if (firstQuote !== -1 && lastQuote !== -1) {
93
+ charset = charset.slice(firstQuote + 1, lastQuote);
94
+ }
95
+ break;
96
+ }
97
+
98
+ if (!charset) {
99
+ charset = this.options.defaultCharset;
100
+ }
101
+
102
+ if (this.options.setCharset && !response.headersSent) {
103
+ newDirectives.push(`charset=${charset}`);
104
+ response.headers['content-type'] = newDirectives.join(';');
105
+ }
106
+ } else if (this.options.setMediaType) {
107
+ charset = this.options.defaultCharset;
108
+ if (!response.headersSent) {
109
+ response.headers['content-type'] = this.options.setCharset
110
+ ? `application/json;charset=${charset}`
111
+ : 'application/json';
112
+ }
113
+ } else if (this.options.setCharset) {
114
+ charset = this.options.defaultCharset;
115
+ if (!response.headersSent) {
116
+ response.headers['content-type'] = `;charset=${charset}`;
117
+ }
118
+ } else {
119
+ // noop?
120
+ }
121
+
122
+ const stringData = JSON.stringify(response.body);
123
+ const bufferEncoding = SendJsonMiddleware.charsetAsBufferEncoding(charset);
124
+ response.body = Buffer.from(stringData, bufferEncoding);
125
+ }
126
+
127
+ /** @type {MiddlewareResponseFunction} */
128
+ execute({ response }) {
129
+ response.finalizers.push(this.finalizeResponse);
130
+ }
131
+ }
@@ -0,0 +1,87 @@
1
+ /** @typedef {import('../types/index.js').IMiddleware} IMiddleware */
2
+ /** @typedef {import('../types/index.js').MiddlewareFunction} MiddlewareFunction */
3
+ /** @typedef {import('../types/index.js').ResponseFinalizer} ResponseFinalizer */
4
+
5
+ /**
6
+ * @typedef {Object} SendStringMiddlewareOptions
7
+ * @prop {string} [defaultCharset='utf-8']
8
+ * @prop {boolean} [setCharset=true]
9
+ * Automatically applies charset in `Content-Type`
10
+ */
11
+
12
+ export default class SendStringMiddleware {
13
+ /** @param {SendStringMiddlewareOptions} [options] */
14
+ constructor(options = {}) {
15
+ this.options = {
16
+ defaultCharset: options.defaultCharset || 'utf-8',
17
+ setCharset: options.setCharset !== false,
18
+ };
19
+ // Single shared function instead of one per response
20
+ this.finalizeResponse = this.finalizeResponse.bind(this);
21
+ }
22
+
23
+ /**
24
+ * @param {string} charset
25
+ * @return {BufferEncoding}
26
+ */
27
+ static charsetAsBufferEncoding(charset) {
28
+ switch (charset) {
29
+ case 'iso-8859-1':
30
+ case 'ascii':
31
+ case 'binary':
32
+ case 'latin1':
33
+ return 'latin1';
34
+ case 'utf-16le':
35
+ case 'ucs-2':
36
+ case 'ucs2':
37
+ case 'utf16le':
38
+ return 'utf16le';
39
+ case 'base64':
40
+ case 'hex':
41
+ return /** @type {BufferEncoding} */ (charset);
42
+ case 'utf-8':
43
+ case 'utf8':
44
+ default:
45
+ return 'utf-8';
46
+ }
47
+ }
48
+
49
+ /** @type {ResponseFinalizer} */
50
+ finalizeResponse(response) {
51
+ if (response.isStreaming || typeof response.body !== 'string') return true;
52
+ let charset;
53
+ let contentType = /** @type {string} */ (response.headers['content-type']);
54
+ if (contentType) {
55
+ contentType.split(';').some((directive) => {
56
+ const parameters = directive.split('=');
57
+ if (parameters[0].trim().toLowerCase() !== 'charset') {
58
+ return false;
59
+ }
60
+ charset = parameters[1]?.trim().toLowerCase();
61
+ const firstQuote = charset.indexOf('"');
62
+ const lastQuote = charset.lastIndexOf('"');
63
+ if (firstQuote !== -1 && lastQuote !== -1) {
64
+ charset = charset.slice(firstQuote + 1, lastQuote);
65
+ }
66
+ return true;
67
+ });
68
+ } else {
69
+ contentType = '';
70
+ }
71
+ if (!charset) {
72
+ charset = this.options.defaultCharset || 'utf-8';
73
+ if (this.options.setCharset && !response.headersSent) {
74
+ response.headers['content-type'] = `${contentType || ''};charset=${charset}`;
75
+ }
76
+ }
77
+
78
+ const bufferEncoding = SendStringMiddleware.charsetAsBufferEncoding(charset);
79
+ response.body = Buffer.from(response.body, bufferEncoding);
80
+ return true;
81
+ }
82
+
83
+ /** @type {MiddlewareFunction} */
84
+ execute({ response }) {
85
+ response.finalizers.push(this.finalizeResponse);
86
+ }
87
+ }
package/package.json CHANGED
@@ -1,5 +1,31 @@
1
1
  {
2
- "name": "webhoster",
2
+ "author": "Carlos Lopez Jr. <clshortfuse@gmail.com> (https://shortfuse.org/)",
3
+ "ava": {
4
+ "files": [
5
+ "test/**/*.js",
6
+ "!test/fixtures/**"
7
+ ]
8
+ },
9
+ "description": "An opt-in, stream-based approach to Web Hosting with NodeJS",
10
+ "devDependencies": {
11
+ "@fidm/x509": "^1.2.1",
12
+ "@types/node": "^16.18.126",
13
+ "@typescript-eslint/eslint-plugin": "^6.21.0",
14
+ "@typescript-eslint/parser": "^6.21.0",
15
+ "ava": "^4.3.3",
16
+ "c8": "^7.14.0",
17
+ "eslint-config-airbnb-base": "^15.0.0",
18
+ "eslint-plugin-canonical": "^4.18.1",
19
+ "eslint-plugin-jsdoc": "^46.10.1",
20
+ "eslint-plugin-n": "^16.6.2",
21
+ "eslint-plugin-unicorn": "^48.0.1"
22
+ },
23
+ "engines": {
24
+ "node": ">v16.13"
25
+ },
26
+ "exports": {
27
+ "./*": "./*"
28
+ },
3
29
  "keywords": [
4
30
  "http",
5
31
  "http2",
@@ -11,35 +37,18 @@
11
37
  "cors",
12
38
  "gzip"
13
39
  ],
14
- "version": "0.1.0",
15
- "description": "An opt-in, stream-based approach to Web Hosting with NodeJS",
16
- "author": "clshortfuse@gmail.com",
17
- "homepage": "https://github.com/clshortfuse/webhoster",
18
- "repository": "github:clshortfuse/webhoster",
19
40
  "license": "MIT",
20
- "main": "index.cjs",
21
- "exports": {
22
- "./": "./"
23
- },
24
- "type": "module",
25
- "engines": {
26
- "node": ">=14"
27
- },
41
+ "name": "webhoster",
28
42
  "scripts": {
29
- "prepublishOnly": "rollup -c",
30
- "test": "echo \"Error: no test specified\" && exit 1"
43
+ "debug-test": "ava --serial",
44
+ "test": "c8 ava",
45
+ "pretestallsync": "rimraf coverage",
46
+ "testallsync": "scripts/test-all-sync.sh",
47
+ "posttestallsync": "c8 report",
48
+ "pretestall": "rimraf coverage",
49
+ "testall": "scripts/test-all.sh",
50
+ "posttestall": "c8 report"
31
51
  },
32
- "devDependencies": {
33
- "@fidm/x509": "^1.2.1",
34
- "@types/node": "^14.0.14",
35
- "@types/tedious": "^4.0.1",
36
- "babel-eslint": "^10.1.0",
37
- "eslint": "^7.3.1",
38
- "eslint-config-airbnb-base": "^14.2.0",
39
- "eslint-plugin-babel": "^5.3.0",
40
- "eslint-plugin-import": "^2.22.0",
41
- "eslint-plugin-jsdoc": "^25.4.3",
42
- "eslint-plugin-node": "^11.1.0",
43
- "rollup": "^2.18.1"
44
- }
52
+ "type": "module",
53
+ "version": "0.3.0"
45
54
  }
@@ -0,0 +1,164 @@
1
+ /* @see https://xhr.spec.whatwg.org/#dom-formdata */
2
+
3
+ /** @implements {FormData} */
4
+ export default class FormData {
5
+ /** @type {Map<string, (string|File)[]>} */
6
+ #list = new Map();
7
+
8
+ /** @param {HTMLFormElement} [form] */
9
+ constructor(form) {
10
+ if (form) {
11
+ throw new Error('InvalidStateError');
12
+ }
13
+ }
14
+
15
+ /**
16
+ * @param {string} s
17
+ * @return {string}
18
+ */
19
+ static #scalarValue = String;
20
+
21
+ /**
22
+ * @param {string} name
23
+ * @param {string|Blob} value
24
+ * @param {string} [filename]
25
+ * @return {{name:string, value:string|File}}
26
+ */
27
+ static #createEntry(name, value, filename) {
28
+ if (typeof value === 'string') {
29
+ return {
30
+ name: FormData.#scalarValue(name),
31
+ value: FormData.#scalarValue(value),
32
+ };
33
+ }
34
+
35
+ if (typeof File === 'undefined') {
36
+ if (!('name' in value) && !('lastModified' in value)) {
37
+ /** @type {File} */
38
+ // eslint-disable-next-line unicorn/prefer-spread
39
+ const file = Object.defineProperties(value.slice(), {
40
+ name: {
41
+ value: filename === undefined ? 'blob' : filename,
42
+ },
43
+ lastModified: {
44
+ value: Date.now(),
45
+ },
46
+ toString: { value: () => '[object File]' },
47
+ });
48
+ return {
49
+ name: FormData.#scalarValue(name),
50
+ value: file,
51
+ };
52
+ }
53
+ return {
54
+ name: FormData.#scalarValue(name),
55
+ value,
56
+ };
57
+ }
58
+ if (value instanceof File) {
59
+ return {
60
+ name: FormData.#scalarValue(name),
61
+ value,
62
+ };
63
+ }
64
+ return {
65
+ name: FormData.#scalarValue(name),
66
+ value: new File([value], filename === undefined ? 'blob' : filename, {}),
67
+ };
68
+ }
69
+
70
+ /**
71
+ * @param {string} name
72
+ * @param {string|Blob} value
73
+ * @param {string} [filename]
74
+ * @return {void}
75
+ */
76
+ append(name, value, filename) {
77
+ const entry = FormData.#createEntry(name, value, filename);
78
+ console.log(entry);
79
+ if (this.#list.has(entry.name)) {
80
+ this.#list.get(entry.name).push(entry.value);
81
+ } else {
82
+ this.#list.set(name, [entry.value]);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * @param {string} name
88
+ * @return {void}
89
+ */
90
+ delete(name) {
91
+ this.#list.delete(name);
92
+ }
93
+
94
+ /**
95
+ * @param {string} name
96
+ * @return {null|File|string}
97
+ */
98
+ get(name) {
99
+ const entry = this.#list.get(name);
100
+ if (!entry) return null;
101
+ return entry[0];
102
+ }
103
+
104
+ /**
105
+ * @param {string} name
106
+ * @return {(File|string)[]}
107
+ */
108
+ getAll(name) {
109
+ return this.#list.get(name) ?? [];
110
+ }
111
+
112
+ /**
113
+ * @param {string} name
114
+ * @return {boolean}
115
+ */
116
+ has(name) {
117
+ return this.#list.has(name);
118
+ }
119
+
120
+ /**
121
+ * @param {string} name
122
+ * @param {string|Blob} value
123
+ * @param {string} [filename]
124
+ * @return {void}
125
+ */
126
+ set(name, value, filename) {
127
+ const entry = FormData.#createEntry(name, value, filename);
128
+ if (this.#list.has(entry.name)) {
129
+ const entries = this.#list.get(name);
130
+ entries.splice(0, entries.length, entry.value);
131
+ } else {
132
+ this.#list.set(name, [entry.value]);
133
+ }
134
+ }
135
+
136
+ /**
137
+ * @param {(value:(string|File), key:string, parent:this) => void} callback
138
+ * @return {void}
139
+ */
140
+ forEach(callback) {
141
+ for (const [key, value] of this) {
142
+ callback(value, key, this);
143
+ }
144
+ }
145
+
146
+ get keys() {
147
+ return this.#list.keys;
148
+ }
149
+
150
+ * values() {
151
+ for (const value of this.#list.values()) {
152
+ yield value[0];
153
+ }
154
+ }
155
+
156
+ * [Symbol.iterator]() {
157
+ for (const entry of this.#list.entries()) {
158
+ yield /** @type {[string, string|File]} */ ([entry[0], entry[1][0]]);
159
+ }
160
+ }
161
+ }
162
+
163
+ FormData.prototype.entries = FormData.prototype[Symbol.iterator];
164
+ FormData.prototype.toString = () => '[Object FormData]';
package/rollup.config.js CHANGED
@@ -1,4 +1,3 @@
1
- /* eslint-disable import/no-anonymous-default-export */
2
1
  /** @typedef {import('rollup')} */
3
2
  export default {
4
3
  input: 'index.js',
@@ -0,0 +1,6 @@
1
+ . ~/.nvm/nvm.sh;
2
+ nvm install 16.13; nvm use 16.13; npx c8 --clean false -r none ava;
3
+ nvm install 16 ; nvm use 16 ; npx c8 --clean false -r none ava;
4
+ nvm install 18 ; nvm use 18 ; npx c8 --clean false -r none ava;
5
+ nvm install 20 ; nvm use 20 ; npx c8 --clean false -r none ava;
6
+ nvm install 22 ; nvm use 22 ; npx c8 --clean false -r none ava;
@@ -0,0 +1,7 @@
1
+ echo . \
2
+ & sh -c ". ~/.nvm/nvm.sh; nvm install 16.13; nvm use 16.13; npx c8 --clean false -r none ava;" \
3
+ & sh -c ". ~/.nvm/nvm.sh; nvm install 16; nvm use 16; npx c8 --clean false -r none ava;" \
4
+ & sh -c ". ~/.nvm/nvm.sh; nvm install 18; nvm use 18; npx c8 --clean false -r none ava;" \
5
+ & sh -c ". ~/.nvm/nvm.sh; nvm install 20; nvm use 20; npx c8 --clean false -r none ava;" \
6
+ & sh -c ". ~/.nvm/nvm.sh; nvm install 22; nvm use 22; npx c8 --clean false -r none ava;" \
7
+
@@ -0,0 +1,53 @@
1
+ import HttpHandler from '../lib/HttpHandler.js';
2
+ import HttpListener from '../helpers/HttpListener.js';
3
+ import ContentDecoderMiddleware from '../middleware/ContentDecoderMiddleware.js';
4
+ import SendStringMiddleware from '../middleware/SendStringMiddleware.js';
5
+ import SendJsonMiddleware from '../middleware/SendJsonMiddleware.js';
6
+ import ContentEncoderMiddleware from '../middleware/ContentEncoderMiddleware.js';
7
+ import HashMiddleware from '../middleware/HashMiddleware.js';
8
+ import ContentLengthMiddleware from '../middleware/ContentLengthMiddleware.js';
9
+ import AutoHeadersMiddleware from '../middleware/AutoHeadersMiddleware.js';
10
+ import HeadMethodMiddleware from '../middleware/HeadMethodMiddleware.js';
11
+
12
+ /**
13
+ * @param {Object} options
14
+ * @param {string} [options.host='0.0.0.0']
15
+ * @param {number} [options.port=8080]
16
+ * @param {import('../types').Middleware[]} [options.middleware]
17
+ * @param {import('../types').MiddlewareErrorHandler[]} [options.errorHandlers]
18
+ * @return {Promise<import('../helpers/HttpListener.js').default>}
19
+ */
20
+ export async function start(options) {
21
+ HttpHandler.defaultInstance.middleware.push(
22
+ new ContentDecoderMiddleware(),
23
+ new SendStringMiddleware(),
24
+ new SendJsonMiddleware(),
25
+ new ContentEncoderMiddleware(),
26
+ new HashMiddleware(),
27
+ new ContentLengthMiddleware(),
28
+ new AutoHeadersMiddleware(),
29
+ new HeadMethodMiddleware(),
30
+ );
31
+ if (options.middleware) {
32
+ // Push by reference to allow post modification
33
+ HttpHandler.defaultInstance.middleware.push(options.middleware);
34
+ }
35
+ if (!options.errorHandlers) {
36
+ HttpHandler.defaultInstance.errorHandlers.push(
37
+ {
38
+ onError() {
39
+ return 500;
40
+ },
41
+ },
42
+ );
43
+ }
44
+
45
+ HttpListener.defaultInstance.configure({
46
+ insecureHost: options.host,
47
+ insecurePort: options.port,
48
+ });
49
+
50
+ await HttpListener.defaultInstance.startHttpServer();
51
+
52
+ return HttpListener.defaultInstance;
53
+ }
@@ -0,0 +1,68 @@
1
+ import { createHash } from 'node:crypto';
2
+ import {
3
+ Readable, pipeline as legacyPipeline,
4
+ } from 'node:stream';
5
+ import { promisify } from 'node:util';
6
+
7
+ /** @type {import('node:stream/promises').pipeline} */
8
+ let pipeline;
9
+ try {
10
+ ({ pipeline } = (await import('node:stream/promises')));
11
+ } catch {
12
+ pipeline = promisify(legacyPipeline);
13
+ }
14
+
15
+ const BUFFER_SIZE = 1024 * 16;
16
+ const CHUNK_SIZE = 256 / 8;
17
+ const CHUNK_COUNT = BUFFER_SIZE / CHUNK_SIZE;
18
+
19
+ const SEED = Math.floor(Math.random() * (2 ** 4));
20
+
21
+ /** @yields {Buffer} */
22
+ function* binaryGenerator() {
23
+ for (let index = 0; index < CHUNK_COUNT; index++) {
24
+ const number_ = (SEED + index);
25
+ /* eslint-disable no-bitwise */
26
+ yield createHash('sha256').update(Buffer.from([
27
+ (number_ >> 24) & 255,
28
+ (number_ >> 16) & 255,
29
+ (number_ >> 8) & 255,
30
+ number_ & 255,
31
+ ])).digest();
32
+ /* eslint-enable no-bitwise */
33
+ }
34
+ }
35
+
36
+ /** @yields {Buffer} */
37
+ function* textGenerator() {
38
+ for (const chunk of binaryGenerator()) {
39
+ const hexString = chunk.toString('hex');
40
+ yield Buffer.from(hexString, 'utf-8');
41
+ }
42
+ }
43
+
44
+ /** @return {Readable} */
45
+ export function getTestBinaryStream() {
46
+ return Readable.from(binaryGenerator());
47
+ }
48
+
49
+ /** @return {Readable} */
50
+ export function getTestTextStream() {
51
+ return Readable.from(textGenerator());
52
+ }
53
+
54
+ /** @return {Promise<string>} */
55
+ export async function getTestHash() {
56
+ const hash = createHash('sha256');
57
+ await pipeline(binaryGenerator(), hash);
58
+ return hash.digest().toString('hex');
59
+ }
60
+
61
+ /** @return {string} */
62
+ export function getTestString() {
63
+ let data = '';
64
+ for (const chunk of textGenerator()) {
65
+ data += chunk;
66
+ }
67
+ return data;
68
+ }
@@ -0,0 +1,18 @@
1
+ import test from 'ava';
2
+
3
+ import HttpListener from '../../../helpers/HttpListener.js';
4
+
5
+ test('HttpListener can be constructed with defaults', (t) => {
6
+ const listener = new HttpListener();
7
+ t.truthy(listener);
8
+ t.is(typeof listener.startHttpServer, 'function');
9
+ t.is(typeof listener.stopHttpServer, 'function');
10
+ });
11
+
12
+ test('HttpListener.defaultInstance returns a singleton', (t) => {
13
+ const inst1 = HttpListener.defaultInstance;
14
+ const inst2 = HttpListener.defaultInstance;
15
+ t.truthy(inst1);
16
+ t.is(inst1, inst2);
17
+ t.true(inst1 instanceof HttpListener);
18
+ });
@@ -0,0 +1,22 @@
1
+ import test from 'ava';
2
+ import HttpListener from '../../../helpers/HttpListener.js';
3
+
4
+ // Test custom port/host and handler injection
5
+
6
+ test('custom insecurePort and insecureHost are set', t => {
7
+ const listener = new HttpListener({ insecurePort: 1234, insecureHost: '127.0.0.1' });
8
+ t.is(listener.insecurePort, 1234);
9
+ t.is(listener.insecureHost, '127.0.0.1');
10
+ });
11
+
12
+ test('custom securePort and secureHost are set', t => {
13
+ const listener = new HttpListener({ securePort: 4321, secureHost: 'localhost' });
14
+ t.is(listener.securePort, 4321);
15
+ t.is(listener.secureHost, 'localhost');
16
+ });
17
+
18
+ test('custom httpHandler is set', t => {
19
+ const fakeHandler = { handleHttp1Request() {}, handleHttp2Stream() {} };
20
+ const listener = new HttpListener({ httpHandler: fakeHandler });
21
+ t.is(listener.httpHandler, fakeHandler);
22
+ });
@@ -0,0 +1,40 @@
1
+ import test from 'ava';
2
+
3
+ import HttpListener, { SERVER_ALREADY_CREATED } from '../../../helpers/HttpListener.js';
4
+
5
+ // Test double server creation throws error
6
+ test('createHttpServer throws if called twice with custom options', (t) => {
7
+ const listener = new HttpListener();
8
+ listener.createHttpServer();
9
+ t.notThrows(() => listener.createHttpServer());
10
+ t.notThrows(() => listener.createHttpServer({}));
11
+ const err = t.throws(() => listener.createHttpServer({ maxHeaderSize: 8192 }));
12
+ t.truthy(err);
13
+ t.is(err.message, SERVER_ALREADY_CREATED);
14
+ });
15
+
16
+ // Use environment variables for PEM string values
17
+ const key = process.env.TEST_SSL_KEY;
18
+ const cert = process.env.TEST_SSL_CERT;
19
+ const haveCerts = key && cert;
20
+ const testFn = (haveCerts ? test : test.skip);
21
+
22
+ testFn('createHttpsServer throws if called twice with custom options', (t) => {
23
+ const listener = new HttpListener({ useHttps: true, tlsOptions: { key, cert } });
24
+ listener.createHttpsServer();
25
+ t.notThrows(() => listener.createHttpsServer());
26
+ t.notThrows(() => listener.createHttpsServer({}));
27
+ const err = t.throws(() => listener.createHttpsServer({ maxHeaderSize: 8192 }));
28
+ t.truthy(err);
29
+ t.is(err.message, SERVER_ALREADY_CREATED);
30
+ });
31
+
32
+ testFn('createHttp2Server throws if called twice with custom options', (t) => {
33
+ const listener = new HttpListener({ useHttp2: true, tlsOptions: { key, cert } });
34
+ listener.createHttp2Server();
35
+ t.notThrows(() => listener.createHttp2Server());
36
+ t.notThrows(() => listener.createHttp2Server({}));
37
+ const err = t.throws(() => listener.createHttp2Server({ settings: { maxConcurrentStreams: 100 } }));
38
+ t.truthy(err);
39
+ t.is(err.message, SERVER_ALREADY_CREATED);
40
+ });