hyperttp 0.2.6 → 0.3.2

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 (152) hide show
  1. package/Hyperttp/Client/HyperClient.d.ts +30 -0
  2. package/Hyperttp/Client/HyperClient.d.ts.map +1 -0
  3. package/Hyperttp/Client/HyperClient.js +215 -0
  4. package/Hyperttp/Client/HyperClient.js.map +1 -0
  5. package/{dist/Hyperttp → Hyperttp}/Request.d.ts +1 -1
  6. package/{dist/Hyperttp → Hyperttp}/Request.d.ts.map +1 -1
  7. package/{dist/Hyperttp → Hyperttp}/Request.js +2 -7
  8. package/Hyperttp/Request.js.map +1 -0
  9. package/{dist/Hyperttp → Hyperttp}/UrlExtractor.d.ts +1 -1
  10. package/{dist/Hyperttp → Hyperttp}/UrlExtractor.d.ts.map +1 -1
  11. package/{dist/Hyperttp → Hyperttp}/UrlExtractor.js +1 -4
  12. package/Hyperttp/UrlExtractor.js.map +1 -0
  13. package/Hyperttp/Utils/RequestBuilder.d.ts +32 -0
  14. package/Hyperttp/Utils/RequestBuilder.d.ts.map +1 -0
  15. package/Hyperttp/Utils/RequestBuilder.js +129 -0
  16. package/Hyperttp/Utils/RequestBuilder.js.map +1 -0
  17. package/Hyperttp/Utils/index.d.ts +2 -0
  18. package/Hyperttp/Utils/index.d.ts.map +1 -0
  19. package/Hyperttp/Utils/index.js +2 -0
  20. package/Hyperttp/Utils/index.js.map +1 -0
  21. package/Hyperttp/Utils/merge.d.ts +2 -0
  22. package/Hyperttp/Utils/merge.d.ts.map +1 -0
  23. package/Hyperttp/Utils/merge.js +25 -0
  24. package/Hyperttp/Utils/merge.js.map +1 -0
  25. package/Hyperttp/defaultConfig.d.ts +3 -0
  26. package/Hyperttp/defaultConfig.d.ts.map +1 -0
  27. package/Hyperttp/defaultConfig.js +39 -0
  28. package/Hyperttp/defaultConfig.js.map +1 -0
  29. package/Hyperttp/index.d.ts +6 -0
  30. package/Hyperttp/index.d.ts.map +1 -0
  31. package/Hyperttp/index.js +6 -0
  32. package/Hyperttp/index.js.map +1 -0
  33. package/{dist/Types → Types}/http-client.d.ts +2 -6
  34. package/Types/http-client.d.ts.map +1 -0
  35. package/Types/http-client.js +2 -0
  36. package/Types/index.d.ts +3 -0
  37. package/Types/index.d.ts.map +1 -0
  38. package/Types/index.js +3 -0
  39. package/Types/index.js.map +1 -0
  40. package/Types/url-extractor.js +2 -0
  41. package/index.d.ts +13 -0
  42. package/index.d.ts.map +1 -0
  43. package/index.js +12 -0
  44. package/index.js.map +1 -0
  45. package/package.json +26 -11
  46. package/LICENSE +0 -21
  47. package/README.md +0 -195
  48. package/dist/Hyperttp/Core/CacheManager.d.ts +0 -84
  49. package/dist/Hyperttp/Core/CacheManager.d.ts.map +0 -1
  50. package/dist/Hyperttp/Core/CacheManager.js +0 -109
  51. package/dist/Hyperttp/Core/CacheManager.js.map +0 -1
  52. package/dist/Hyperttp/Core/HttpClientImproved.d.ts +0 -149
  53. package/dist/Hyperttp/Core/HttpClientImproved.d.ts.map +0 -1
  54. package/dist/Hyperttp/Core/HttpClientImproved.js +0 -541
  55. package/dist/Hyperttp/Core/HttpClientImproved.js.map +0 -1
  56. package/dist/Hyperttp/Core/InterceptorManager.d.ts +0 -62
  57. package/dist/Hyperttp/Core/InterceptorManager.d.ts.map +0 -1
  58. package/dist/Hyperttp/Core/InterceptorManager.js +0 -64
  59. package/dist/Hyperttp/Core/InterceptorManager.js.map +0 -1
  60. package/dist/Hyperttp/Core/MetricsManager.d.ts +0 -71
  61. package/dist/Hyperttp/Core/MetricsManager.d.ts.map +0 -1
  62. package/dist/Hyperttp/Core/MetricsManager.js +0 -246
  63. package/dist/Hyperttp/Core/MetricsManager.js.map +0 -1
  64. package/dist/Hyperttp/Core/QueueManager.d.ts +0 -16
  65. package/dist/Hyperttp/Core/QueueManager.d.ts.map +0 -1
  66. package/dist/Hyperttp/Core/QueueManager.js +0 -75
  67. package/dist/Hyperttp/Core/QueueManager.js.map +0 -1
  68. package/dist/Hyperttp/Core/RateLimiter.d.ts +0 -63
  69. package/dist/Hyperttp/Core/RateLimiter.d.ts.map +0 -1
  70. package/dist/Hyperttp/Core/RateLimiter.js +0 -170
  71. package/dist/Hyperttp/Core/RateLimiter.js.map +0 -1
  72. package/dist/Hyperttp/Core/RequestBuilder.d.ts +0 -83
  73. package/dist/Hyperttp/Core/RequestBuilder.d.ts.map +0 -1
  74. package/dist/Hyperttp/Core/RequestBuilder.js +0 -169
  75. package/dist/Hyperttp/Core/RequestBuilder.js.map +0 -1
  76. package/dist/Hyperttp/Core/RequestExecutor.d.ts +0 -31
  77. package/dist/Hyperttp/Core/RequestExecutor.d.ts.map +0 -1
  78. package/dist/Hyperttp/Core/RequestExecutor.js +0 -167
  79. package/dist/Hyperttp/Core/RequestExecutor.js.map +0 -1
  80. package/dist/Hyperttp/Core/RequestProfiler.d.ts +0 -10
  81. package/dist/Hyperttp/Core/RequestProfiler.d.ts.map +0 -1
  82. package/dist/Hyperttp/Core/RequestProfiler.js +0 -55
  83. package/dist/Hyperttp/Core/RequestProfiler.js.map +0 -1
  84. package/dist/Hyperttp/Core/ResponseConverter.d.ts +0 -23
  85. package/dist/Hyperttp/Core/ResponseConverter.d.ts.map +0 -1
  86. package/dist/Hyperttp/Core/ResponseConverter.js +0 -369
  87. package/dist/Hyperttp/Core/ResponseConverter.js.map +0 -1
  88. package/dist/Hyperttp/Core/index.d.ts +0 -27
  89. package/dist/Hyperttp/Core/index.d.ts.map +0 -1
  90. package/dist/Hyperttp/Core/index.js +0 -56
  91. package/dist/Hyperttp/Core/index.js.map +0 -1
  92. package/dist/Hyperttp/Request.js.map +0 -1
  93. package/dist/Hyperttp/UrlExtractor.js.map +0 -1
  94. package/dist/Hyperttp/index.d.ts +0 -5
  95. package/dist/Hyperttp/index.d.ts.map +0 -1
  96. package/dist/Hyperttp/index.js +0 -24
  97. package/dist/Hyperttp/index.js.map +0 -1
  98. package/dist/Types/cache.d.ts +0 -10
  99. package/dist/Types/cache.d.ts.map +0 -1
  100. package/dist/Types/cache.js +0 -3
  101. package/dist/Types/cache.js.map +0 -1
  102. package/dist/Types/errors.d.ts +0 -15
  103. package/dist/Types/errors.d.ts.map +0 -1
  104. package/dist/Types/errors.js +0 -34
  105. package/dist/Types/errors.js.map +0 -1
  106. package/dist/Types/http-client.d.ts.map +0 -1
  107. package/dist/Types/http-client.js +0 -3
  108. package/dist/Types/http.d.ts +0 -5
  109. package/dist/Types/http.d.ts.map +0 -1
  110. package/dist/Types/http.js +0 -3
  111. package/dist/Types/http.js.map +0 -1
  112. package/dist/Types/index.d.ts +0 -13
  113. package/dist/Types/index.d.ts.map +0 -1
  114. package/dist/Types/index.js +0 -29
  115. package/dist/Types/index.js.map +0 -1
  116. package/dist/Types/interceptors.d.ts +0 -13
  117. package/dist/Types/interceptors.d.ts.map +0 -1
  118. package/dist/Types/interceptors.js +0 -3
  119. package/dist/Types/interceptors.js.map +0 -1
  120. package/dist/Types/metrics.d.ts +0 -90
  121. package/dist/Types/metrics.d.ts.map +0 -1
  122. package/dist/Types/metrics.js +0 -3
  123. package/dist/Types/metrics.js.map +0 -1
  124. package/dist/Types/options.d.ts +0 -233
  125. package/dist/Types/options.d.ts.map +0 -1
  126. package/dist/Types/options.js +0 -3
  127. package/dist/Types/options.js.map +0 -1
  128. package/dist/Types/queue.d.ts +0 -8
  129. package/dist/Types/queue.d.ts.map +0 -1
  130. package/dist/Types/queue.js +0 -3
  131. package/dist/Types/queue.js.map +0 -1
  132. package/dist/Types/request.d.ts +0 -189
  133. package/dist/Types/request.d.ts.map +0 -1
  134. package/dist/Types/request.js +0 -3
  135. package/dist/Types/request.js.map +0 -1
  136. package/dist/Types/response.d.ts +0 -28
  137. package/dist/Types/response.d.ts.map +0 -1
  138. package/dist/Types/response.js +0 -3
  139. package/dist/Types/response.js.map +0 -1
  140. package/dist/Types/stream.d.ts +0 -39
  141. package/dist/Types/stream.d.ts.map +0 -1
  142. package/dist/Types/stream.js +0 -3
  143. package/dist/Types/stream.js.map +0 -1
  144. package/dist/Types/url-extractor.js +0 -3
  145. package/dist/index.d.ts +0 -3
  146. package/dist/index.d.ts.map +0 -1
  147. package/dist/index.js +0 -18
  148. package/dist/index.js.map +0 -1
  149. /package/{dist/Types → Types}/http-client.js.map +0 -0
  150. /package/{dist/Types → Types}/url-extractor.d.ts +0 -0
  151. /package/{dist/Types → Types}/url-extractor.d.ts.map +0 -0
  152. /package/{dist/Types → Types}/url-extractor.js.map +0 -0
