@hyperttp/core 1.2.6 → 1.3.1
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/Core/HyperCore.d.ts +145 -23
- package/Core/HyperCore.d.ts.map +1 -1
- package/Core/HyperCore.js +325 -231
- package/Core/HyperCore.js.map +1 -1
- package/package.json +6 -3
- package/transports/manager.d.ts +102 -0
- package/transports/manager.d.ts.map +1 -0
- package/transports/manager.js +293 -0
- package/transports/manager.js.map +1 -0
- package/transports/node.d.ts +40 -10
- package/transports/node.d.ts.map +1 -1
- package/transports/node.js +106 -325
- package/transports/node.js.map +1 -1
- package/utils/decompress.d.ts +29 -0
- package/utils/decompress.d.ts.map +1 -0
- package/utils/decompress.js +117 -0
- package/utils/decompress.js.map +1 -0
- package/utils/normalize.d.ts +28 -1
- package/utils/normalize.d.ts.map +1 -1
- package/utils/normalize.js +173 -61
- package/utils/normalize.js.map +1 -1
- package/utils/pipeline.d.ts +51 -10
- package/utils/pipeline.d.ts.map +1 -1
- package/utils/pipeline.js +126 -21
- package/utils/pipeline.js.map +1 -1
- package/utils/response.d.ts +0 -3
- package/utils/response.d.ts.map +1 -1
- package/utils/response.js +0 -3
- package/utils/response.js.map +1 -1
- package/utils/retryUtils.d.ts +20 -0
- package/utils/retryUtils.d.ts.map +1 -1
- package/utils/retryUtils.js +24 -0
- package/utils/retryUtils.js.map +1 -1
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { brotliDecompressSync, createBrotliDecompress, createGunzip, createInflate, gunzipSync, inflateSync, } from "node:zlib";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
|
+
/**
|
|
4
|
+
* @ru Разбирает строку Content-Encoding на массив кодировок (без identity).
|
|
5
|
+
* @en Parses a Content-Encoding string into an array of encodings (excluding identity).
|
|
6
|
+
* @param encoding - The Content-Encoding header value.
|
|
7
|
+
* @returns Array of normalized encoding names.
|
|
8
|
+
*/
|
|
9
|
+
function parseEncodings(encoding) {
|
|
10
|
+
return encoding
|
|
11
|
+
.split(",")
|
|
12
|
+
.map((part) => part.trim().toLowerCase())
|
|
13
|
+
.filter((part) => part.length > 0 && part !== "identity");
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* @ru Прикрепляет пустой метод dump к буферу для соответствия интерфейсу TransportStreamExtensions.
|
|
17
|
+
* @en Attaches a no-op dump method to a buffer to conform to TransportStreamExtensions.
|
|
18
|
+
* @param buffer - The buffer to decorate.
|
|
19
|
+
* @returns The same buffer with a dump method.
|
|
20
|
+
*/
|
|
21
|
+
function attachNoopDump(buffer) {
|
|
22
|
+
const payload = buffer;
|
|
23
|
+
payload.dump = async () => { };
|
|
24
|
+
return payload;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* @ru Прикрепляет метод dump, который отменяет поток, к ReadableStream.
|
|
28
|
+
* @en Attaches a dump method that cancels the stream to a ReadableStream.
|
|
29
|
+
* @param stream - The stream to decorate.
|
|
30
|
+
* @returns The same stream with a dump method.
|
|
31
|
+
*/
|
|
32
|
+
function attachStreamDump(stream) {
|
|
33
|
+
const payload = stream;
|
|
34
|
+
payload.dump = async () => {
|
|
35
|
+
try {
|
|
36
|
+
await payload.cancel();
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
//
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
return payload;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* @ru Применяет декомпрессию один раз для заданной кодировки. Поддерживает gzip, deflate, br.
|
|
46
|
+
* @en Applies decompression once for a given encoding. Supports gzip, deflate, br.
|
|
47
|
+
* @param input - The compressed input buffer.
|
|
48
|
+
* @param encoding - Single encoding name (e.g., 'gzip', 'deflate', 'br').
|
|
49
|
+
* @returns Decompressed buffer, or original if encoding is not recognized.
|
|
50
|
+
*/
|
|
51
|
+
function decompressOnce(input, encoding) {
|
|
52
|
+
const buffer = Buffer.from(input);
|
|
53
|
+
switch (encoding) {
|
|
54
|
+
case "gzip":
|
|
55
|
+
case "x-gzip":
|
|
56
|
+
return gunzipSync(buffer);
|
|
57
|
+
case "deflate":
|
|
58
|
+
return inflateSync(buffer);
|
|
59
|
+
case "br":
|
|
60
|
+
return brotliDecompressSync(buffer);
|
|
61
|
+
default:
|
|
62
|
+
return input;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* @ru Декомпрессирует буфер, последовательно применяя все кодировки из Content-Encoding.
|
|
67
|
+
* @en Decompresses a buffer by sequentially applying all encodings from Content-Encoding.
|
|
68
|
+
* @param body - Compressed buffer (Uint8Array).
|
|
69
|
+
* @param encoding - Content-Encoding header value (e.g., 'gzip, deflate').
|
|
70
|
+
* @returns Decompressed buffer with a no-op dump method.
|
|
71
|
+
*/
|
|
72
|
+
export function decompressBuffer(body, encoding) {
|
|
73
|
+
let current = body;
|
|
74
|
+
for (const enc of parseEncodings(encoding)) {
|
|
75
|
+
current = decompressOnce(current, enc);
|
|
76
|
+
}
|
|
77
|
+
return attachNoopDump(current);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* @ru Создаёт декомпрессирующий поток для тела ответа, поддерживая цепочку кодировок. Использует DecompressionStream (если доступен) или Node.js zlib.
|
|
81
|
+
* @en Creates a decompressing stream for the response body, supporting chained encodings. Uses DecompressionStream (if available) or Node.js zlib.
|
|
82
|
+
* @param body - Source compressed stream.
|
|
83
|
+
* @param encoding - Content-Encoding header value.
|
|
84
|
+
* @returns Transformed stream with a dump method that cancels the stream.
|
|
85
|
+
*/
|
|
86
|
+
export function createDecompressStream(body, encoding) {
|
|
87
|
+
let current = body;
|
|
88
|
+
for (const enc of parseEncodings(encoding)) {
|
|
89
|
+
if (enc === "gzip" || enc === "x-gzip") {
|
|
90
|
+
if (typeof DecompressionStream !== "undefined") {
|
|
91
|
+
current = current.pipeThrough(new DecompressionStream("gzip"));
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const nodeReadable = Readable.fromWeb(current);
|
|
95
|
+
const decompressed = nodeReadable.pipe(createGunzip());
|
|
96
|
+
current = Readable.toWeb(decompressed);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (enc === "deflate") {
|
|
100
|
+
if (typeof DecompressionStream !== "undefined") {
|
|
101
|
+
current = current.pipeThrough(new DecompressionStream("deflate"));
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const nodeReadable = Readable.fromWeb(current);
|
|
105
|
+
const decompressed = nodeReadable.pipe(createInflate());
|
|
106
|
+
current = Readable.toWeb(decompressed);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (enc === "br") {
|
|
110
|
+
const nodeReadable = Readable.fromWeb(current);
|
|
111
|
+
const decompressed = nodeReadable.pipe(createBrotliDecompress());
|
|
112
|
+
current = Readable.toWeb(decompressed);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return attachStreamDump(current);
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=decompress.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decompress.js","sourceRoot":"","sources":["../../src/utils/decompress.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,YAAY,EACZ,aAAa,EACb,UAAU,EACV,WAAW,GACZ,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAevC;;;;;GAKG;AACH,SAAS,cAAc,CAAC,QAAgB;IACtC,OAAO,QAAQ;SACZ,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;SACxC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,KAAK,UAAU,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;GAKG;AACH,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AAC,KAAK,CACtB,YAAY,CAC4B,CAAC;QAC7C,CAAC;IACH,CAAC;IAED,OAAO,gBAAgB,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC"}
|
package/utils/normalize.d.ts
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
import type { Method, RequestBodyData } from "@hyperttp/types";
|
|
2
2
|
export type NormalizedBody = string | Uint8Array | ArrayBuffer | FormData | URLSearchParams | ReadableStream | Blob | null | undefined;
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* @ru Нормализует метод HTTP: приводит к верхнему регистру, использует кэш для часто встречающихся методов.
|
|
5
|
+
* @en Normalizes an HTTP method: converts to uppercase, uses cache for common methods.
|
|
6
|
+
* @param method - Raw method string (e.g., 'get', 'POST').
|
|
7
|
+
* @returns Normalized uppercase method.
|
|
8
|
+
*/
|
|
4
9
|
export declare function normalizeMethod(method: string): Method;
|
|
10
|
+
/**
|
|
11
|
+
* @ru Извлекает URL из объекта запроса или строки. Поддерживает поля url, _url, или комбинацию scheme/host/path.
|
|
12
|
+
* @en Extracts a URL from a request object or string. Supports url, _url fields, or scheme/host/path combination.
|
|
13
|
+
* @param req - Request object or URL string.
|
|
14
|
+
* @returns Normalized URL string.
|
|
15
|
+
* @throws If URL cannot be resolved.
|
|
16
|
+
*/
|
|
17
|
+
export declare function normalizeUrl(req: any): string;
|
|
18
|
+
/**
|
|
19
|
+
* @ru Нормализует заголовки из различных форматов (массив, объект) в единый объект с правильной обработкой множественных значений (cookie, set-cookie).
|
|
20
|
+
* @en Normalizes headers from various formats (array, object) into a single object with proper handling of multi-value headers (cookie, set-cookie).
|
|
21
|
+
* @param headers - Raw headers in array or object format.
|
|
22
|
+
* @returns Normalized headers object where values are strings or arrays of strings (for set-cookie).
|
|
23
|
+
*/
|
|
24
|
+
export declare function normalizeHeaders(headers: unknown): Record<string, string | string[]>;
|
|
25
|
+
/**
|
|
26
|
+
* @ru Нормализует тело запроса: для методов GET и HEAD тело всегда undefined, для остальных возвращает переданное тело.
|
|
27
|
+
* @en Normalizes request body: for GET and HEAD methods body is always undefined, for others returns the provided body.
|
|
28
|
+
* @param method - HTTP method.
|
|
29
|
+
* @param body - Raw request body.
|
|
30
|
+
* @returns Normalized body or undefined.
|
|
31
|
+
*/
|
|
5
32
|
export declare function normalizeBody(method: Method, body: RequestBodyData | undefined): RequestBodyData | undefined;
|
|
6
33
|
//# sourceMappingURL=normalize.d.ts.map
|
package/utils/normalize.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAE/D,MAAM,MAAM,cAAc,GACtB,MAAM,GACN,UAAU,GACV,WAAW,GACX,QAAQ,GACR,eAAe,GACf,cAAc,GACd,IAAI,GACJ,IAAI,GACJ,SAAS,CAAC;AA+
|
|
1
|
+
{"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAE/D,MAAM,MAAM,cAAc,GACtB,MAAM,GACN,UAAU,GACV,WAAW,GACX,QAAQ,GACR,eAAe,GACf,cAAc,GACd,IAAI,GACJ,IAAI,GACJ,SAAS,CAAC;AA+Cd;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAItD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,CAY7C;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,OAAO,GACf,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CA+HnC;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,eAAe,GAAG,SAAS,GAChC,eAAe,GAAG,SAAS,CAK7B"}
|
package/utils/normalize.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @ru Множество заголовков, которые должны иметь только одно значение (не объединяются при повторении).
|
|
3
|
+
* @en Set of headers that should have only a single value (not merged when repeated).
|
|
4
|
+
*/
|
|
5
|
+
const SINGLE_VALUE_HEADERS = Object.create(null);
|
|
6
|
+
const svh = [
|
|
2
7
|
"content-type",
|
|
3
8
|
"content-length",
|
|
4
9
|
"content-encoding",
|
|
@@ -12,83 +17,190 @@ const SINGLE_VALUE_HEADERS = new Set([
|
|
|
12
17
|
"location",
|
|
13
18
|
"etag",
|
|
14
19
|
"last-modified",
|
|
15
|
-
]
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
|
|
20
|
+
];
|
|
21
|
+
for (let i = 0; i < svh.length; i++) {
|
|
22
|
+
SINGLE_VALUE_HEADERS[svh[i]] = true;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* @ru Кэш нормализованных методов HTTP для быстрого доступа.
|
|
26
|
+
* @en Cache of normalized HTTP methods for fast lookup.
|
|
27
|
+
*/
|
|
28
|
+
const METHOD_CACHE = {
|
|
29
|
+
get: "GET",
|
|
30
|
+
GET: "GET",
|
|
31
|
+
post: "POST",
|
|
32
|
+
POST: "POST",
|
|
33
|
+
put: "PUT",
|
|
34
|
+
PUT: "PUT",
|
|
35
|
+
delete: "DELETE",
|
|
36
|
+
DELETE: "DELETE",
|
|
37
|
+
patch: "PATCH",
|
|
38
|
+
PATCH: "PATCH",
|
|
39
|
+
head: "HEAD",
|
|
40
|
+
HEAD: "HEAD",
|
|
41
|
+
options: "OPTIONS",
|
|
42
|
+
OPTIONS: "OPTIONS",
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* @ru Нормализует метод HTTP: приводит к верхнему регистру, использует кэш для часто встречающихся методов.
|
|
46
|
+
* @en Normalizes an HTTP method: converts to uppercase, uses cache for common methods.
|
|
47
|
+
* @param method - Raw method string (e.g., 'get', 'POST').
|
|
48
|
+
* @returns Normalized uppercase method.
|
|
49
|
+
*/
|
|
50
|
+
export function normalizeMethod(method) {
|
|
51
|
+
const cached = METHOD_CACHE[method];
|
|
52
|
+
if (cached !== undefined)
|
|
53
|
+
return cached;
|
|
54
|
+
return method.toUpperCase();
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* @ru Извлекает URL из объекта запроса или строки. Поддерживает поля url, _url, или комбинацию scheme/host/path.
|
|
58
|
+
* @en Extracts a URL from a request object or string. Supports url, _url fields, or scheme/host/path combination.
|
|
59
|
+
* @param req - Request object or URL string.
|
|
60
|
+
* @returns Normalized URL string.
|
|
61
|
+
* @throws If URL cannot be resolved.
|
|
62
|
+
*/
|
|
63
|
+
export function normalizeUrl(req) {
|
|
64
|
+
if (typeof req === "string")
|
|
65
|
+
return req;
|
|
66
|
+
if (req.url)
|
|
67
|
+
return typeof req.url === "string" ? req.url : String(req.url);
|
|
68
|
+
if (req._url)
|
|
69
|
+
return typeof req._url === "string" ? req._url : String(req._url);
|
|
70
|
+
if (req.scheme && req.host && req.path) {
|
|
71
|
+
return `${req.scheme}://${req.host}${req.path}`;
|
|
72
|
+
}
|
|
73
|
+
throw new Error("URL missing in request");
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* @ru Нормализует заголовки из различных форматов (массив, объект) в единый объект с правильной обработкой множественных значений (cookie, set-cookie).
|
|
77
|
+
* @en Normalizes headers from various formats (array, object) into a single object with proper handling of multi-value headers (cookie, set-cookie).
|
|
78
|
+
* @param headers - Raw headers in array or object format.
|
|
79
|
+
* @returns Normalized headers object where values are strings or arrays of strings (for set-cookie).
|
|
80
|
+
*/
|
|
28
81
|
export function normalizeHeaders(headers) {
|
|
29
82
|
const out = Object.create(null);
|
|
30
|
-
if (!headers)
|
|
83
|
+
if (!headers || typeof headers !== "object")
|
|
31
84
|
return out;
|
|
32
|
-
const appendHeader = (key, rawValue) => {
|
|
33
|
-
const lower = key.toLowerCase();
|
|
34
|
-
if (!lower)
|
|
35
|
-
return;
|
|
36
|
-
if (rawValue === undefined || rawValue === null)
|
|
37
|
-
return;
|
|
38
|
-
const value = typeof rawValue === "string" ? rawValue : String(rawValue);
|
|
39
|
-
if (SINGLE_VALUE_HEADERS.has(lower)) {
|
|
40
|
-
out[lower] = value;
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
const existing = out[lower];
|
|
44
|
-
if (existing === undefined) {
|
|
45
|
-
out[lower] = value;
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
if (lower === "cookie" || lower === "cookie2") {
|
|
49
|
-
out[lower] = `${existing}; ${value}`;
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
if (lower === "set-cookie") {
|
|
53
|
-
out[lower] = `${existing}\n${value}`;
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
if (MULTI_VALUE_HEADERS.has(lower)) {
|
|
57
|
-
out[lower] = `${existing}, ${value}`;
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
out[lower] = value;
|
|
61
|
-
};
|
|
62
85
|
if (Array.isArray(headers)) {
|
|
63
86
|
for (let i = 0; i < headers.length; i += 2) {
|
|
64
87
|
const key = headers[i];
|
|
65
|
-
const value = headers[i + 1];
|
|
66
88
|
if (typeof key !== "string" || !key)
|
|
67
89
|
continue;
|
|
68
|
-
|
|
90
|
+
const rawValue = headers[i + 1];
|
|
91
|
+
if (rawValue === undefined || rawValue === null)
|
|
92
|
+
continue;
|
|
93
|
+
const lower = key.toLowerCase();
|
|
94
|
+
const value = typeof rawValue === "string" ? rawValue : String(rawValue);
|
|
95
|
+
if (SINGLE_VALUE_HEADERS[lower] !== undefined) {
|
|
96
|
+
out[lower] = value;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const existing = out[lower];
|
|
100
|
+
if (existing === undefined) {
|
|
101
|
+
out[lower] = value;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (lower === "set-cookie") {
|
|
105
|
+
if (Array.isArray(existing)) {
|
|
106
|
+
existing.push(value);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
out[lower] = [existing, value];
|
|
110
|
+
}
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (lower === "cookie" || lower === "cookie2") {
|
|
114
|
+
out[lower] = `${existing}; ${value}`;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
out[lower] = Array.isArray(existing)
|
|
118
|
+
? `${existing.join(", ")}, ${value}`
|
|
119
|
+
: `${existing}, ${value}`;
|
|
69
120
|
}
|
|
70
121
|
return out;
|
|
71
122
|
}
|
|
72
123
|
const headerObj = headers;
|
|
73
|
-
for (const
|
|
74
|
-
if (
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
124
|
+
for (const key in headerObj) {
|
|
125
|
+
if (Object.prototype.hasOwnProperty.call(headerObj, key)) {
|
|
126
|
+
const val = headerObj[key];
|
|
127
|
+
if (val === undefined || val === null)
|
|
128
|
+
continue;
|
|
129
|
+
const lower = key.toLowerCase();
|
|
130
|
+
if (Array.isArray(val)) {
|
|
131
|
+
for (let i = 0; i < val.length; i++) {
|
|
132
|
+
const rawValue = val[i];
|
|
133
|
+
if (rawValue === undefined || rawValue === null)
|
|
134
|
+
continue;
|
|
135
|
+
const value = typeof rawValue === "string" ? rawValue : String(rawValue);
|
|
136
|
+
if (SINGLE_VALUE_HEADERS[lower] !== undefined) {
|
|
137
|
+
out[lower] = value;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const existing = out[lower];
|
|
141
|
+
if (existing === undefined) {
|
|
142
|
+
out[lower] = value;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (lower === "set-cookie") {
|
|
146
|
+
if (Array.isArray(existing)) {
|
|
147
|
+
existing.push(value);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
out[lower] = [existing, value];
|
|
151
|
+
}
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (lower === "cookie" || lower === "cookie2") {
|
|
155
|
+
out[lower] = `${existing}; ${value}`;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
out[lower] = Array.isArray(existing)
|
|
159
|
+
? `${existing.join(", ")}, ${value}`
|
|
160
|
+
: `${existing}, ${value}`;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
const value = typeof val === "string" ? val : String(val);
|
|
165
|
+
if (SINGLE_VALUE_HEADERS[lower] !== undefined) {
|
|
166
|
+
out[lower] = value;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const existing = out[lower];
|
|
170
|
+
if (existing === undefined) {
|
|
171
|
+
out[lower] = value;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (lower === "set-cookie") {
|
|
175
|
+
if (Array.isArray(existing)) {
|
|
176
|
+
existing.push(value);
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
out[lower] = [existing, value];
|
|
180
|
+
}
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (lower === "cookie" || lower === "cookie2") {
|
|
184
|
+
out[lower] = `${existing}; ${value}`;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
out[lower] = Array.isArray(existing)
|
|
188
|
+
? `${existing.join(", ")}, ${value}`
|
|
189
|
+
: `${existing}, ${value}`;
|
|
190
|
+
}
|
|
82
191
|
}
|
|
83
192
|
}
|
|
84
193
|
return out;
|
|
85
194
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
195
|
+
/**
|
|
196
|
+
* @ru Нормализует тело запроса: для методов GET и HEAD тело всегда undefined, для остальных возвращает переданное тело.
|
|
197
|
+
* @en Normalizes request body: for GET and HEAD methods body is always undefined, for others returns the provided body.
|
|
198
|
+
* @param method - HTTP method.
|
|
199
|
+
* @param body - Raw request body.
|
|
200
|
+
* @returns Normalized body or undefined.
|
|
201
|
+
*/
|
|
89
202
|
export function normalizeBody(method, body) {
|
|
90
|
-
|
|
91
|
-
if (upper === "GET" || upper === "HEAD") {
|
|
203
|
+
if (method === "GET" || method === "HEAD") {
|
|
92
204
|
return undefined;
|
|
93
205
|
}
|
|
94
206
|
return body ?? undefined;
|
package/utils/normalize.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAaA,MAAM,oBAAoB,
|
|
1
|
+
{"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAaA;;;GAGG;AACH,MAAM,oBAAoB,GAA4B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC1E,MAAM,GAAG,GAAG;IACV,cAAc;IACd,gBAAgB;IAChB,kBAAkB;IAClB,qBAAqB;IACrB,MAAM;IACN,eAAe;IACf,qBAAqB;IACrB,YAAY;IACZ,SAAS;IACT,QAAQ;IACR,UAAU;IACV,MAAM;IACN,eAAe;CAChB,CAAC;AACF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;IACpC,oBAAoB,CAAC,GAAG,CAAC,CAAC,CAAE,CAAC,GAAG,IAAI,CAAC;AACvC,CAAC;AAED;;;GAGG;AACH,MAAM,YAAY,GAA2B;IAC3C,GAAG,EAAE,KAAK;IACV,GAAG,EAAE,KAAK;IACV,IAAI,EAA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,MAAM,KAAK,MAAM,EAAE,CAAC;QAC1C,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,IAAI,IAAI,SAAS,CAAC;AAC3B,CAAC"}
|
package/utils/pipeline.d.ts
CHANGED
|
@@ -1,42 +1,83 @@
|
|
|
1
|
-
import type { HyperPlugin, PluginContext, InternalRequest, HttpResponse, HyperttpError, HttpClientOptions } from "@hyperttp/types";
|
|
1
|
+
import type { HyperPlugin, PluginContext, InternalRequest, HttpResponse, HyperttpError, HttpClientOptions, TransportResponse } from "@hyperttp/types";
|
|
2
2
|
/**
|
|
3
3
|
* @ru Структура записи хука с метаданными для оптимизации и сортировки.
|
|
4
4
|
* @en Hook record structure with metadata for optimization and sorting.
|
|
5
5
|
*/
|
|
6
6
|
export interface HookRecord<T> {
|
|
7
|
+
/** @ru Уникальное имя хука. @en Unique hook name. */
|
|
7
8
|
readonly name: string;
|
|
9
|
+
/** @ru Приоритет выполнения (выше значение — раньше выполнение). @en Execution priority (higher value runs earlier). */
|
|
8
10
|
readonly priority: number;
|
|
11
|
+
/** @ru Функция-обработчик. @en Handler function. */
|
|
9
12
|
readonly run: T;
|
|
10
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* @ru Контейнер конвейеров для различных фаз обработки запроса/ответа.
|
|
16
|
+
* @en Pipeline container for different request/response processing phases.
|
|
17
|
+
*/
|
|
11
18
|
export interface PipelineContainer {
|
|
19
|
+
/** @ru Хуки, выполняемые перед отправкой запроса. @en Hooks executed before sending the request. */
|
|
12
20
|
readonly request: HookRecord<Required<HyperPlugin>["onRequest"]>[];
|
|
21
|
+
/** @ru Хуки, обрабатывающие сырые данные транспорта. @en Hooks processing raw transport data. */
|
|
22
|
+
readonly responseData: HookRecord<Required<HyperPlugin>["onResponseData"]>[];
|
|
23
|
+
/** @ru Хуки, мутирующие ответ (последовательное выполнение). @en Hooks that mutate the response (sequential execution). */
|
|
13
24
|
readonly responseMutators: HookRecord<Required<HyperPlugin>["onResponse"]>[];
|
|
25
|
+
/** @ru Хуки с побочными эффектами (выполняются в фоне). @en Side-effect hooks (executed in the background). */
|
|
14
26
|
readonly responseSideEffects: HookRecord<Required<HyperPlugin>["onResponse"]>[];
|
|
27
|
+
/** @ru Хуки для перехвата ошибок. @en Error interception hooks. */
|
|
15
28
|
readonly error: HookRecord<Required<HyperPlugin>["onError"]>[];
|
|
16
29
|
}
|
|
17
30
|
/**
|
|
18
|
-
* @ru
|
|
31
|
+
* @ru Создаёт пустой контейнер для конвейеров плагинов.
|
|
19
32
|
* @en Creates an empty container for plugin pipelines.
|
|
33
|
+
* @returns An empty pipeline container.
|
|
20
34
|
*/
|
|
21
35
|
export declare function createPipelines(): PipelineContainer;
|
|
22
36
|
/**
|
|
23
37
|
* @ru Вставляет хук в массив с сохранением сортировки по убыванию приоритета (деревья поиска тут избыточны).
|
|
24
38
|
* @en Inserts a hook into the array maintaining descending priority order.
|
|
39
|
+
* @param list - Target array to insert into.
|
|
40
|
+
* @param hook - Hook record to insert.
|
|
25
41
|
*/
|
|
26
42
|
export declare function insertHookSorted<T>(list: HookRecord<T>[], hook: HookRecord<T>): void;
|
|
27
43
|
/**
|
|
28
|
-
* @ru Выполняет конвейер пред-запроса. Поддерживает short-circuit (ранний возврат ответа).
|
|
29
|
-
* @en Executes the pre-request pipeline. Supports short-circuiting.
|
|
44
|
+
* @ru Выполняет конвейер пред-запроса. Поддерживает short-circuit (ранний возврат ответа). Использует Fast-Path для синхронных хуков без аллокации микротасок.
|
|
45
|
+
* @en Executes the pre-request pipeline. Supports short-circuiting with fast-path for sync hooks.
|
|
46
|
+
* @param hooks - Array of request hooks.
|
|
47
|
+
* @param req - Internal request object.
|
|
48
|
+
* @param ctx - Plugin context.
|
|
49
|
+
* @returns A response if short-circuited, null otherwise, or a promise.
|
|
50
|
+
*/
|
|
51
|
+
export declare function executeRequestPipeline(hooks: readonly HookRecord<Required<HyperPlugin>["onRequest"]>[], req: InternalRequest, ctx: PluginContext): Promise<HttpResponse<unknown> | null> | HttpResponse<unknown> | null | void;
|
|
52
|
+
/**
|
|
53
|
+
* @ru Выполняет низкоуровневый конвейер трансформации сырых данных транспорта (фаза DATA). Если хук возвращает измененный TransportResponse, он передается дальше по цепочке.
|
|
54
|
+
* @en Executes low-level transport data transformation pipeline (DATA phase). If a hook returns a modified TransportResponse, it is passed along the chain.
|
|
55
|
+
* @param hooks - Array of response data hooks.
|
|
56
|
+
* @param res - Current transport response.
|
|
57
|
+
* @param ctx - Plugin context.
|
|
58
|
+
* @returns The (possibly transformed) transport response, either directly or wrapped in a promise.
|
|
30
59
|
*/
|
|
31
|
-
export declare function
|
|
60
|
+
export declare function executeResponseDataPipeline(hooks: readonly HookRecord<Required<HyperPlugin>["onResponseData"]>[], res: TransportResponse, ctx: PluginContext): Promise<TransportResponse> | TransportResponse;
|
|
32
61
|
/**
|
|
33
|
-
* @ru Выполняет конвейер пост-ответа. Разделен на мутаторы (последовательно) и сайд-эффекты (в фоне).
|
|
34
|
-
* @en Executes the post-response pipeline. Split into mutators (sequential) and side-effects (background).
|
|
62
|
+
* @ru Выполняет конвейер пост-ответа. Разделен на мутаторы (последовательно) и сайд-эффекты (в фоне). Оптимизирован для минимизации выделения памяти под замыкания логгера.
|
|
63
|
+
* @en Executes the post-response pipeline. Split into mutators (sequential) and side-effects (background). Optimized to minimize memory allocations for logger closures.
|
|
64
|
+
* @param mutators - Hooks that mutate the response (executed sequentially).
|
|
65
|
+
* @param sideEffects - Hooks that run in background, errors are logged but do not break the main flow.
|
|
66
|
+
* @param res - HTTP response object.
|
|
67
|
+
* @param req - Internal request object.
|
|
68
|
+
* @param ctx - Plugin context.
|
|
69
|
+
* @param logger - Optional logger for side-effect errors.
|
|
70
|
+
* @returns A promise if any mutator returns a promise, otherwise void.
|
|
35
71
|
*/
|
|
36
|
-
export declare function executeResponsePipeline(mutators: readonly HookRecord<Required<HyperPlugin>["onResponse"]>[], sideEffects: readonly HookRecord<Required<HyperPlugin>["onResponse"]>[], res: HttpResponse<unknown>, req: InternalRequest, ctx: PluginContext, logger?: HttpClientOptions["logger"]): Promise<void
|
|
72
|
+
export declare function executeResponsePipeline(mutators: readonly HookRecord<Required<HyperPlugin>["onResponse"]>[], sideEffects: readonly HookRecord<Required<HyperPlugin>["onResponse"]>[], res: HttpResponse<unknown>, req: InternalRequest, ctx: PluginContext, logger?: HttpClientOptions["logger"]): Promise<void> | void;
|
|
37
73
|
/**
|
|
38
74
|
* @ru Выполняет конвейер перехвата ошибок. Первый вернувший HttpResponse плагин прерывает панику.
|
|
39
|
-
* @en Executes the error interception pipeline.
|
|
75
|
+
* @en Executes the error interception pipeline. The first plugin that returns HttpResponse stops the panic.
|
|
76
|
+
* @param hooks - Array of error hooks.
|
|
77
|
+
* @param error - The error that occurred.
|
|
78
|
+
* @param req - Internal request object.
|
|
79
|
+
* @param ctx - Plugin context.
|
|
80
|
+
* @returns A response if recovered, null otherwise, or a promise.
|
|
40
81
|
*/
|
|
41
|
-
export declare function executeErrorPipeline(hooks: readonly HookRecord<Required<HyperPlugin>["onError"]>[], error: HyperttpError, req: InternalRequest, ctx: PluginContext): Promise<HttpResponse<unknown> | null
|
|
82
|
+
export declare function executeErrorPipeline(hooks: readonly HookRecord<Required<HyperPlugin>["onError"]>[], error: HyperttpError, req: InternalRequest, ctx: PluginContext): Promise<HttpResponse<unknown> | null> | HttpResponse<unknown> | null | void;
|
|
42
83
|
//# sourceMappingURL=pipeline.d.ts.map
|
package/utils/pipeline.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline.d.ts","sourceRoot":"","sources":["../../src/utils/pipeline.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,aAAa,EACb,eAAe,EACf,YAAY,EACZ,aAAa,EACb,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AAEzB;;;GAGG;AACH,MAAM,WAAW,UAAU,CAAC,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QA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