@sevtech/kit 0.0.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.
@@ -0,0 +1,1292 @@
1
+ import { isArray, isNonEmptyString, isPlainObject, isNil, isString, isNumber, isBoolean, resolveMaybeFn, isUndefined, isFunction, isInstance, objectKeys, isDefined, objectEntries, randomArrayItem } from '@sevtech/kit/misc';
2
+ import { HttpStatusCode, HttpClient, HttpParams, HttpContext, HttpContextToken, HttpHeaders, HttpResponse, HttpEventType, HttpErrorResponse } from '@angular/common/http';
3
+ import * as i0 from '@angular/core';
4
+ import { InjectionToken, inject, Injectable, signal, computed } from '@angular/core';
5
+ import { finalize, tap, catchError, throwError, delay, of, map, retry, timer, timeout } from 'rxjs';
6
+
7
+ function parseHttpHeaders(headers) {
8
+ const requestHeaders = {};
9
+ for (const key of headers.keys()) {
10
+ const value = headers.getAll(key);
11
+ if (isArray(value)) {
12
+ requestHeaders[key.toLowerCase()] = value;
13
+ }
14
+ }
15
+ return requestHeaders;
16
+ }
17
+ function resolveErrorMessage(error) {
18
+ try {
19
+ const message = resolveMessage(error);
20
+ return isNonEmptyString(message) ? message : undefined;
21
+ }
22
+ catch {
23
+ return isPlainObject(error) && isNonEmptyString(error['message'])
24
+ ? error['message']
25
+ : undefined;
26
+ }
27
+ }
28
+ function resolveMessage(data) {
29
+ const errors = resolveErrorsArray(data);
30
+ if (isNil(errors) || errors.length === 0)
31
+ return data.message;
32
+ const foundError = errors.find((item) => isNonEmptyString(item.message));
33
+ return foundError?.message ? foundError.message : data.message;
34
+ }
35
+ function resolveErrorsArray(data) {
36
+ if (!isPlainObject(data))
37
+ return undefined;
38
+ if (isArray(data.errors))
39
+ return data.errors;
40
+ return 'error' in data && isPlainObject(data.error) ? data.error.errors : undefined;
41
+ }
42
+
43
+ var ApiErrorKind;
44
+ (function (ApiErrorKind) {
45
+ /**
46
+ * Сетевая ошибка.
47
+ * @description Например, недоступен сервер, обрыв соединения, DNS‑ошибка и т.п.
48
+ * Может не иметь валидного HTTP‑статуса.
49
+ */
50
+ ApiErrorKind[ApiErrorKind["Network"] = 0] = "Network";
51
+ /**
52
+ * Попытка обращения к несуществующим данным.
53
+ * @description Пример: отсутствует запись с указанным идентификатором.
54
+ * Обычно соответствует HTTP‑статусу `404 Not Found`.
55
+ */
56
+ ApiErrorKind[ApiErrorKind["NotExist"] = 1] = "NotExist";
57
+ /**
58
+ * Ошибка валидации входных данных.
59
+ * @description Переданные параметры не соответствуют требованиям API.
60
+ * Обычно соответствует HTTP‑статусу `400 Bad Request`.
61
+ */
62
+ ApiErrorKind[ApiErrorKind["Validation"] = 2] = "Validation";
63
+ /**
64
+ * Ошибка доступа (недостаточно прав).
65
+ * @description У пользователя нет прав на выполнение операции.
66
+ * Обычно соответствует HTTP‑статусу `403 Forbidden`.
67
+ */
68
+ ApiErrorKind[ApiErrorKind["Access"] = 3] = "Access";
69
+ /**
70
+ * Бизнес‑ошибка, возвращаемая доменным слоем/БД.
71
+ * @description Например, попытка создать дубликат сущности или нарушение бизнес‑правил.
72
+ * В типичном случае мапится на `418 I'm a teapot`
73
+ */
74
+ ApiErrorKind[ApiErrorKind["Domain"] = 4] = "Domain";
75
+ /**
76
+ * Таймаут запроса на стороне клиента.
77
+ * @description Превышено допустимое время ожидания ответа сервера.
78
+ * Обычно соответствует HTTP‑статусу `408 Request Timeout`.
79
+ */
80
+ ApiErrorKind[ApiErrorKind["Timeout"] = 5] = "Timeout";
81
+ /**
82
+ * Пользователь не аутентифицирован.
83
+ * @description Например, отсутствует или истёк токен доступа.
84
+ * Обычно соответствует HTTP‑статусу `401 Unauthorized`.
85
+ */
86
+ ApiErrorKind[ApiErrorKind["Unauthorized"] = 6] = "Unauthorized";
87
+ /**
88
+ * Неизвестная ошибка.
89
+ * @description Используется для любых ошибок, которые не подпадают
90
+ * под остальные категории.
91
+ */
92
+ ApiErrorKind[ApiErrorKind["Unknown"] = 7] = "Unknown";
93
+ })(ApiErrorKind || (ApiErrorKind = {}));
94
+
95
+ class HttpBaseError {
96
+ constructor(httpError, resolveMessage) {
97
+ this.url = httpError.url;
98
+ this.status = httpError.status;
99
+ this.redirected = httpError.redirected;
100
+ this.payload = httpError.error;
101
+ this.message = resolveMessage
102
+ ? (resolveErrorMessage(httpError.error) ?? httpError.message)
103
+ : httpError.message;
104
+ }
105
+ }
106
+ class HttpNetworkError extends HttpBaseError {
107
+ constructor(httpError, message) {
108
+ super(httpError, false);
109
+ this.name = HttpNetworkError.name;
110
+ this.kind = ApiErrorKind.Network;
111
+ if (isString(message)) {
112
+ this.message = message;
113
+ }
114
+ }
115
+ }
116
+ class HttpNotExistError extends HttpBaseError {
117
+ constructor(httpError) {
118
+ super(httpError, true);
119
+ this.name = HttpNotExistError.name;
120
+ this.kind = ApiErrorKind.NotExist;
121
+ }
122
+ }
123
+ class HttpValidationError extends HttpBaseError {
124
+ constructor(httpError) {
125
+ super(httpError, false);
126
+ this.name = HttpValidationError.name;
127
+ this.kind = ApiErrorKind.Validation;
128
+ this.errorsMap = new Map();
129
+ this.fillErrorsMap(httpError.error);
130
+ this.errors = [...this.errorsMap.values()].flat();
131
+ }
132
+ selectErrors(location) {
133
+ const locations = isArray(location) ? location : [location];
134
+ const result = [];
135
+ for (const key of locations) {
136
+ result.push(...(this.errorsMap.get(key) ?? []));
137
+ }
138
+ return result;
139
+ }
140
+ resolveMessages(location, separator = null) {
141
+ const errors = this.selectErrors(location);
142
+ const messages = errors.map((error) => error.message);
143
+ if (messages.length === 0)
144
+ return '';
145
+ return isNil(separator) ? messages[0] : messages.join(separator);
146
+ }
147
+ fillErrorsMap(data) {
148
+ if (isNil(data))
149
+ return;
150
+ const errors = resolveErrorsArray(data);
151
+ if (isNil(errors))
152
+ return;
153
+ for (const error of errors) {
154
+ const item = this.normalizeValidationItem(error);
155
+ if (isNil(item))
156
+ continue;
157
+ this.errorsMap.set(item.location, [...(this.errorsMap.get(item.location) ?? []), item]);
158
+ }
159
+ }
160
+ normalizeValidationItem(item) {
161
+ if (isValidationItem(item)) {
162
+ const path = item.path.replace(/[\\/]+/g, '.').replace(/^\./, '');
163
+ return { ...item, path };
164
+ }
165
+ if (!isString(item.path) || !isString(item.message))
166
+ return null;
167
+ const [location, ...rest] = item.path.split(/[\\/]/);
168
+ if (!isValidationLocations(location) || rest.length === 0)
169
+ return null;
170
+ return {
171
+ location,
172
+ message: item.message,
173
+ path: rest.join('.'),
174
+ };
175
+ }
176
+ }
177
+ class HttpAccessError extends HttpBaseError {
178
+ constructor(httpError) {
179
+ super(httpError, true);
180
+ this.name = HttpAccessError.name;
181
+ this.kind = ApiErrorKind.Access;
182
+ }
183
+ }
184
+ class HttpDomainError extends HttpBaseError {
185
+ constructor(httpError) {
186
+ super(httpError, true);
187
+ this.name = HttpDomainError.name;
188
+ this.kind = ApiErrorKind.Domain;
189
+ }
190
+ }
191
+ class HttpTimeoutError extends HttpBaseError {
192
+ constructor(httpError) {
193
+ super(httpError, true);
194
+ this.name = HttpTimeoutError.name;
195
+ this.kind = ApiErrorKind.Timeout;
196
+ }
197
+ }
198
+ class HttpUnauthorizedError extends HttpBaseError {
199
+ constructor(httpError) {
200
+ super(httpError, true);
201
+ this.name = HttpUnauthorizedError.name;
202
+ this.kind = ApiErrorKind.Unauthorized;
203
+ }
204
+ }
205
+ class HttpUnknownError extends HttpBaseError {
206
+ constructor(httpError) {
207
+ super(httpError, true);
208
+ this.name = HttpUnknownError.name;
209
+ this.kind = ApiErrorKind.Unknown;
210
+ }
211
+ }
212
+
213
+ function isValidationLocations(data) {
214
+ return isString(data) && ['body', 'header', 'path', 'env', 'query'].includes(data);
215
+ }
216
+ function isBaseError(data) {
217
+ if (!isPlainObject(data))
218
+ return false;
219
+ if (data['success'] !== false || !isString(data['message'])) {
220
+ return false;
221
+ }
222
+ const errors = resolveErrorsArray(data);
223
+ if (isNil(errors))
224
+ return true;
225
+ return errors.every(isDBErrorItem);
226
+ }
227
+ function isValidationError(data) {
228
+ if (!isPlainObject(data))
229
+ return false;
230
+ if (data['status'] !== HttpStatusCode.BadRequest)
231
+ return false;
232
+ return isArray(data['errors']) && data['errors'].every(isValidationItem);
233
+ }
234
+ function isDBErrorItem(data) {
235
+ return isPlainObject(data) && isString(data['code']);
236
+ }
237
+ function isValidationItem(data) {
238
+ return (isPlainObject(data) &&
239
+ isString(data['path']) &&
240
+ isString(data['message']) &&
241
+ isString(data['location']));
242
+ }
243
+ function isPrimitive(data) {
244
+ return isString(data) || isNumber(data) || isBoolean(data);
245
+ }
246
+ function isApiError(data, kind) {
247
+ if (data instanceof HttpBaseError) {
248
+ return isNil(kind) ? true : data.kind === kind;
249
+ }
250
+ return false;
251
+ }
252
+
253
+ const DEFAULT_API_OPTIONS = {
254
+ observe: 'body',
255
+ contentType: 'default',
256
+ responseType: 'json',
257
+ serialize: {
258
+ arrayKeyStyle: 'plain',
259
+ arrayFormat: 'repeat',
260
+ unsupported: 'error',
261
+ },
262
+ };
263
+
264
+ const API_PREFIX = new InjectionToken('[URL_PREFIX]: добавляет базовый префикс к URL запроса');
265
+ function provideApiPrefix(prefix) {
266
+ return {
267
+ provide: API_PREFIX,
268
+ useFactory: () => resolveMaybeFn(prefix),
269
+ };
270
+ }
271
+ const API_OPTIONS = new InjectionToken('[API_OPTIONS]: определяет настройки запросов по умолчанию', {
272
+ providedIn: 'root',
273
+ factory: () => DEFAULT_API_OPTIONS,
274
+ });
275
+ function provideApiOptions(options) {
276
+ return {
277
+ provide: API_OPTIONS,
278
+ useFactory: () => {
279
+ const resolvedOptions = resolveMaybeFn(options);
280
+ return {
281
+ ...DEFAULT_API_OPTIONS,
282
+ ...resolvedOptions,
283
+ };
284
+ },
285
+ };
286
+ }
287
+ const API_BODY_TRANSFORM = new InjectionToken('[API_BODY_TRANSFORM]: предоставляет функции для трансформации тела запроса');
288
+ function provideApiBodyTransform(transform) {
289
+ return {
290
+ provide: API_BODY_TRANSFORM,
291
+ useValue: transform,
292
+ };
293
+ }
294
+
295
+ const ERROR_NAMESPACE = '[HTTP_API]';
296
+ class ApiBase {
297
+ constructor() {
298
+ this.httpClient = inject(HttpClient);
299
+ this.bodyTransform = inject(API_BODY_TRANSFORM, { optional: true });
300
+ this.prefix = inject(API_PREFIX, { optional: true });
301
+ this.options = inject(API_OPTIONS);
302
+ }
303
+ request(method, url, options, data) {
304
+ const { contentType, body, serialize, ...restOptions } = this.resolveRequestOptions(options);
305
+ const serializeOptions = this.resolveSerializeConfig(serialize);
306
+ const requestParams = this.resolveOptions(restOptions, serializeOptions);
307
+ const requestBody = this.resolveBody(data ?? body, contentType ?? 'default', serializeOptions);
308
+ if (!isUndefined(requestBody)) {
309
+ requestParams['body'] = requestBody;
310
+ }
311
+ if (method !== 'GET' && method !== 'POST') {
312
+ delete requestParams['transferCache'];
313
+ }
314
+ return this.httpClient.request(method, this.resolveUrl(url), requestParams);
315
+ }
316
+ resolveRequestOptions(options) {
317
+ return {
318
+ ...this.options,
319
+ ...options,
320
+ };
321
+ }
322
+ resolveSerializeConfig(config) {
323
+ return {
324
+ ...DEFAULT_API_OPTIONS.serialize,
325
+ ...config,
326
+ };
327
+ }
328
+ resolveBody(body, contentType, config) {
329
+ const transformedBody = isFunction(this.bodyTransform) ? this.bodyTransform(body) : body;
330
+ if (transformedBody === null)
331
+ return null;
332
+ switch (contentType) {
333
+ case 'encoded':
334
+ return normalizeEncodedContent(transformedBody, config);
335
+ case 'text':
336
+ return normalizeTextContent(transformedBody);
337
+ case 'form-data':
338
+ return normalizeFormDataContent(transformedBody, config);
339
+ case 'binary':
340
+ return normalizeBinaryContent(transformedBody);
341
+ default:
342
+ return transformedBody;
343
+ }
344
+ }
345
+ resolveUrl(url) {
346
+ if (/^https?:\/\//i.test(url) || isNil(this.prefix))
347
+ return url;
348
+ const normalizedPrefix = this.prefix.replace(/\/$/, '');
349
+ const normalizedUrl = url.replace(/^\//, '');
350
+ return `${normalizedPrefix}/${normalizedUrl}`;
351
+ }
352
+ resolveOptions(options, serializeConfig) {
353
+ if (isNil(options))
354
+ return {};
355
+ const params = normalizeParams(options.params, serializeConfig);
356
+ const context = normalizeContext(options.context);
357
+ return {
358
+ ...options,
359
+ context,
360
+ params,
361
+ };
362
+ }
363
+ }
364
+ function normalizeTextContent(data) {
365
+ if (isString(data))
366
+ return data;
367
+ throw new TypeError(`${ERROR_NAMESPACE}: Expected string, received ${typeof data}`);
368
+ }
369
+ function normalizeBinaryContent(data) {
370
+ if (isInstance(data, Blob) || isInstance(data, ArrayBuffer) || isInstance(data, Uint8Array)) {
371
+ return data;
372
+ }
373
+ throw new TypeError(`${ERROR_NAMESPACE}: Expected Blob, ArrayBuffer or Uint8Array, received ${typeof data}`);
374
+ }
375
+ function normalizeEncodedContent(data, config) {
376
+ if (data instanceof HttpParams)
377
+ return data;
378
+ if (data instanceof URLSearchParams)
379
+ return new HttpParams({ fromString: data.toString() });
380
+ if (!isPlainObject(data)) {
381
+ throw new TypeError(`${ERROR_NAMESPACE}: Expected HttpParams, URLSearchParams or plain object, received ${typeof data}`);
382
+ }
383
+ return new HttpParams({ fromObject: normalizeParamsObject(data, config, false) });
384
+ }
385
+ function normalizeFormDataContent(data, config) {
386
+ if (data instanceof FormData)
387
+ return data;
388
+ if (!isPlainObject(data)) {
389
+ throw new TypeError(`${ERROR_NAMESPACE}: Expected FormData or plain object, received ${typeof data}`);
390
+ }
391
+ const obj = normalizeParamsObject(data, config, true);
392
+ const formData = new FormData();
393
+ for (const key of objectKeys(obj)) {
394
+ const value = obj[key];
395
+ if (isArray(value)) {
396
+ for (const item of value) {
397
+ formData.append(key, item);
398
+ }
399
+ }
400
+ else {
401
+ formData.set(key, value);
402
+ }
403
+ }
404
+ return formData;
405
+ }
406
+ function normalizeContext(context) {
407
+ return isFunction(context) ? context(new HttpContext()) : undefined;
408
+ }
409
+ function normalizeParams(params, config) {
410
+ if (isNil(params))
411
+ return;
412
+ if (params instanceof HttpParams)
413
+ return params;
414
+ if (params instanceof URLSearchParams)
415
+ return new HttpParams({ fromString: params.toString() });
416
+ return new HttpParams({ fromObject: normalizeParamsObject(params, config, false) });
417
+ }
418
+ function normalizeParamsObject(obj, config, safeBlob) {
419
+ return objectKeys(obj).reduce((result, key) => {
420
+ try {
421
+ const value = normalizeValue(obj[key], config, safeBlob);
422
+ if (isNil(value))
423
+ return result;
424
+ const paramKey = config.arrayKeyStyle === 'brackets' && isArray(value) ? `${key}[]` : key;
425
+ result[paramKey] = isArray(value) && config.arrayFormat === 'comma' ? String(value) : value;
426
+ return result;
427
+ }
428
+ catch (error) {
429
+ if (error instanceof TypeError) {
430
+ throw new TypeError(`${ERROR_NAMESPACE}: Failed to serialize key "${key}", unsupported value type`);
431
+ }
432
+ throw error;
433
+ }
434
+ }, {});
435
+ }
436
+ function normalizeValue(value, config, safeBlob) {
437
+ if (isNil(value))
438
+ return;
439
+ if (isPrimitive(value))
440
+ return String(value);
441
+ if (isArray(value))
442
+ return normalizeArray(value, config.unsupported, safeBlob);
443
+ if (safeBlob && value instanceof Blob)
444
+ return value;
445
+ return handleUnsupported(value, config.unsupported);
446
+ }
447
+ function normalizeArray(values, unsupported, safeBlob) {
448
+ const result = [];
449
+ for (const value of values) {
450
+ if (isNil(value))
451
+ continue;
452
+ if (isPrimitive(value)) {
453
+ result.push(String(value));
454
+ continue;
455
+ }
456
+ if (safeBlob && value instanceof Blob) {
457
+ result.push(value);
458
+ continue;
459
+ }
460
+ const data = handleUnsupported(value, unsupported);
461
+ if (isString(data)) {
462
+ result.push(data);
463
+ }
464
+ }
465
+ return result.length > 0 ? result : undefined;
466
+ }
467
+ function handleUnsupported(value, unsupportedStrategy) {
468
+ switch (unsupportedStrategy) {
469
+ case 'stringify':
470
+ return JSON.stringify(value);
471
+ case 'skip':
472
+ return;
473
+ default:
474
+ throw new TypeError(`${ERROR_NAMESPACE}: Expect a primitive value type`);
475
+ }
476
+ }
477
+
478
+ class HttpApiService extends ApiBase {
479
+ get(url, params, options) {
480
+ return this.request('GET', url, { ...options, params });
481
+ }
482
+ post(url, body, options) {
483
+ return this.request('POST', url, options, body);
484
+ }
485
+ put(url, body, options) {
486
+ return this.request('PUT', url, options, body);
487
+ }
488
+ patch(url, body, options) {
489
+ return this.request('PATCH', url, options, body);
490
+ }
491
+ delete(url, params, options) {
492
+ return this.request('DELETE', url, { ...options, params });
493
+ }
494
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: HttpApiService, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
495
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: HttpApiService, providedIn: 'root' }); }
496
+ }
497
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: HttpApiService, decorators: [{
498
+ type: Injectable,
499
+ args: [{
500
+ providedIn: 'root',
501
+ }]
502
+ }] });
503
+
504
+ const DEFAULT_PROGRESS_CONFIG = {
505
+ silent: [],
506
+ enabled: true,
507
+ };
508
+
509
+ const PROGRESS_CONFIG = new InjectionToken('PROGRESS_CONFIG', {
510
+ factory: () => DEFAULT_PROGRESS_CONFIG,
511
+ });
512
+ /**
513
+ * HttpContextToken для управления прогрессом конкретного запроса.
514
+ *
515
+ * @description
516
+ * Поведение:
517
+ * - `true` - включить глобальный прогресс (игнорирует silent)
518
+ * - `string` - использовать локальный ключ
519
+ * - `null` - стандартное поведение (учитывает silent)
520
+ * @example
521
+ * this.http.get(url, {
522
+ * context: new HttpContext().set(USE_PROGRESS, 'users-table')
523
+ * });
524
+ * @default null
525
+ */
526
+ const USE_PROGRESS = new HttpContextToken(() => null);
527
+ function provideProgressConfig(config) {
528
+ return {
529
+ provide: PROGRESS_CONFIG,
530
+ useFactory: () => ({
531
+ ...DEFAULT_PROGRESS_CONFIG,
532
+ ...resolveMaybeFn(config),
533
+ }),
534
+ };
535
+ }
536
+
537
+ class ProgressManagerService {
538
+ constructor() {
539
+ this.keys$$ = signal(new Map(), ...(ngDevMode ? [{ debugName: "keys$$" }] : []));
540
+ this.count$$ = signal(0, ...(ngDevMode ? [{ debugName: "count$$" }] : []));
541
+ }
542
+ start(key) {
543
+ this.count$$.update((value) => value + 1);
544
+ if (!isString(key))
545
+ return;
546
+ const map = new Map(this.keys$$());
547
+ map.set(key, (map.get(key) ?? 0) + 1);
548
+ this.keys$$.set(map);
549
+ }
550
+ stop(key) {
551
+ this.count$$.update((value) => Math.max(0, value - 1));
552
+ if (!isString(key))
553
+ return;
554
+ const map = new Map(this.keys$$());
555
+ const current = (map.get(key) ?? 1) - 1;
556
+ if (current <= 0) {
557
+ map.delete(key);
558
+ }
559
+ else {
560
+ map.set(key, current);
561
+ }
562
+ this.keys$$.set(map);
563
+ }
564
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: ProgressManagerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
565
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: ProgressManagerService, providedIn: 'root' }); }
566
+ }
567
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: ProgressManagerService, decorators: [{
568
+ type: Injectable,
569
+ args: [{
570
+ providedIn: 'root',
571
+ }]
572
+ }] });
573
+
574
+ class ProgressHttpService {
575
+ constructor() {
576
+ this.manager = inject(ProgressManagerService);
577
+ /**
578
+ * Глобальный сигнал загрузки.
579
+ *
580
+ * @description
581
+ * Возвращает `true`, если есть хотя бы один активный HTTP-запрос.
582
+ * Подходит для глобального прогресс-бара приложения.
583
+ */
584
+ this.progress$$ = computed(() => this.manager.count$$() > 0, ...(ngDevMode ? [{ debugName: "progress$$" }] : []));
585
+ }
586
+ /**
587
+ * Возвращает сигнал загрузки для конкретного ключа
588
+ * @description
589
+ * Используется для отображения локальных спиннеров
590
+ * (например, таблица, карточка, форма и т.д.).
591
+ *
592
+ * @example
593
+ * const loading$$ = progressHttp.select('users-table');
594
+ */
595
+ select(key) {
596
+ return computed(() => (this.manager.keys$$().get(key) ?? 0) > 0);
597
+ }
598
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: ProgressHttpService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
599
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: ProgressHttpService, providedIn: 'root' }); }
600
+ }
601
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: ProgressHttpService, decorators: [{
602
+ type: Injectable,
603
+ args: [{
604
+ providedIn: 'root',
605
+ }]
606
+ }] });
607
+
608
+ function resolveProgressConfig(request, config) {
609
+ const useProgress = request.context.get(USE_PROGRESS);
610
+ if (isDefined(useProgress))
611
+ return useProgress;
612
+ if (!config.enabled)
613
+ return false;
614
+ const silent = isArray(config.silent) ? config.silent : [config.silent];
615
+ return !silent.some((rule) => isString(rule) ? request.url.includes(rule) : rule.test(request.url));
616
+ }
617
+ const progressInterceptor = (request, next) => {
618
+ const manager = inject(ProgressManagerService);
619
+ const config = resolveProgressConfig(request, inject(PROGRESS_CONFIG));
620
+ if (!config)
621
+ return next(request);
622
+ const key = isString(config) ? config : undefined;
623
+ manager.start(isString(config) ? config : undefined);
624
+ return next(request).pipe(finalize(() => manager.stop(key)));
625
+ };
626
+
627
+ const DEFAULT_HEADERS_CONFIG = {
628
+ skip: [],
629
+ enabled: true,
630
+ strategy: 'replace',
631
+ };
632
+
633
+ function applyHeaders(headers, key, value, strategy) {
634
+ if (strategy === 'replace')
635
+ return value;
636
+ if (strategy === 'skip') {
637
+ return Object.hasOwnProperty.call(headers, key) ? headers[key] : value;
638
+ }
639
+ const prev = headers[key];
640
+ if (isNil(prev))
641
+ return value;
642
+ const nextValues = isArray(value) ? value : [value];
643
+ if (isArray(prev))
644
+ return [...prev, ...nextValues];
645
+ return [prev, ...nextValues];
646
+ }
647
+
648
+ const USE_HEADERS = new HttpContextToken(() => null);
649
+ const HEADERS_RESOLVER = new InjectionToken('[HEADERS_RESOLVER]: предоставляет заголовок для http-запроса');
650
+ const HEADERS_CONFIG = new InjectionToken('[HEADERS_CONFIG]: конфигурация работы headers-интерсептора', {
651
+ providedIn: 'root',
652
+ factory: () => DEFAULT_HEADERS_CONFIG,
653
+ });
654
+ function provideHeadersConfig(config) {
655
+ return {
656
+ provide: HEADERS_CONFIG,
657
+ useFactory: () => ({
658
+ ...DEFAULT_HEADERS_CONFIG,
659
+ ...resolveMaybeFn(config),
660
+ }),
661
+ };
662
+ }
663
+ function provideHeaders(resolver, strategy) {
664
+ return {
665
+ multi: true,
666
+ provide: HEADERS_RESOLVER,
667
+ useFactory: () => {
668
+ const applyStrategy = strategy ?? inject(HEADERS_CONFIG).strategy;
669
+ if (isFunction(resolver))
670
+ return resolver;
671
+ return (_, headers) => {
672
+ for (const [key, value] of objectEntries(resolver)) {
673
+ headers[key] = applyHeaders(headers, key, value, applyStrategy ?? DEFAULT_HEADERS_CONFIG.strategy);
674
+ }
675
+ };
676
+ },
677
+ };
678
+ }
679
+
680
+ function matchesUrl(pattern, url) {
681
+ return isString(pattern) ? url.includes(pattern) : pattern.test(url);
682
+ }
683
+ function matchRule(request, rule) {
684
+ if (isString(rule) || rule instanceof RegExp) {
685
+ return matchesUrl(rule, request.url);
686
+ }
687
+ if (isArray(rule)) {
688
+ return rule.some((item) => matchesUrl(item, request.url));
689
+ }
690
+ const { method, url } = rule;
691
+ const methodOk = method ? method === request.method : true;
692
+ const urlOk = url ? matchesUrl(url, request.url) : true;
693
+ return methodOk && urlOk;
694
+ }
695
+ function canUseInterceptor(request, config) {
696
+ const flag = request.context.get(USE_HEADERS);
697
+ if (isDefined(flag))
698
+ return flag;
699
+ if (!config.enabled)
700
+ return false;
701
+ return !matchRule(request, config.skip);
702
+ }
703
+ const headersInterceptor = (request, next) => {
704
+ const config = inject(HEADERS_CONFIG);
705
+ if (!canUseInterceptor(request, config))
706
+ return next(request);
707
+ const resolvers = inject(HEADERS_RESOLVER, { optional: true }) ?? [];
708
+ const requestHeaders = parseHttpHeaders(request.headers);
709
+ const headersMap = resolvers.reduce((headers, resolver) => resolver(request, headers) || headers, requestHeaders);
710
+ return next(request.clone({ headers: new HttpHeaders(headersMap) }));
711
+ };
712
+
713
+ const DEFAULT_HREF_STYLE = 'padding: 2px 4px; border-radius: 0 4px 4px 0;';
714
+ const DEFAULT_METHOD_STYLE = 'font-weight: 700; padding: 2px 4px; border-radius: 4px 0 0 4px; color: #fff;';
715
+ const DEFAULT_STATUS_STYLE = 'font-weight: 700; padding: 2px 4px; border-radius: 4px;';
716
+ const STYLES = {
717
+ href: {
718
+ GET: `${DEFAULT_HREF_STYLE} background-color: #61affe26;`,
719
+ POST: `${DEFAULT_HREF_STYLE} background-color: #49cc9026;`,
720
+ PUT: `${DEFAULT_HREF_STYLE} background-color: #fca13026;`,
721
+ PATCH: `${DEFAULT_HREF_STYLE} background-color: #50e3c226;`,
722
+ DELETE: `${DEFAULT_HREF_STYLE} background-color: #f93e3e26;`,
723
+ OPTIONS: `${DEFAULT_HREF_STYLE} background-color: #0d5aa726;`,
724
+ HEAD: `${DEFAULT_HREF_STYLE} background-color: #9012fe26;`,
725
+ },
726
+ title: 'font-weight: 700; margin-top: 10px; color: #6B7280',
727
+ namespace: 'font-size: 0; padding: 0; margin: 0',
728
+ duration: (duration) => {
729
+ return duration >= 1000 ? 'color: #DD2A2A; font-weight: bold;' : 'color: #18BC36;';
730
+ },
731
+ status: {
732
+ success: `${DEFAULT_STATUS_STYLE} color: #18BC36; background: #18BC3626;`,
733
+ redirect: `${DEFAULT_STATUS_STYLE} color: #1863DF; background: #1863DF26;`,
734
+ clientError: `${DEFAULT_STATUS_STYLE} color: #FFA000; background: #FFA00026;`,
735
+ serverError: `${DEFAULT_STATUS_STYLE} color: #DD2A2A; background: #DD2A2A26;`,
736
+ network: `${DEFAULT_STATUS_STYLE} color: #9CA3AF; background: #9CA3AF26;`,
737
+ },
738
+ method: {
739
+ GET: `${DEFAULT_METHOD_STYLE} background-color: #61affe;`,
740
+ POST: `${DEFAULT_METHOD_STYLE} background-color: #49cc90;`,
741
+ PUT: `${DEFAULT_METHOD_STYLE} background-color: #fca130;`,
742
+ PATCH: `${DEFAULT_METHOD_STYLE} background-color: #50e3c2;`,
743
+ DELETE: `${DEFAULT_METHOD_STYLE} background-color: #f93e3e;`,
744
+ OPTIONS: `${DEFAULT_METHOD_STYLE} background-color: #0d5aa7;`,
745
+ HEAD: `${DEFAULT_METHOD_STYLE} background-color: #9012fe;`,
746
+ },
747
+ };
748
+ const httpLogger = ({ request, duration, namespace, response }) => {
749
+ const url = new URL(request.urlWithParams, location.origin);
750
+ const method = request.method;
751
+ const href = url.origin === location.origin ? url.pathname : url.href.replace(/^http/, 'http\u200B');
752
+ const queryParams = computeQueryParams(url);
753
+ const statusType = computeStatusType(response.status);
754
+ console.groupCollapsed(`%c${namespace ?? ''}%c${method}%c${href}`, STYLES.namespace, STYLES.method[method], STYLES.href[method]);
755
+ console.log(`%cStatus: %c${response.status}`, STYLES.title, STYLES.status[statusType] ?? STYLES.status.network);
756
+ if (url.searchParams.size > 0) {
757
+ console.log('%cParams:\n', STYLES.title, queryParams);
758
+ }
759
+ console.log('%cHeaders:\n', STYLES.title, parseHttpHeaders(request.headers));
760
+ if (request.body) {
761
+ const body = computeRequestBody(request.body, request.headers.get('Content-Type') ?? '');
762
+ console.log('%cBody:\n', STYLES.title, body);
763
+ }
764
+ if (response instanceof HttpResponse) {
765
+ console.log('%cResponse:\n', STYLES.title, response);
766
+ }
767
+ else {
768
+ console.log('%cError:\n', STYLES.title, response);
769
+ }
770
+ console.log(`%cDuration: %c${formatDuration(duration)}`, STYLES.title, STYLES.duration(duration));
771
+ console.groupEnd();
772
+ };
773
+ function computeStatusType(status) {
774
+ if (!status)
775
+ return 'network';
776
+ if (status >= 200 && status < 300)
777
+ return 'success';
778
+ if (status >= 300 && status < 400)
779
+ return 'redirect';
780
+ if (status >= 400 && status < 500)
781
+ return 'clientError';
782
+ if (status >= 500)
783
+ return 'serverError';
784
+ return 'network';
785
+ }
786
+ function formatDuration(time) {
787
+ if (time < 1000) {
788
+ return `${time.toFixed(0)}ms`;
789
+ }
790
+ return `${(time / 1000).toFixed(2)}s`;
791
+ }
792
+ function computeQueryParams(url) {
793
+ const queryParams = {};
794
+ url.searchParams.forEach((value, key) => {
795
+ queryParams[key] = value;
796
+ });
797
+ return queryParams;
798
+ }
799
+ function computeRequestBody(body, contentType) {
800
+ if (body instanceof FormData) {
801
+ const result = {};
802
+ body.forEach((value, key) => (result[key] = value));
803
+ return result;
804
+ }
805
+ if (isString(body) && contentType.includes('application/x-www-form-urlencoded')) {
806
+ return body
807
+ .split('&')
808
+ .map((pair) => pair.split('='))
809
+ .reduce((acc, [key, value]) => {
810
+ acc[decodeURIComponent(key)] = decodeURIComponent(value);
811
+ return acc;
812
+ }, {});
813
+ }
814
+ return body;
815
+ }
816
+
817
+ const DEFAULT_LOGGER_CONFIG = {
818
+ namespace: '[HTTP]',
819
+ rules: [],
820
+ };
821
+
822
+ const LOGGER_CONFIG = new InjectionToken('[LOGGER_CONFIG]: конфигурация логера', {
823
+ providedIn: 'root',
824
+ factory: () => DEFAULT_LOGGER_CONFIG,
825
+ });
826
+ const LOGGER_HANDLER = new InjectionToken('[LOGGER_HANDLER]: функции-обработчик, для логирования (LoggerFn)', {
827
+ providedIn: 'root',
828
+ factory: () => httpLogger,
829
+ });
830
+ /**
831
+ * Контекстный токен для управления логированием конкретного HTTP-запроса.
832
+ * @description Имеет приоритет над глобальной конфигурацией (LoggerConfig.rules).
833
+ *
834
+ * Возможные значения:
835
+ * - false — отключить логирование для запроса
836
+ * - true — логировать все статусы
837
+ * - number — логировать только указанный статус
838
+ * - number[] — логировать только указанные статусы
839
+ * - RegExp — логировать статусы, подходящие под регулярное выражение
840
+ *
841
+ * @example
842
+ * this.http.get(url, {
843
+ * context: new HttpContext().set(USE_LOGGER, 404)
844
+ * });
845
+ */
846
+ const USE_LOGGER = new HttpContextToken(() => false);
847
+ function provideLoggerConfig(config) {
848
+ return {
849
+ provide: LOGGER_CONFIG,
850
+ useFactory: () => ({
851
+ ...DEFAULT_LOGGER_CONFIG,
852
+ ...resolveMaybeFn(config),
853
+ }),
854
+ };
855
+ }
856
+ function provideLoggerHandler(handler) {
857
+ return {
858
+ provide: LOGGER_HANDLER,
859
+ useFactory: () => resolveMaybeFn(handler),
860
+ };
861
+ }
862
+
863
+ function resolveConfig$1(config, request) {
864
+ const contextRule = request.context.get(USE_LOGGER);
865
+ if (contextRule !== false)
866
+ return contextRule;
867
+ if (isNil(config.rules) || config.rules.length === 0)
868
+ return false;
869
+ const foundRule = config.rules.find((rule) => {
870
+ if (request.method !== rule.method)
871
+ return false;
872
+ if (isString(rule.url) && request.url.includes(rule.url))
873
+ return true;
874
+ return rule.url instanceof RegExp && rule.url.test(request.url);
875
+ });
876
+ if (foundRule) {
877
+ return foundRule.status ?? true;
878
+ }
879
+ return false;
880
+ }
881
+ function canLog(statusConfig, response) {
882
+ if (statusConfig === true)
883
+ return true;
884
+ if (isArray(statusConfig))
885
+ return statusConfig.includes(response.status);
886
+ if (statusConfig instanceof RegExp)
887
+ return statusConfig.test(response.status.toString());
888
+ return statusConfig === response.status;
889
+ }
890
+ const loggerInterceptor = (request, next) => {
891
+ const config = inject(LOGGER_CONFIG);
892
+ const resolvedConfig = resolveConfig$1(config, request);
893
+ if (resolvedConfig === false) {
894
+ return next(request);
895
+ }
896
+ const logger = inject(LOGGER_HANDLER);
897
+ if (!isFunction(logger)) {
898
+ console.warn('[HTTP]: Logger handler is not defined');
899
+ return next(request);
900
+ }
901
+ const started = performance.now();
902
+ return next(request).pipe(tap((event) => {
903
+ if (event.type !== HttpEventType.Response)
904
+ return;
905
+ if (canLog(resolvedConfig, event)) {
906
+ logger({
907
+ namespace: config.namespace,
908
+ response: event,
909
+ duration: performance.now() - started,
910
+ request,
911
+ });
912
+ }
913
+ }), catchError((error) => {
914
+ if (error instanceof HttpErrorResponse && canLog(resolvedConfig, error)) {
915
+ logger({
916
+ namespace: config.namespace,
917
+ response: error,
918
+ duration: performance.now() - started,
919
+ request,
920
+ });
921
+ }
922
+ return throwError(() => error);
923
+ }));
924
+ };
925
+
926
+ const MOCK_STORE = new Map();
927
+ const DEFAULT_CONFIG$1 = {
928
+ enabled: false,
929
+ delay: 800,
930
+ errorChance: 0.3,
931
+ fallbackErrors: new HttpErrorResponse({
932
+ status: 500,
933
+ error: 'Internal error',
934
+ }),
935
+ };
936
+
937
+ /**
938
+ * Регистрирует мок-конфигурацию для определённого `MOCK_ID`.
939
+ * @example
940
+ * defineMock('get-user', {
941
+ * response: { id: 1, name: 'Иван' },
942
+ * });
943
+ *
944
+ * defineMock('get-users-list', {
945
+ * response: () => Array.from({ length: 10 }, () => ({
946
+ * id: faker.number.int(10_000),
947
+ * name: faker.person.fullName(),
948
+ * }))
949
+ * });
950
+ *
951
+ * @remarks
952
+ * Если мок с таким `id` уже зарегистрирован, будет выведено предупреждение в консоль,
953
+ * и существующая конфигурация не перезапишется.
954
+ * @remarks
955
+ * Функцию сразу регистрирует конфигурацию в хранилище
956
+ */
957
+ function defineMock(id, config) {
958
+ if (MOCK_STORE.has(id)) {
959
+ console.warn(`[MOCK INTERCEPTOR] Config ${id} already exist`, MOCK_STORE.get(id));
960
+ return;
961
+ }
962
+ MOCK_STORE.set(id, {
963
+ ...config,
964
+ enabled: config.enabled ?? true,
965
+ });
966
+ }
967
+
968
+ const USE_MOCK = new HttpContextToken(() => null);
969
+ const MOCK_CONFIG = new InjectionToken('[MOCK_CONFIG]: Базовая конфигурация интерсептора', {
970
+ providedIn: 'root',
971
+ factory: () => DEFAULT_CONFIG$1,
972
+ });
973
+ function provideMockConfig(config) {
974
+ return {
975
+ provide: MOCK_CONFIG,
976
+ useFactory: () => {
977
+ const normalizedConfig = resolveMaybeFn(config);
978
+ return {
979
+ ...DEFAULT_CONFIG$1,
980
+ ...normalizedConfig,
981
+ };
982
+ },
983
+ };
984
+ }
985
+
986
+ function resolveMockConfig(id, config) {
987
+ if (isNil(id) || isNil(config) || !config.enabled) {
988
+ return null;
989
+ }
990
+ const requestConfig = MOCK_STORE.get(id);
991
+ if (isNil(requestConfig) || !requestConfig.enabled) {
992
+ return null;
993
+ }
994
+ return {
995
+ ...config,
996
+ ...requestConfig,
997
+ };
998
+ }
999
+ function resolveError(config) {
1000
+ if (config.errorChance < Math.random())
1001
+ return null;
1002
+ const errors = config.errors ?? config.fallbackErrors;
1003
+ if (isNil(errors))
1004
+ return null;
1005
+ const resolvedError = resolveMaybeFn(errors);
1006
+ const errorsList = isArray(resolvedError) ? resolvedError : [resolvedError];
1007
+ return randomArrayItem(errorsList);
1008
+ }
1009
+ function resolveResponse(request, response) {
1010
+ const bodyOrResponse = resolveMaybeFn(response);
1011
+ if (bodyOrResponse instanceof HttpResponse) {
1012
+ return bodyOrResponse.clone({
1013
+ url: bodyOrResponse.url ?? request.url,
1014
+ });
1015
+ }
1016
+ return new HttpResponse({
1017
+ url: request.url,
1018
+ body: bodyOrResponse,
1019
+ });
1020
+ }
1021
+ const mockInterceptor = (request, next) => {
1022
+ const id = request.context.get(USE_MOCK);
1023
+ const config = resolveMockConfig(id, inject(MOCK_CONFIG));
1024
+ if (isNil(config))
1025
+ return next(request);
1026
+ const error = resolveError(config);
1027
+ if (error instanceof HttpErrorResponse) {
1028
+ return throwError(() => error).pipe(delay(config.delay));
1029
+ }
1030
+ const response = resolveResponse(request, config.response);
1031
+ return of(response).pipe(delay(config.delay));
1032
+ };
1033
+
1034
+ const DEFAULT_OPEN_API_CONFIG = {
1035
+ isApiResponse: (response) => {
1036
+ if ([0, 401, 408].some((status) => response.status === status))
1037
+ return true;
1038
+ return response.headers.get('X-Source') === 'erp-open-api';
1039
+ },
1040
+ errorResolver: (response) => {
1041
+ if (response.status === 0) {
1042
+ if (response.error instanceof DOMException && response.error.name === 'TimeoutError') {
1043
+ return new HttpTimeoutError(response);
1044
+ }
1045
+ if (isDefined(navigator) && !navigator.onLine) {
1046
+ return new HttpNetworkError(response);
1047
+ }
1048
+ return new HttpUnknownError(response);
1049
+ }
1050
+ if (response.status === 400) {
1051
+ return isBaseError(response.error) || isValidationError(response.error)
1052
+ ? new HttpValidationError(response)
1053
+ : new HttpUnknownError(response);
1054
+ }
1055
+ if (response.status === 500 && isValidationError(response.error)) {
1056
+ return new HttpValidationError(response);
1057
+ }
1058
+ if (!isBaseError(response.error)) {
1059
+ return new HttpUnknownError(response);
1060
+ }
1061
+ switch (response.status) {
1062
+ case 401:
1063
+ return new HttpUnauthorizedError(response);
1064
+ case 408:
1065
+ return new HttpNetworkError(response);
1066
+ case 403:
1067
+ return new HttpAccessError(response);
1068
+ case 404:
1069
+ return new HttpNotExistError(response);
1070
+ case 418:
1071
+ return new HttpDomainError(response);
1072
+ default:
1073
+ return new HttpUnknownError(response);
1074
+ }
1075
+ },
1076
+ };
1077
+
1078
+ const OPEN_API_CONFIG = new InjectionToken('[OPEN_API_CONFIG]: конфигурация OpenApi-интерсептора', {
1079
+ providedIn: 'root',
1080
+ factory: () => DEFAULT_OPEN_API_CONFIG,
1081
+ });
1082
+ function provideOpenApiConfig(config) {
1083
+ return {
1084
+ provide: OPEN_API_CONFIG,
1085
+ useFactory: () => {
1086
+ const resolvedConfig = resolveMaybeFn(config);
1087
+ return {
1088
+ ...DEFAULT_OPEN_API_CONFIG,
1089
+ ...resolvedConfig,
1090
+ };
1091
+ },
1092
+ };
1093
+ }
1094
+
1095
+ const openApiInterceptor = (request, next) => {
1096
+ const config = inject(OPEN_API_CONFIG);
1097
+ return next(request).pipe(map((response) => {
1098
+ if (response.type !== HttpEventType.Response) {
1099
+ return response;
1100
+ }
1101
+ if (isFunction(config.responseResolver) && config.isApiResponse(response)) {
1102
+ return config.responseResolver(response);
1103
+ }
1104
+ return response;
1105
+ }), catchError((error) => {
1106
+ if (!isInstance(error, HttpErrorResponse) || !config.isApiResponse(error)) {
1107
+ return throwError(() => error);
1108
+ }
1109
+ return throwError(() => config.errorResolver(error));
1110
+ }));
1111
+ };
1112
+
1113
+ const DEFAULT_CONFIG = {
1114
+ delay: 500,
1115
+ maxRetries: 3,
1116
+ delayMultiplier: 2,
1117
+ maxDelay: 30_000,
1118
+ jitter: 0.2,
1119
+ maxRetryTime: 60_000,
1120
+ status: [0, 408, 429, 500, 502, 503, 504],
1121
+ rules: [],
1122
+ };
1123
+
1124
+ const USE_RETRY = new HttpContextToken(() => null);
1125
+ const RETRY_CONFIG = new InjectionToken('[RETRY_CONFIG]: конфигурация retry-интерсептора', {
1126
+ providedIn: 'root',
1127
+ factory: () => DEFAULT_CONFIG,
1128
+ });
1129
+ function provideRetryConfig(config) {
1130
+ return {
1131
+ provide: RETRY_CONFIG,
1132
+ useFactory: () => ({
1133
+ ...DEFAULT_CONFIG,
1134
+ ...resolveMaybeFn(config),
1135
+ }),
1136
+ };
1137
+ }
1138
+
1139
+ function resolveConfig(request, { rules, ...defaultConfig }) {
1140
+ const requestRetry = request.context.get(USE_RETRY);
1141
+ if (isBoolean(requestRetry)) {
1142
+ return requestRetry ? defaultConfig : null;
1143
+ }
1144
+ if (isPlainObject(requestRetry)) {
1145
+ return { ...defaultConfig, ...requestRetry };
1146
+ }
1147
+ const matchedRule = rules.find((rule) => {
1148
+ if (rule.method !== request.method)
1149
+ return;
1150
+ if (isString(rule.url))
1151
+ return request.url === rule.url;
1152
+ return rule.url.test(request.url);
1153
+ });
1154
+ if (matchedRule) {
1155
+ return { ...defaultConfig, ...matchedRule };
1156
+ }
1157
+ return null;
1158
+ }
1159
+ function resolveRetryAfter(error) {
1160
+ const retryAfter = error.headers.get('Retry-After');
1161
+ if (isNil(retryAfter))
1162
+ return null;
1163
+ if (isNumber(retryAfter)) {
1164
+ return Math.max(0, retryAfter * 1000);
1165
+ }
1166
+ const httpDate = Date.parse(retryAfter);
1167
+ if (isNumber(httpDate)) {
1168
+ return Math.max(0, httpDate - Date.now());
1169
+ }
1170
+ return null;
1171
+ }
1172
+ function shouldRetryStatus(status, retryStatus) {
1173
+ if (isNumber(retryStatus))
1174
+ return status === retryStatus;
1175
+ if (isArray(retryStatus))
1176
+ return retryStatus.includes(status);
1177
+ if (retryStatus instanceof RegExp)
1178
+ return retryStatus.test(String(status));
1179
+ return false;
1180
+ }
1181
+ function computeDelay(config, retryCount) {
1182
+ const initialDelay = Math.max(0, config.delay);
1183
+ const multiplier = config.delayMultiplier;
1184
+ const maxDelay = config.maxDelay;
1185
+ const exponentialDelay = initialDelay * Math.pow(multiplier, Math.max(0, retryCount));
1186
+ const cappedDelay = Math.min(maxDelay, exponentialDelay);
1187
+ const normalizedJitter = Math.min(1, Math.max(0, config.jitter ?? 0));
1188
+ if (normalizedJitter === 0) {
1189
+ return Math.floor(cappedDelay);
1190
+ }
1191
+ const minimumDelay = cappedDelay * (1 - normalizedJitter);
1192
+ const randomizedDelay = minimumDelay + Math.random() * (cappedDelay - minimumDelay);
1193
+ return Math.floor(randomizedDelay);
1194
+ }
1195
+ function applyRetryBudget(delay, startedAt, maxRetryTime) {
1196
+ if (isNil(maxRetryTime))
1197
+ return delay;
1198
+ const elapsedTime = Date.now() - startedAt;
1199
+ const remainingTime = maxRetryTime - elapsedTime;
1200
+ if (remainingTime <= 0) {
1201
+ return null;
1202
+ }
1203
+ return Math.min(delay, remainingTime);
1204
+ }
1205
+ const retryInterceptor = (request, next) => {
1206
+ const config = resolveConfig(request, inject(RETRY_CONFIG));
1207
+ if (isNil(config)) {
1208
+ return next(request);
1209
+ }
1210
+ const startedAt = Date.now();
1211
+ return next(request).pipe(retry({
1212
+ count: config.maxRetries,
1213
+ delay: (error, retryCount) => {
1214
+ if (!isInstance(error, HttpErrorResponse) ||
1215
+ !shouldRetryStatus(error.status, config.status)) {
1216
+ return throwError(() => error);
1217
+ }
1218
+ const delay = resolveRetryAfter(error) ?? computeDelay(config, retryCount - 1);
1219
+ const delayBudget = applyRetryBudget(delay, startedAt, config.maxRetryTime);
1220
+ if (isNil(delayBudget)) {
1221
+ return throwError(() => error);
1222
+ }
1223
+ return timer(delayBudget);
1224
+ },
1225
+ }));
1226
+ };
1227
+
1228
+ const DEFAULT_TIMEOUT_CONFIG = {
1229
+ timeout: 10000,
1230
+ rules: [],
1231
+ message: 'Request Timeout',
1232
+ };
1233
+
1234
+ const USE_TIMEOUT = new HttpContextToken(() => null);
1235
+ const TIMEOUT_CONFIG = new InjectionToken('[TIMEOUT_CONFIG]: глобальная конфигурация timeout интерсептора', {
1236
+ providedIn: 'root',
1237
+ factory: () => DEFAULT_TIMEOUT_CONFIG,
1238
+ });
1239
+ function provideTimeoutConfig(config) {
1240
+ return {
1241
+ provide: TIMEOUT_CONFIG,
1242
+ useFactory: () => ({
1243
+ ...DEFAULT_TIMEOUT_CONFIG,
1244
+ ...resolveMaybeFn(config),
1245
+ }),
1246
+ };
1247
+ }
1248
+
1249
+ function resolveTimeoutConfig(request, { rules, ...defaultConfig }) {
1250
+ const requestTimeout = request.context.get(USE_TIMEOUT);
1251
+ if (isNumber(requestTimeout)) {
1252
+ return { timeout: requestTimeout };
1253
+ }
1254
+ const matchedRule = rules.find((rule) => {
1255
+ if (rule.method !== request.method)
1256
+ return false;
1257
+ if (isString(rule.url))
1258
+ return request.url === rule.url;
1259
+ return rule.url.test(request.url);
1260
+ });
1261
+ if (matchedRule) {
1262
+ return { timeout: matchedRule.timeout ?? defaultConfig.timeout };
1263
+ }
1264
+ return defaultConfig;
1265
+ }
1266
+ const timeoutInterceptor = (request, next) => {
1267
+ if (isNumber(request.timeout)) {
1268
+ return next(request);
1269
+ }
1270
+ const config = inject(TIMEOUT_CONFIG);
1271
+ const resolvedConfig = resolveTimeoutConfig(request, config);
1272
+ if (isNil(resolvedConfig))
1273
+ return next(request);
1274
+ return next(request).pipe(timeout({
1275
+ each: resolvedConfig.timeout,
1276
+ with: () => throwError(() => new HttpErrorResponse({
1277
+ status: 408,
1278
+ url: request.url,
1279
+ error: {
1280
+ success: false,
1281
+ message: config.message,
1282
+ },
1283
+ })),
1284
+ }));
1285
+ };
1286
+
1287
+ /**
1288
+ * Generated bundle index. Do not edit.
1289
+ */
1290
+
1291
+ export { ApiErrorKind, HttpAccessError, HttpApiService, HttpDomainError, HttpNetworkError, HttpNotExistError, HttpTimeoutError, HttpUnauthorizedError, HttpUnknownError, HttpValidationError, ProgressHttpService, USE_HEADERS, USE_LOGGER, USE_PROGRESS, USE_RETRY, USE_TIMEOUT, defineMock, headersInterceptor, httpLogger, isApiError, loggerInterceptor, mockInterceptor, openApiInterceptor, progressInterceptor, provideApiBodyTransform, provideApiOptions, provideApiPrefix, provideHeaders, provideHeadersConfig, provideLoggerConfig, provideLoggerHandler, provideMockConfig, provideOpenApiConfig, provideProgressConfig, provideRetryConfig, provideTimeoutConfig, retryInterceptor, timeoutInterceptor };
1292
+ //# sourceMappingURL=http.mjs.map