@@ -1,149 +0,0 @@
1
- import { RequestBuilder } from "./RequestBuilder.js";
2
- import { HttpClientInterface } from "../../Types/http-client.js";
3
- import { HttpClientOptions } from "../../Types/options.js";
4
- import { ResponseType } from "../../Types/http.js";
5
- import { RequestInterface } from "../../Types/request.js";
6
- import { RequestMetrics } from "../../Types/metrics.js";
7
- import { StreamResponse } from "../../Types/stream.js";
8
- import { Readable } from "node:stream";
9
- /**
10
- * @class HttpClientImproved
11
- * @en High-performance HTTP client with built-in caching, queuing, rate limiting, and metrics.
12
- * @ru Высокопроизводительный HTTP-клиент со встроенным кэшированием, очередями, лимитами и метриками.
13
- */
14
- export default class HttpClientImproved implements HttpClientInterface {
15
- private agent;
16
- readonly config: HttpClientOptions;
17
- private cache?;
18
- private queue?;
19
- private limiter?;
20
- private metricsManager;
21
- private interceptors;
22
- private executor;
23
- private converter;
24
- private inflight;
25
- private defaultHeaders;
26
- private readonly cacheEnabled;
27
- private readonly queueEnabled;
28
- private readonly limiterEnabled;
29
- private readonly metricsEnabled;
30
- private readonly verboseEnabled;
31
- constructor(config?: HttpClientOptions);
32
- /**
33
- * @en Performs an HTTP GET request.
34
- * @ru Выполняет HTTP GET запрос.
35
- * @param req Request URL or Request object
36
- * @param responseType Expected response format
37
- */
38
- get<T = any>(req: RequestInterface | string, responseType?: ResponseType): Promise<T>;
39
- /**
40
- * @en Performs an HTTP POST request.
41
- * @ru Выполняет HTTP POST запрос.
42
- * @param req Request URL or Request object
43
- * @param body Request body data
44
- * @param responseType Expected response format
45
- */
46
- post<T = any>(req: RequestInterface | string, body?: any, responseType?: ResponseType): Promise<T>;
47
- /**
48
- * @en Performs an HTTP PUT request.
49
- * @ru Выполняет HTTP PUT запрос.
50
- */
51
- put<T = any>(req: RequestInterface | string, body?: any, responseType?: ResponseType): Promise<T>;
52
- /**
53
- * @en Performs an HTTP DELETE request.
54
- * @ru Выполняет HTTP DELETE запрос.
55
- */
56
- delete<T = any>(req: RequestInterface | string, responseType?: ResponseType): Promise<T>;
57
- /**
58
- * @en Performs an HTTP PATCH request.
59
- * @ru Выполняет HTTP PATCH запрос.
60
- */
61
- patch<T = any>(req: RequestInterface | string, body?: any, responseType?: ResponseType): Promise<T>;
62
- /**
63
- * @en Performs an HTTP OPTIONS request.
64
- * @ru Выполняет HTTP OPTIONS запрос.
65
- */
66
- options<T = any>(req: RequestInterface | string, body?: any, responseType?: ResponseType): Promise<T>;
67
- /**
68
- * @en Performs an HTTP HEAD request.
69
- * @ru Выполняет HTTP HEAD запрос.
70
- */
71
- head(req: RequestInterface | string): Promise<{
72
- status: number;
73
- headers: Record<string, any>;
74
- }>;
75
- /**
76
- * @en Creates a new HttpClient instance with merged configuration.
77
- * @ru Создаёт новый экземпляр HttpClient с объединённой конфигурацией.
78
- *
79
- * @param options Partial configuration to override current settings
80
- * @returns New HttpClientImproved instance
81
- */
82
- extend(options: Partial<HttpClientOptions>): HttpClientImproved;
83
- /**
84
- * @en Alias for extend(). Creates a new configured client instance.
85
- * @ru Алиас для extend(). Создаёт новый настроенный экземпляр клиента.
86
- *
87
- * @param options Partial configuration overrides
88
- * @returns New HttpClientImproved instance
89
- */
90
- create(options: Partial<HttpClientOptions>): HttpClientImproved;
91
- /**
92
- * @en Executes a request and returns an AsyncIterable stream.
93
- * @ru Выполняет запрос и возвращает итерируемый поток данных.
94
- */
95
- stream(req: RequestInterface | string): Promise<StreamResponse<Readable>>;
96
- /**
97
- * @en Creates a RequestBuilder for a fluent API approach.
98
- * @ru Создает RequestBuilder для использования Fluent API.
99
- * @example client.request('url').get().send();
100
- */
101
- request(url: string): RequestBuilder;
102
- destroy(): Promise<void>;
103
- clearCache(): void;
104
- /**
105
- * @en Clears all collected performance metrics.
106
- * @ru Очищает все собранные метрики производительности.
107
- */
108
- clearMetrics(): void;
109
- /**
110
- * @en Retrieves metrics for a specific URL.
111
- * @ru Получает метрики для конкретного URL.
112
- */
113
- getMetrics(key: string): RequestMetrics | undefined;
114
- /**
115
- * @en Retrieves all stored request metrics.
116
- * @ru Получает список всех сохраненных метрик.
117
- */
118
- getAllMetrics(): RequestMetrics[];
119
- /**
120
- * @en Returns real-time statistics about the client's internal state.
121
- * @ru Возвращает статистику состояния клиента в реальном времени.
122
- * @returns Cache size, active requests, queue state, etc.
123
- */
124
- getStats(): {
125
- cacheSize: number;
126
- inflightRequests: number;
127
- queuedRequests: any;
128
- activeRequests: any;
129
- currentRateLimit: any;
130
- };
131
- warmup(urls: string[], count?: number): Promise<void>;
132
- private mergeOptions;
133
- private normalizeRequest;
134
- private applyDefaulthcoptions;
135
- /**
136
- * @en Core internal method for handling all HTTP requests.
137
- * @ru Основной внутренний метод для обработки всех HTTP-запросов.
138
- * @param method HTTP method (GET, POST, etc.)
139
- * @param req Request object
140
- * @param useCache Whether to use caching for this request
141
- * @param responseType Expected response format
142
- */
143
- private requestInternal;
144
- private prepareRequestData;
145
- private createInitialMetrics;
146
- private recordSuccess;
147
- private recordError;
148
- }
149
- //# sourceMappingURL=HttpClientImproved.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"HttpClientImproved.d.ts","sourceRoot":"","sources":["../../../src/Hyperttp/Core/HttpClientImproved.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAIrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAU,YAAY,EAAE,MAAM,qBAAq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AAI,CAAC;IAsB9B,UAAU,IAAI,IAAI;IAIlB;;;OAGG;IACH,YAAY,IAAI,IAAI;IAIpB;;;OAGG;IACH,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAInD;;;OAGG;IACH,aAAa,IAAI,cAAc,EAAE;IAIjC;;;;OAIG;IACH,QAAQ;;;;;;;IAuBF,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,KAAK,SAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAYvD,OAAO,CAAC,YAAY;IAoBpB,OAAO,CAAC,gBAAgB;IAcxB,OAAO,CAAC,qBAAqB;IAqE7B;;;;;;;OAOG;YACW,eAAe;IAqJ7B,OAAO,CAAC,kBAAkB;IA0C1B,OAAO,CAAC,oBAAoB;IAc5B,OAAO,CAAC,aAAa;IAkBrB,OAAO,CAAC,WAAW;CAiBpB"}
@@ -1,541 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const undici_1 = require("http-cookie-agent/undici");
4
- const CacheManager_js_1 = require("./CacheManager.js");
5
- const QueueManager_js_1 = require("./QueueManager.js");
6
- const RateLimiter_js_1 = require("./RateLimiter.js");
7
- const MetricsManager_js_1 = require("./MetricsManager.js");
8
- const RequestBuilder_js_1 = require("./RequestBuilder.js");
9
- const InterceptorManager_js_1 = require("./InterceptorManager.js");
10
- const RequestExecutor_js_1 = require("./RequestExecutor.js");
11
- const ResponseConverter_js_1 = require("./ResponseConverter.js");
12
- const errors_js_1 = require("../../Types/errors.js");
13
- const isProd = process.env.NODE_ENV === "production";
14
- /**
15
- * @class HttpClientImproved
16
- * @en High-performance HTTP client with built-in caching, queuing, rate limiting, and metrics.
17
- * @ru Высокопроизводительный HTTP-клиент со встроенным кэшированием, очередями, лимитами и метриками.
18
- */
19
- class HttpClientImproved {
20
- agent;
21
- config;
22
- cache;
23
- queue;
24
- limiter;
25
- metricsManager;
26
- interceptors;
27
- executor;
28
- converter;
29
- inflight = new Map();
30
- defaultHeaders = {};
31
- cacheEnabled;
32
- queueEnabled;
33
- limiterEnabled;
34
- metricsEnabled;
35
- verboseEnabled;
36
- constructor(config) {
37
- this.config = this.applyDefaulthcoptions(config);
38
- this.cacheEnabled = !!this.config.cache?.enabled;
39
- this.queueEnabled = !!this.config.queue?.enabled;
40
- this.limiterEnabled = !!this.config.rateLimit?.enabled;
41
- this.metricsEnabled = this.config.metrics?.enabled ?? true;
42
- this.verboseEnabled = !!this.config.verbose && !isProd;
43
- this.metricsManager = new MetricsManager_js_1.MetricsManager({
44
- maxHistory: this.config.metrics?.maxHistory,
45
- });
46
- this.converter = new ResponseConverter_js_1.ResponseConverter({
47
- maxBodySize: this.config.responseConverter?.maxBodySize,
48
- parseHTML: this.config.responseConverter?.parseHTML,
49
- htmlMode: this.config.responseConverter?.htmlMode,
50
- charset: this.config.responseConverter?.charset,
51
- });
52
- this.interceptors = new InterceptorManager_js_1.InterceptorManager();
53
- if (this.cacheEnabled) {
54
- this.cache = new CacheManager_js_1.CacheManager({
55
- cacheTTL: this.config.cache?.ttl,
56
- cacheMaxSize: this.config.cache?.maxSize,
57
- });
58
- }
59
- const concurrency = this.config.network?.maxConcurrent === 0
60
- ? Infinity
61
- : (this.config.network?.maxConcurrent ?? 500);
62
- if (this.queueEnabled) {
63
- this.queue = new QueueManager_js_1.QueueManager(concurrency);
64
- }
65
- if (this.config.rateLimit?.enabled) {
66
- this.limiter = new RateLimiter_js_1.RateLimiter(this.config.rateLimit);
67
- }
68
- this.agent = new undici_1.CookieAgent({
69
- connections: concurrency,
70
- pipelining: this.config.network?.pipelining ?? 10,
71
- keepAliveTimeout: this.config.network?.keepAliveTimeout ?? 30000,
72
- keepAliveMaxTimeout: this.config.network?.keepAliveTimeout ?? 30000,
73
- connect: {
74
- ciphers: "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384",
75
- rejectUnauthorized: this.config.network?.rejectUnauthorized,
76
- },
77
- allowH2: this.config.network?.allowHttp2 ?? true,
78
- });
79
- this.executor = new RequestExecutor_js_1.RequestExecutor(this.agent, this.interceptors, {
80
- timeout: this.config.network?.timeout ?? 30000,
81
- maxRetries: this.config.retry?.maxRetries ?? 3,
82
- followRedirects: this.config.network?.followRedirects ?? true,
83
- maxRedirects: this.config.network?.maxRedirects ?? 5,
84
- retryOptions: {
85
- maxRetries: this.config.retry?.maxRetries ?? 3,
86
- baseDelay: this.config.retry?.baseDelay ?? 1000,
87
- maxDelay: this.config.retry?.maxDelay ?? 10000,
88
- retryStatusCodes: this.config.retry?.retryStatusCodes ?? [
89
- 408, 429, 500, 502, 503, 504,
90
- ],
91
- jitter: this.config.retry?.jitter ?? true,
92
- },
93
- verbose: this.verboseEnabled,
94
- logger: this.config.logger,
95
- });
96
- const useragent = this.config.network?.userAgent
97
- ? this.config.network?.userAgent
98
- : "Hyperttp/2.0";
99
- this.defaultHeaders = {
100
- Accept: "application/json, text/plain, */*",
101
- "Accept-Encoding": "gzip, deflate, br",
102
- "User-Agent": useragent,
103
- };
104
- }
105
- /**
106
- * @en Performs an HTTP GET request.
107
- * @ru Выполняет HTTP GET запрос.
108
- * @param req Request URL or Request object
109
- * @param responseType Expected response format
110
- */
111
- get(req, responseType = "auto") {
112
- const requestObj = this.normalizeRequest(req);
113
- return this.requestInternal("GET", requestObj, true, responseType);
114
- }
115
- /**
116
- * @en Performs an HTTP POST request.
117
- * @ru Выполняет HTTP POST запрос.
118
- * @param req Request URL or Request object
119
- * @param body Request body data
120
- * @param responseType Expected response format
121
- */
122
- post(req, body, responseType = "auto") {
123
- return this.requestInternal("POST", this.normalizeRequest(req, body), false, responseType);
124
- }
125
- /**
126
- * @en Performs an HTTP PUT request.
127
- * @ru Выполняет HTTP PUT запрос.
128
- */
129
- put(req, body, responseType = "auto") {
130
- return this.requestInternal("PUT", this.normalizeRequest(req, body), false, responseType);
131
- }
132
- /**
133
- * @en Performs an HTTP DELETE request.
134
- * @ru Выполняет HTTP DELETE запрос.
135
- */
136
- delete(req, responseType = "auto") {
137
- return this.requestInternal("DELETE", this.normalizeRequest(req), false, responseType);
138
- }
139
- /**
140
- * @en Performs an HTTP PATCH request.
141
- * @ru Выполняет HTTP PATCH запрос.
142
- */
143
- patch(req, body, responseType = "auto") {
144
- return this.requestInternal("PATCH", this.normalizeRequest(req, body), false, responseType);
145
- }
146
- /**
147
- * @en Performs an HTTP OPTIONS request.
148
- * @ru Выполняет HTTP OPTIONS запрос.
149
- */
150
- options(req, body, responseType = "auto") {
151
- return this.requestInternal("OPTIONS", this.normalizeRequest(req, body), false, responseType);
152
- }
153
- /**
154
- * @en Performs an HTTP HEAD request.
155
- * @ru Выполняет HTTP HEAD запрос.
156
- */
157
- async head(req) {
158
- return this.requestInternal("HEAD", this.normalizeRequest(req), false);
159
- }
160
- /**
161
- * @en Creates a new HttpClient instance with merged configuration.
162
- * @ru Создаёт новый экземпляр HttpClient с объединённой конфигурацией.
163
- *
164
- * @param options Partial configuration to override current settings
165
- * @returns New HttpClientImproved instance
166
- */
167
- extend(options) {
168
- return new HttpClientImproved(this.mergeOptions(this.config, options));
169
- }
170
- /**
171
- * @en Alias for extend(). Creates a new configured client instance.
172
- * @ru Алиас для extend(). Создаёт новый настроенный экземпляр клиента.
173
- *
174
- * @param options Partial configuration overrides
175
- * @returns New HttpClientImproved instance
176
- */
177
- create(options) {
178
- return this.extend(options);
179
- }
180
- /**
181
- * @en Executes a request and returns an AsyncIterable stream.
182
- * @ru Выполняет запрос и возвращает итерируемый поток данных.
183
- */
184
- async stream(req) {
185
- const requestObj = this.normalizeRequest(req);
186
- const url = requestObj.getURL();
187
- const { body, headers } = this.prepareRequestData("GET", requestObj);
188
- const controller = new AbortController();
189
- const userSignal = requestObj.getSignal?.();
190
- const signal = userSignal
191
- ? AbortSignal.any([userSignal, controller.signal])
192
- : controller.signal;
193
- const rawResponse = await this.executor.execute("GET", url, headers, body, undefined, signal);
194
- const cleanup = () => {
195
- this.inflight.delete(url);
196
- };
197
- rawResponse.body.once("close", cleanup);
198
- rawResponse.body.once("error", cleanup);
199
- rawResponse.body.once("end", cleanup);
200
- this.inflight.set(url, {
201
- promise: Promise.resolve(undefined),
202
- controller,
203
- });
204
- return {
205
- status: rawResponse.status,
206
- headers: rawResponse.headers,
207
- body: rawResponse.body,
208
- url: rawResponse.url,
209
- };
210
- }
211
- /**
212
- * @en Creates a RequestBuilder for a fluent API approach.
213
- * @ru Создает RequestBuilder для использования Fluent API.
214
- * @example client.request('url').get().send();
215
- */
216
- request(url) {
217
- return new RequestBuilder_js_1.RequestBuilder(url, this);
218
- }
219
- async destroy() {
220
- this.queue?.clear();
221
- this.limiter?.reset();
222
- for (const { controller } of this.inflight.values()) {
223
- controller.abort();
224
- }
225
- this.inflight.clear();
226
- try {
227
- if (typeof this.agent.destroy === "function") {
228
- await this.agent.destroy();
229
- }
230
- else if (typeof this.agent.close === "function") {
231
- await this.agent.close();
232
- }
233
- }
234
- catch {
235
- /* ignore */
236
- }
237
- this.cache?.clear();
238
- }
239
- clearCache() {
240
- this.cache?.clear();
241
- }
242
- /**
243
- * @en Clears all collected performance metrics.
244
- * @ru Очищает все собранные метрики производительности.
245
- */
246
- clearMetrics() {
247
- this.metricsManager.clear();
248
- }
249
- /**
250
- * @en Retrieves metrics for a specific URL.
251
- * @ru Получает метрики для конкретного URL.
252
- */
253
- getMetrics(key) {
254
- return this.metricsManager.get(key);
255
- }
256
- /**
257
- * @en Retrieves all stored request metrics.
258
- * @ru Получает список всех сохраненных метрик.
259
- */
260
- getAllMetrics() {
261
- return Array.from(this.metricsManager.getAll());
262
- }
263
- /**
264
- * @en Returns real-time statistics about the client's internal state.
265
- * @ru Возвращает статистику состояния клиента в реальном времени.
266
- * @returns Cache size, active requests, queue state, etc.
267
- */
268
- getStats() {
269
- return {
270
- cacheSize: this.cache?.size ?? 0,
271
- inflightRequests: this.inflight.size,
272
- queuedRequests: this.queueEnabled && this.queue
273
- ? (this.queue.queuedCount ?? 0)
274
- : 0,
275
- activeRequests: this.queueEnabled && this.queue
276
- ? (this.queue.activeCount ?? 0)
277
- : 0,
278
- currentRateLimit: this.limiterEnabled && this.limiter
279
- ? (this.limiter.currentCount ?? 0)
280
- : 0,
281
- };
282
- }
283
- async warmup(urls, count = 10) {
284
- const tasks = [];
285
- for (let i = 0; i < count; i++) {
286
- const url = urls[i % urls.length];
287
- tasks.push(this.get(url, "text").catch(() => undefined));
288
- }
289
- await Promise.all(tasks);
290
- }
291
- mergeOptions(base, patch) {
292
- return {
293
- ...base,
294
- ...patch,
295
- network: { ...base.network, ...patch.network },
296
- retry: { ...base.retry, ...patch.retry },
297
- cache: { ...base.cache, ...patch.cache },
298
- rateLimit: { ...base.rateLimit, ...patch.rateLimit },
299
- metrics: { ...base.metrics, ...patch.metrics },
300
- queue: { ...base.queue, ...patch.queue },
301
- responseConverter: {
302
- ...base.responseConverter,
303
- ...patch.responseConverter,
304
- },
305
- };
306
- }
307
- normalizeRequest(req, body) {
308
- if (typeof req === "string") {
309
- return {
310
- getURL: () => req,
311
- getBodyData: () => body,
312
- getHeaders: () => ({}),
313
- };
314
- }
315
- return req;
316
- }
317
- applyDefaulthcoptions(opt) {
318
- const defaults = {
319
- network: {
320
- timeout: 30000,
321
- maxRedirects: 5,
322
- followRedirects: true,
323
- maxResponseBytes: 10 * 1024 * 1024,
324
- userAgent: "Hyperttp/2.0",
325
- allowHttp2: true,
326
- pipelining: 10,
327
- keepAliveTimeout: 30000,
328
- maxConcurrent: 0,
329
- rejectUnauthorized: false,
330
- },
331
- cache: {
332
- enabled: true,
333
- ttl: 1000 * 60 * 5,
334
- maxSize: 500,
335
- methods: [],
336
- },
337
- retry: {
338
- maxRetries: 3,
339
- baseDelay: 1000,
340
- maxDelay: 10000,
341
- retryStatusCodes: [408, 429, 500, 502, 503, 504],
342
- jitter: true,
343
- },
344
- rateLimit: {
345
- enabled: false,
346
- maxRequests: 100,
347
- windowMs: 60000,
348
- },
349
- metrics: {
350
- enabled: true,
351
- maxHistory: 1000,
352
- },
353
- queue: {
354
- enabled: true,
355
- },
356
- responseConverter: {
357
- maxBodySize: 0,
358
- parseHTML: false,
359
- htmlMode: "simple",
360
- charset: "utf-8",
361
- },
362
- };
363
- return {
364
- ...defaults,
365
- ...opt,
366
- network: { ...defaults.network, ...opt?.network },
367
- cache: { ...defaults.cache, ...opt?.cache },
368
- retry: { ...defaults.retry, ...opt?.retry },
369
- rateLimit: { ...defaults.rateLimit, ...opt?.rateLimit },
370
- metrics: { ...defaults.metrics, ...opt?.metrics },
371
- queue: { ...defaults.queue, ...opt?.queue },
372
- responseConverter: {
373
- ...defaults.responseConverter,
374
- ...opt?.responseConverter,
375
- },
376
- };
377
- }
378
- /**
379
- * @en Core internal method for handling all HTTP requests.
380
- * @ru Основной внутренний метод для обработки всех HTTP-запросов.
381
- * @param method HTTP method (GET, POST, etc.)
382
- * @param req Request object
383
- * @param useCache Whether to use caching for this request
384
- * @param responseType Expected response format
385
- */
386
- async requestInternal(method, req, useCache = true, responseType = "auto") {
387
- const url = req.getURL();
388
- const userSignal = req.getSignal?.();
389
- if (userSignal?.aborted) {
390
- throw new errors_js_1.HttpClientError("Request aborted by user", "ABORTED", 0, undefined, url, method);
391
- }
392
- if (this.metricsManager.isCircuitOpen(url)) {
393
- throw new errors_js_1.HttpClientError("Circuit Breaker is OPEN", "CIRCUIT_OPEN", 503, undefined, url, method);
394
- }
395
- if (this.limiter) {
396
- await this.limiter.wait();
397
- }
398
- const { body, headers } = this.prepareRequestData(method, req);
399
- const key = method === "GET"
400
- ? `GET:${url}`
401
- : body !== undefined && body !== null
402
- ? `${method}:${url}:${typeof body === "string" ? body : JSON.stringify(body)}`
403
- : `${method}:${url}`;
404
- if (this.cache && method === "GET" && useCache) {
405
- const cached = await this.cache.get(key);
406
- if (cached !== undefined) {
407
- return cached;
408
- }
409
- }
410
- const existing = this.inflight.get(key);
411
- if (existing) {
412
- return existing.promise;
413
- }
414
- const internalController = new AbortController();
415
- const abortHandler = () => internalController.abort();
416
- if (userSignal) {
417
- userSignal.addEventListener("abort", abortHandler, { once: true });
418
- }
419
- const run = () => (async () => {
420
- let metrics;
421
- const needMetrics = this.metricsEnabled;
422
- if (needMetrics) {
423
- metrics = this.createInitialMetrics(url, method);
424
- }
425
- try {
426
- if (method === "HEAD") {
427
- const rawResponse = await this.executor.execute(method, url, headers, body, metrics, internalController.signal);
428
- if (needMetrics && metrics) {
429
- this.recordSuccess(metrics, rawResponse.status);
430
- }
431
- return {
432
- status: rawResponse.status,
433
- headers: rawResponse.headers,
434
- };
435
- }
436
- const rawResponse = await this.executor.execute(method, url, headers, body, metrics, internalController.signal);
437
- const bufferBody = await this.converter.readBody(rawResponse.body);
438
- const parsed = await this.converter.convert(bufferBody, responseType, {
439
- contentType: rawResponse.headers["content-type"],
440
- contentEncoding: rawResponse.headers["content-encoding"],
441
- url: rawResponse.url,
442
- });
443
- if (this.cache &&
444
- method === "GET" &&
445
- useCache &&
446
- parsed !== undefined) {
447
- this.cache.set(key, parsed);
448
- }
449
- if (needMetrics && metrics) {
450
- this.recordSuccess(metrics, rawResponse.status);
451
- }
452
- return parsed;
453
- }
454
- catch (error) {
455
- if (needMetrics && metrics) {
456
- this.recordError(metrics, error);
457
- }
458
- throw error;
459
- }
460
- finally {
461
- if (userSignal) {
462
- userSignal.removeEventListener("abort", abortHandler);
463
- }
464
- this.inflight.delete(key);
465
- }
466
- })();
467
- const promise = this.queueEnabled && this.queue ? this.queue.enqueue(run) : run();
468
- this.inflight.set(key, { promise, controller: internalController });
469
- return promise;
470
- }
471
- prepareRequestData(method, req) {
472
- const headers = { ...this.defaultHeaders, ...req.getHeaders() };
473
- let rawBody = req.getBodyData();
474
- if (!["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
475
- return { body: undefined, headers };
476
- }
477
- if (rawBody &&
478
- typeof rawBody === "object" &&
479
- !(rawBody instanceof Buffer)) {
480
- const contentType = (headers["content-type"] ||
481
- headers["Content-Type"] ||
482
- "").toLowerCase();
483
- if (contentType.includes("application/x-www-form-urlencoded")) {
484
- const params = new URLSearchParams();
485
- for (const [key, value] of Object.entries(rawBody)) {
486
- params.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
487
- }
488
- rawBody = params.toString();
489
- }
490
- else {
491
- rawBody = JSON.stringify(rawBody);
492
- if (!headers["content-type"]) {
493
- headers["content-type"] = "application/json; charset=utf-8";
494
- }
495
- }
496
- }
497
- return {
498
- body: rawBody === null || rawBody === undefined ? undefined : rawBody,
499
- headers,
500
- };
501
- }
502
- createInitialMetrics(url, method) {
503
- return {
504
- startTime: Date.now(),
505
- endTime: 0,
506
- duration: 0,
507
- bytesReceived: 0,
508
- bytesSent: 0,
509
- retries: 0,
510
- cached: false,
511
- url,
512
- method,
513
- };
514
- }
515
- recordSuccess(metrics, status) {
516
- metrics.endTime = Date.now();
517
- metrics.duration = metrics.endTime - metrics.startTime;
518
- metrics.statusCode = status;
519
- this.metricsManager.record(metrics);
520
- if (this.verboseEnabled) {
521
- this.config.logger?.("info", `Request successful: ${metrics.method} ${metrics.url}`, {
522
- duration: metrics.duration,
523
- status: metrics.statusCode,
524
- });
525
- }
526
- }
527
- recordError(metrics, error) {
528
- metrics.endTime = Date.now();
529
- metrics.duration = metrics.endTime - metrics.startTime;
530
- metrics.statusCode = error?.statusCode || 0;
531
- this.metricsManager.record(metrics);
532
- if (this.verboseEnabled) {
533
- this.config.logger?.("error", `Request failed: ${metrics.method} ${metrics.url}`, {
534
- error: error?.message,
535
- code: error?.code,
536
- });
537
- }
538
- }
539
- }
540
- exports.default = HttpClientImproved;
541
- //# sourceMappingURL=HttpClientImproved.js.map