@hyperttp/interceptors 1.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -1
- package/index.js +2 -3
- package/index.js.map +7 -1
- package/package.json +10 -2
- package/plugin.d.ts +4 -9
- package/plugin.d.ts.map +1 -1
- package/plugin.js +2 -56
- package/plugin.js.map +7 -1
- package/types/interceptors.d.ts +5 -27
- package/types/interceptors.d.ts.map +1 -1
- package/types/interceptors.js +2 -2
- package/types/interceptors.js.map +7 -1
- package/utils/InterceptorManager.d.ts +4 -72
- package/utils/InterceptorManager.d.ts.map +1 -1
- package/utils/InterceptorManager.js +2 -153
- package/utils/InterceptorManager.js.map +7 -1
package/README.md
CHANGED
|
@@ -1 +1,38 @@
|
|
|
1
|
-
# hyperttp
|
|
1
|
+
# @hyperttp/interceptors
|
|
2
|
+
|
|
3
|
+
> English | [Русский](https://github.com/IT-IF-OR/hyperttp-interceptors/tree/main/lang/ru)
|
|
4
|
+
|
|
5
|
+
Request and response interceptor plugin for Hyperttp.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Runs user-defined handlers around the Core v2 request lifecycle.
|
|
10
|
+
- Supports request, response, and error interception.
|
|
11
|
+
- Uses protocol-neutral `SendRequest`, `UniversalResponse`, and `RequestContext` values.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @hyperttp/interceptors
|
|
17
|
+
# or
|
|
18
|
+
bun add @hyperttp/interceptors
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { HyperClient } from "hyperttp";
|
|
25
|
+
import { withInterceptors } from "@hyperttp/interceptors";
|
|
26
|
+
|
|
27
|
+
const client = new HyperClient({
|
|
28
|
+
plugins: [withInterceptors({
|
|
29
|
+
onRequest: (request) => request,
|
|
30
|
+
})],
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
See the exported `InterceptorsOptions` type for available lifecycle callbacks.
|
|
35
|
+
|
|
36
|
+
## License
|
|
37
|
+
|
|
38
|
+
MIT © dirold2
|
package/index.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
|
|
3
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";export{withInterceptors}from"./plugin.js";export*from"./utils/InterceptorManager.js";
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["export { withInterceptors } from \"./plugin.js\";\nexport * from \"./utils/InterceptorManager.js\";\nexport type * from \"./types/interceptors.js\";\n"],
|
|
5
|
+
"mappings": "aAAA,OAAS,qBAAwB,cACjC,WAAc",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyperttp/interceptors",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./index.d.ts",
|
|
10
|
+
"import": "./index.js",
|
|
11
|
+
"require": "./index.js"
|
|
12
|
+
},
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
7
15
|
"keywords": [
|
|
8
16
|
"hyperttp"
|
|
9
17
|
],
|
|
@@ -14,7 +22,7 @@
|
|
|
14
22
|
"url": "git+https://github.com/IT-IF-OR/hyperttp-interceptors.git"
|
|
15
23
|
},
|
|
16
24
|
"peerDependencies": {
|
|
17
|
-
"@hyperttp/types": "^0.
|
|
25
|
+
"@hyperttp/types": "^0.3.0"
|
|
18
26
|
},
|
|
19
27
|
"private": false
|
|
20
28
|
}
|
package/plugin.d.ts
CHANGED
|
@@ -2,17 +2,12 @@ import type { HyperPlugin } from "@hyperttp/types";
|
|
|
2
2
|
import { InterceptorManager } from "./utils/InterceptorManager.js";
|
|
3
3
|
import type { InterceptorOptions } from "./types/interceptors.js";
|
|
4
4
|
declare module "@hyperttp/types" {
|
|
5
|
+
interface HyperClientOptions {
|
|
6
|
+
interceptors?: InterceptorOptions;
|
|
7
|
+
}
|
|
5
8
|
interface PluginContext {
|
|
6
9
|
interceptors?: InterceptorManager;
|
|
7
10
|
}
|
|
8
|
-
interface HttpClientOptions {
|
|
9
|
-
interceptors?: InterceptorOptions;
|
|
10
|
-
}
|
|
11
11
|
}
|
|
12
|
-
|
|
13
|
-
* @ru Плагин для интеграции кастомных интерцепторов запросов и ответов (Axios-like Interceptors).
|
|
14
|
-
* @en Plugin for integrating custom request and response interceptors (Axios-like Interceptors).
|
|
15
|
-
* @returns HyperPlugin object instance.
|
|
16
|
-
*/
|
|
17
|
-
export declare function withInterceptors(): HyperPlugin;
|
|
12
|
+
export declare function withInterceptors(options?: InterceptorOptions): HyperPlugin;
|
|
18
13
|
//# sourceMappingURL=plugin.d.ts.map
|
package/plugin.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EAMZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EACV,kBAAkB,EAGnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,QAAQ,iBAAiB,CAAC;IAC/B,UAAU,kBAAkB;QAC1B,YAAY,CAAC,EAAE,kBAAkB,CAAC;KACnC;IAED,UAAU,aAAa;QACrB,YAAY,CAAC,EAAE,kBAAkB,CAAC;KACnC;CACF;AAOD,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,WAAW,CA0C1E"}
|
package/plugin.js
CHANGED
|
@@ -1,56 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
* @ru Плагин для интеграции кастомных интерцепторов запросов и ответов (Axios-like Interceptors).
|
|
4
|
-
* @en Plugin for integrating custom request and response interceptors (Axios-like Interceptors).
|
|
5
|
-
* @returns HyperPlugin object instance.
|
|
6
|
-
*/
|
|
7
|
-
export function withInterceptors() {
|
|
8
|
-
let manager;
|
|
9
|
-
return {
|
|
10
|
-
name: "hyperttp-interceptors",
|
|
11
|
-
/**
|
|
12
|
-
* @ru Проверяет активацию плагина на основе переданной конфигурации.
|
|
13
|
-
* @en Evaluates plugin activation based on the provided client configuration.
|
|
14
|
-
*/
|
|
15
|
-
enabled: (config) => !!config.interceptors?.enabled,
|
|
16
|
-
/**
|
|
17
|
-
* @ru Хук инициализации. Создает менеджер интерцепторов и регистрирует его в контексте ядра.
|
|
18
|
-
* @en Initialization hook. Creates the interceptor manager and registers it within the core context.
|
|
19
|
-
* @param core - Shared plugin orchestration context.
|
|
20
|
-
*/
|
|
21
|
-
setup(core) {
|
|
22
|
-
manager = new InterceptorManager();
|
|
23
|
-
core.interceptors = manager;
|
|
24
|
-
},
|
|
25
|
-
/**
|
|
26
|
-
* @ru Перехватчик фазы запроса. Последовательно применяет все зарегистрированные интерцепторы к конфигурации запроса.
|
|
27
|
-
* @en Request phase interceptor hook. Sequentially applies all registered interceptors to the request configuration.
|
|
28
|
-
* @param req - Contextual internal request parameters.
|
|
29
|
-
*/
|
|
30
|
-
async onRequest(req) {
|
|
31
|
-
if (!manager.hasRequest)
|
|
32
|
-
return;
|
|
33
|
-
const reqResult = await manager.applyRequest(req);
|
|
34
|
-
if (reqResult) {
|
|
35
|
-
// Накатываем изменения на текущую ссылку запроса, если интерцептор вернул обновленный объект
|
|
36
|
-
Object.assign(req, reqResult);
|
|
37
|
-
}
|
|
38
|
-
},
|
|
39
|
-
/**
|
|
40
|
-
* @ru Перехватчик фазы успешного ответа. Пропускает объект ответа через цепочку пользовательских интерцепторов модификации.
|
|
41
|
-
* @en Response phase interceptor hook. Passes the response object through the chain of custom modification interceptors.
|
|
42
|
-
* @param res - Output HTTP client response reference.
|
|
43
|
-
* @param req - Contextual internal request parameters.
|
|
44
|
-
*/
|
|
45
|
-
async onResponse(res, req) {
|
|
46
|
-
if (!manager.hasResponse)
|
|
47
|
-
return;
|
|
48
|
-
const resResult = await manager.applyResponse(res);
|
|
49
|
-
if (resResult) {
|
|
50
|
-
// Мутируем объект ответа перед передачей в пользовательский код
|
|
51
|
-
Object.assign(res, resResult);
|
|
52
|
-
}
|
|
53
|
-
},
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
//# sourceMappingURL=plugin.js.map
|
|
1
|
+
"use strict";import{InterceptorManager as o}from"./utils/InterceptorManager.js";function p(n,e){n&&(Array.isArray(n)?n:[n]).forEach(e)}export function withInterceptors(n){let e;return{name:"hyperttp-interceptors",enabled:t=>t.interceptors?.enabled??n?.enabled??n!==void 0,setup(t){e=new o;const s=t.config.interceptors;p(n?.request,r=>e.addRequest(r)),p(n?.response,r=>e.addResponse(r)),p(s?.request,r=>e.addRequest(r)),p(s?.response,r=>e.addResponse(r)),t.interceptors=e},async onRequest(t,s,r){if(e.hasRequest)return e.applyRequest(t,s,r)},async onResponse(t,s,r,a){if(e.hasResponse)return e.applyResponse(t,s,r,a)}}}
|
|
2
|
+
//# sourceMappingURL=plugin.js.map
|
package/plugin.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/plugin.ts"],
|
|
4
|
+
"sourcesContent": ["import type {\n HyperPlugin,\n HyperClientOptions,\n UniversalResponse,\n PluginContext,\n SendRequest,\n RequestContext,\n} from \"@hyperttp/types\";\nimport { InterceptorManager } from \"./utils/InterceptorManager.js\";\nimport type {\n InterceptorOptions,\n RequestInterceptor,\n ResponseInterceptor,\n} from \"./types/interceptors.js\";\n\ndeclare module \"@hyperttp/types\" {\n interface HyperClientOptions {\n interceptors?: InterceptorOptions;\n }\n\n interface PluginContext {\n interceptors?: InterceptorManager;\n }\n}\n\nfunction register<T>(value: T | readonly T[] | undefined, add: (interceptor: T) => void): void {\n if (!value) return;\n (Array.isArray(value) ? value : [value]).forEach(add);\n}\n\nexport function withInterceptors(options?: InterceptorOptions): HyperPlugin {\n let manager: InterceptorManager;\n\n return {\n name: \"hyperttp-interceptors\",\n enabled: (config: HyperClientOptions): boolean =>\n config.interceptors?.enabled ?? options?.enabled ?? options !== undefined,\n setup(ctx: PluginContext): void {\n manager = new InterceptorManager();\n const configured = ctx.config.interceptors;\n register<RequestInterceptor>(options?.request, (interceptor) =>\n manager.addRequest(interceptor),\n );\n register<ResponseInterceptor>(options?.response, (interceptor) =>\n manager.addResponse(interceptor),\n );\n register<RequestInterceptor>(configured?.request, (interceptor) =>\n manager.addRequest(interceptor),\n );\n register<ResponseInterceptor>(configured?.response, (interceptor) =>\n manager.addResponse(interceptor),\n );\n ctx.interceptors = manager;\n },\n async onRequest(\n req: SendRequest,\n ctx?: PluginContext,\n reqCtx?: RequestContext,\n ): Promise<SendRequest | void> {\n if (!manager.hasRequest) return;\n return manager.applyRequest(req, ctx, reqCtx);\n },\n async onResponse(\n res: UniversalResponse,\n req?: SendRequest,\n ctx?: PluginContext,\n reqCtx?: RequestContext,\n ): Promise<UniversalResponse | void> {\n if (!manager.hasResponse) return;\n return manager.applyResponse(res, req, ctx, reqCtx);\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "aAQA,OAAS,sBAAAA,MAA0B,gCAiBnC,SAASC,EAAYC,EAAqCC,EAA6B,CAChFD,IACJ,MAAM,QAAQA,CAAK,EAAIA,EAAQ,CAACA,CAAK,GAAG,QAAQC,CAAG,CACtD,CAEM,gBAAU,iBAAiBC,EAA4B,CAC3D,IAAIC,EAEJ,MAAO,CACL,KAAM,wBACN,QAAUC,GACRA,EAAO,cAAc,SAAWF,GAAS,SAAWA,IAAY,OAClE,MAAMG,EAAkB,CACtBF,EAAU,IAAIL,EACd,MAAMQ,EAAaD,EAAI,OAAO,aAC9BN,EAA6BG,GAAS,QAAUK,GAC9CJ,EAAQ,WAAWI,CAAW,CAAC,EAEjCR,EAA8BG,GAAS,SAAWK,GAChDJ,EAAQ,YAAYI,CAAW,CAAC,EAElCR,EAA6BO,GAAY,QAAUC,GACjDJ,EAAQ,WAAWI,CAAW,CAAC,EAEjCR,EAA8BO,GAAY,SAAWC,GACnDJ,EAAQ,YAAYI,CAAW,CAAC,EAElCF,EAAI,aAAeF,CACrB,EACA,MAAM,UACJK,EACAH,EACAI,EAAuB,CAEvB,GAAKN,EAAQ,WACb,OAAOA,EAAQ,aAAaK,EAAKH,EAAKI,CAAM,CAC9C,EACA,MAAM,WACJC,EACAF,EACAH,EACAI,EAAuB,CAEvB,GAAKN,EAAQ,YACb,OAAOA,EAAQ,cAAcO,EAAKF,EAAKH,EAAKI,CAAM,CACpD,EAEJ",
|
|
6
|
+
"names": ["InterceptorManager", "register", "value", "add", "options", "manager", "config", "ctx", "configured", "interceptor", "req", "reqCtx", "res"]
|
|
7
|
+
}
|
package/types/interceptors.d.ts
CHANGED
|
@@ -1,31 +1,9 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
/**
|
|
3
|
-
* @ru Опции конфигурации для плагина интерцепторов.
|
|
4
|
-
* @en Configuration options for the interceptors plugin.
|
|
5
|
-
*/
|
|
1
|
+
import type { PluginContext, RequestContext, SendRequest, UniversalResponse } from "@hyperttp/types";
|
|
6
2
|
export interface InterceptorOptions {
|
|
7
|
-
/**
|
|
8
|
-
* @ru Включить обработку интерцепторов для клиента.
|
|
9
|
-
* @en Enable interceptor processing for the client.
|
|
10
|
-
*/
|
|
11
3
|
enabled?: boolean;
|
|
4
|
+
request?: RequestInterceptor | readonly RequestInterceptor[];
|
|
5
|
+
response?: ResponseInterceptor | readonly ResponseInterceptor[];
|
|
12
6
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
* Принимает внутренний объект запроса ядра. Может вернуть модифицированный объект
|
|
16
|
-
* или `void` (если изменения вносятся напрямую в переданный объект по ссылке).
|
|
17
|
-
* * @en Request interceptor.
|
|
18
|
-
* Accepts the core internal request object. Can return a modified configuration
|
|
19
|
-
* or `void` (if modifications are applied directly to the passed object reference).
|
|
20
|
-
*/
|
|
21
|
-
export type RequestInterceptor = (config: InternalRequest) => InternalRequest | void | Promise<InternalRequest | void>;
|
|
22
|
-
/**
|
|
23
|
-
* @ru Перехватчик ответа.
|
|
24
|
-
* Принимает объект ответа с любым типом тела (`HttpResponse<any>`). Может вернуть
|
|
25
|
-
* трансформированный объект ответа или `void` (если объект мутирует по ссылке).
|
|
26
|
-
* * @en Response interceptor.
|
|
27
|
-
* Accepts a response object with any body layout (`HttpResponse<any>`). Can return
|
|
28
|
-
* a transformed response container or `void` (if the object is mutated in-place).
|
|
29
|
-
*/
|
|
30
|
-
export type ResponseInterceptor = (response: HttpResponse<any>) => HttpResponse<any> | void | Promise<HttpResponse<any> | void>;
|
|
7
|
+
export type RequestInterceptor = (request: SendRequest, context?: PluginContext, requestContext?: RequestContext) => SendRequest | void | Promise<SendRequest | void>;
|
|
8
|
+
export type ResponseInterceptor = (response: UniversalResponse, request?: SendRequest, context?: PluginContext, requestContext?: RequestContext) => UniversalResponse | void | Promise<UniversalResponse | void>;
|
|
31
9
|
//# sourceMappingURL=interceptors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interceptors.d.ts","sourceRoot":"","sources":["../../src/types/interceptors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"interceptors.d.ts","sourceRoot":"","sources":["../../src/types/interceptors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,WAAW,EACX,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,kBAAkB;IACjC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,kBAAkB,GAAG,SAAS,kBAAkB,EAAE,CAAC;IAC7D,QAAQ,CAAC,EAAE,mBAAmB,GAAG,SAAS,mBAAmB,EAAE,CAAC;CACjE;AAED,MAAM,MAAM,kBAAkB,GAAG,CAC/B,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,KAC5B,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;AAEtD,MAAM,MAAM,mBAAmB,GAAG,CAChC,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,CAAC,EAAE,WAAW,EACrB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,KAC5B,iBAAiB,GAAG,IAAI,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAAC"}
|
package/types/interceptors.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
//# sourceMappingURL=interceptors.js.map
|
|
1
|
+
"use strict";export{};
|
|
2
|
+
//# sourceMappingURL=interceptors.js.map
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["interceptors.js"],
|
|
4
|
+
"sourcesContent": ["export {};\n//# sourceMappingURL=interceptors.js.map"],
|
|
5
|
+
"mappings": "aAAA",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,84 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { RequestInterceptor, ResponseInterceptor } from "../types/interceptors.js";
|
|
3
|
-
/**
|
|
4
|
-
* @ru Менеджер перехватчиков (интерцепторов) для сквозной обработки запросов и ответов.
|
|
5
|
-
* Использует гибридный цикл (fast-path): выполняется синхронно до тех пор, пока не встретит Promise.
|
|
6
|
-
* @en Interceptor manager for pipeline execution of requests and responses.
|
|
7
|
-
* Uses a hybrid loop (fast-path): runs synchronously until a Promise is encountered.
|
|
8
|
-
*/
|
|
1
|
+
import type { PluginContext, RequestContext, SendRequest, UniversalResponse } from "@hyperttp/types";
|
|
2
|
+
import type { RequestInterceptor, ResponseInterceptor } from "../types/interceptors.js";
|
|
9
3
|
export declare class InterceptorManager {
|
|
10
|
-
/**
|
|
11
|
-
* @private
|
|
12
|
-
* @ru Массив зарегистрированных перехватчиков запроса.
|
|
13
|
-
* @en Array of registered request interceptors.
|
|
14
|
-
*/
|
|
15
4
|
private requestInterceptors;
|
|
16
|
-
/**
|
|
17
|
-
* @private
|
|
18
|
-
* @ru Массив зарегистрированных перехватчиков ответа.
|
|
19
|
-
* @en Array of registered response interceptors.
|
|
20
|
-
*/
|
|
21
5
|
private responseInterceptors;
|
|
22
|
-
/**
|
|
23
|
-
* @ru Флаг наличия активных перехватчиков запроса для быстрого ветвления.
|
|
24
|
-
* @en Flag indicating presence of active request interceptors for fast branch short-circuiting.
|
|
25
|
-
*/
|
|
26
6
|
hasRequest: boolean;
|
|
27
|
-
/**
|
|
28
|
-
* @ru Флаг наличия активных перехватчиков ответа для быстрого ветвления.
|
|
29
|
-
* @en Flag indicating presence of active response interceptors for fast branch short-circuiting.
|
|
30
|
-
*/
|
|
31
7
|
hasResponse: boolean;
|
|
32
|
-
/**
|
|
33
|
-
* @ru Регистрирует новый перехватчик запроса в конвейере.
|
|
34
|
-
* @en Registers a new request interceptor in the pipeline.
|
|
35
|
-
* @param interceptor - Target request interceptor function.
|
|
36
|
-
*/
|
|
37
8
|
addRequest(interceptor: RequestInterceptor): void;
|
|
38
|
-
/**
|
|
39
|
-
* @ru Регистрирует новый перехватчик ответа в конвейере.
|
|
40
|
-
* @en Registers a new response interceptor in the pipeline.
|
|
41
|
-
* @param interceptor - Target response interceptor function.
|
|
42
|
-
*/
|
|
43
9
|
addResponse(interceptor: ResponseInterceptor): void;
|
|
44
|
-
|
|
45
|
-
* @ru Последовательно применяет цепочку перехватчиков к конфигурации запроса.
|
|
46
|
-
* @en Sequentially applies the chain of interceptors to the request configuration.
|
|
47
|
-
* @param config - Initial internal request configuration object.
|
|
48
|
-
* @returns Modified configuration or a Promise resolving to it.
|
|
49
|
-
*/
|
|
50
|
-
applyRequest(config: InternalRequest): InternalRequest | Promise<InternalRequest>;
|
|
51
|
-
/**
|
|
52
|
-
* @private
|
|
53
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки запросов после обнаружения Promise.
|
|
54
|
-
* @en Asynchronous fallback to process the remaining request chain after encountering a Promise.
|
|
55
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
56
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
57
|
-
* @param currentResult - Cumulative configuration result before the Promise step.
|
|
58
|
-
*/
|
|
10
|
+
applyRequest(request: SendRequest, context?: PluginContext, requestContext?: RequestContext): SendRequest | Promise<SendRequest>;
|
|
59
11
|
private applyRequestAsync;
|
|
60
|
-
|
|
61
|
-
* @ru Последовательно применяет цепочку перехватчиков к полученному объекту ответа.
|
|
62
|
-
* @en Sequentially applies the chain of interceptors to the incoming response container.
|
|
63
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
64
|
-
* @param response - Target HTTP response context wrapper.
|
|
65
|
-
* @returns Transformed response context or a Promise resolving to it.
|
|
66
|
-
*/
|
|
67
|
-
applyResponse<T = unknown>(response: HttpResponse<T>): HttpResponse<T> | Promise<HttpResponse<T>>;
|
|
68
|
-
/**
|
|
69
|
-
* @private
|
|
70
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки ответов после обнаружения Promise.
|
|
71
|
-
* @en Asynchronous fallback to process the remaining response chain after encountering a Promise.
|
|
72
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
73
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
74
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
75
|
-
* @param currentResult - Cumulative response result before the Promise step.
|
|
76
|
-
*/
|
|
12
|
+
applyResponse(response: UniversalResponse, request?: SendRequest, context?: PluginContext, requestContext?: RequestContext): UniversalResponse | Promise<UniversalResponse>;
|
|
77
13
|
private applyResponseAsync;
|
|
78
|
-
/**
|
|
79
|
-
* @ru Полностью очищает списки зарегистрированных перехватчиков и сбрасывает флаги.
|
|
80
|
-
* @en Completely flushes internal interceptor registers and resets state indicators.
|
|
81
|
-
*/
|
|
82
14
|
clear(): void;
|
|
83
15
|
}
|
|
84
16
|
//# sourceMappingURL=InterceptorManager.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InterceptorManager.d.ts","sourceRoot":"","sources":["../../src/utils/InterceptorManager.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"InterceptorManager.d.ts","sourceRoot":"","sources":["../../src/utils/InterceptorManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,WAAW,EACX,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAExF,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,mBAAmB,CAA4B;IACvD,OAAO,CAAC,oBAAoB,CAA6B;IAClD,UAAU,UAAS;IACnB,WAAW,UAAS;IAE3B,UAAU,CAAC,WAAW,EAAE,kBAAkB,GAAG,IAAI,CAGhD;IAED,WAAW,CAAC,WAAW,EAAE,mBAAmB,GAAG,IAAI,CAGlD;IAED,YAAY,CACV,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,GAC9B,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,CAUpC;YAEa,iBAAiB;IAe/B,aAAa,CACX,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,CAAC,EAAE,WAAW,EACrB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,GAC9B,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAiBhD;YAEa,kBAAkB;IAgBhC,KAAK,IAAI,IAAI,CAKZ;CACF"}
|
|
@@ -1,153 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Использует гибридный цикл (fast-path): выполняется синхронно до тех пор, пока не встретит Promise.
|
|
4
|
-
* @en Interceptor manager for pipeline execution of requests and responses.
|
|
5
|
-
* Uses a hybrid loop (fast-path): runs synchronously until a Promise is encountered.
|
|
6
|
-
*/
|
|
7
|
-
export class InterceptorManager {
|
|
8
|
-
/**
|
|
9
|
-
* @private
|
|
10
|
-
* @ru Массив зарегистрированных перехватчиков запроса.
|
|
11
|
-
* @en Array of registered request interceptors.
|
|
12
|
-
*/
|
|
13
|
-
requestInterceptors = [];
|
|
14
|
-
/**
|
|
15
|
-
* @private
|
|
16
|
-
* @ru Массив зарегистрированных перехватчиков ответа.
|
|
17
|
-
* @en Array of registered response interceptors.
|
|
18
|
-
*/
|
|
19
|
-
responseInterceptors = [];
|
|
20
|
-
/**
|
|
21
|
-
* @ru Флаг наличия активных перехватчиков запроса для быстрого ветвления.
|
|
22
|
-
* @en Flag indicating presence of active request interceptors for fast branch short-circuiting.
|
|
23
|
-
*/
|
|
24
|
-
hasRequest = false;
|
|
25
|
-
/**
|
|
26
|
-
* @ru Флаг наличия активных перехватчиков ответа для быстрого ветвления.
|
|
27
|
-
* @en Flag indicating presence of active response interceptors for fast branch short-circuiting.
|
|
28
|
-
*/
|
|
29
|
-
hasResponse = false;
|
|
30
|
-
/**
|
|
31
|
-
* @ru Регистрирует новый перехватчик запроса в конвейере.
|
|
32
|
-
* @en Registers a new request interceptor in the pipeline.
|
|
33
|
-
* @param interceptor - Target request interceptor function.
|
|
34
|
-
*/
|
|
35
|
-
addRequest(interceptor) {
|
|
36
|
-
this.requestInterceptors.push(interceptor);
|
|
37
|
-
this.hasRequest = true;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* @ru Регистрирует новый перехватчик ответа в конвейере.
|
|
41
|
-
* @en Registers a new response interceptor in the pipeline.
|
|
42
|
-
* @param interceptor - Target response interceptor function.
|
|
43
|
-
*/
|
|
44
|
-
addResponse(interceptor) {
|
|
45
|
-
this.responseInterceptors.push(interceptor);
|
|
46
|
-
this.hasResponse = true;
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* @ru Последовательно применяет цепочку перехватчиков к конфигурации запроса.
|
|
50
|
-
* @en Sequentially applies the chain of interceptors to the request configuration.
|
|
51
|
-
* @param config - Initial internal request configuration object.
|
|
52
|
-
* @returns Modified configuration or a Promise resolving to it.
|
|
53
|
-
*/
|
|
54
|
-
applyRequest(config) {
|
|
55
|
-
let result = config;
|
|
56
|
-
const len = this.requestInterceptors.length;
|
|
57
|
-
for (let i = 0; i < len; i++) {
|
|
58
|
-
const nextConfig = this.requestInterceptors[i](result);
|
|
59
|
-
if (nextConfig instanceof Promise) {
|
|
60
|
-
return this.applyRequestAsync(i, nextConfig, result);
|
|
61
|
-
}
|
|
62
|
-
if (nextConfig)
|
|
63
|
-
result = nextConfig;
|
|
64
|
-
}
|
|
65
|
-
return result;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* @private
|
|
69
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки запросов после обнаружения Promise.
|
|
70
|
-
* @en Asynchronous fallback to process the remaining request chain after encountering a Promise.
|
|
71
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
72
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
73
|
-
* @param currentResult - Cumulative configuration result before the Promise step.
|
|
74
|
-
*/
|
|
75
|
-
async applyRequestAsync(startIndex, currentPromise, currentResult) {
|
|
76
|
-
let result = currentResult;
|
|
77
|
-
const resolved = await currentPromise;
|
|
78
|
-
if (resolved)
|
|
79
|
-
result = resolved;
|
|
80
|
-
const len = this.requestInterceptors.length;
|
|
81
|
-
for (let i = startIndex + 1; i < len; i++) {
|
|
82
|
-
const nextConfig = this.requestInterceptors[i](result);
|
|
83
|
-
if (nextConfig instanceof Promise) {
|
|
84
|
-
const res = await nextConfig;
|
|
85
|
-
if (res)
|
|
86
|
-
result = res;
|
|
87
|
-
}
|
|
88
|
-
else if (nextConfig) {
|
|
89
|
-
result = nextConfig;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return result;
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* @ru Последовательно применяет цепочку перехватчиков к полученному объекту ответа.
|
|
96
|
-
* @en Sequentially applies the chain of interceptors to the incoming response container.
|
|
97
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
98
|
-
* @param response - Target HTTP response context wrapper.
|
|
99
|
-
* @returns Transformed response context or a Promise resolving to it.
|
|
100
|
-
*/
|
|
101
|
-
applyResponse(response) {
|
|
102
|
-
let result = response;
|
|
103
|
-
const len = this.responseInterceptors.length;
|
|
104
|
-
for (let i = 0; i < len; i++) {
|
|
105
|
-
const nextResponse = this.responseInterceptors[i](result);
|
|
106
|
-
if (nextResponse instanceof Promise) {
|
|
107
|
-
return this.applyResponseAsync(i, nextResponse, result);
|
|
108
|
-
}
|
|
109
|
-
if (nextResponse)
|
|
110
|
-
result = nextResponse;
|
|
111
|
-
}
|
|
112
|
-
return result;
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* @private
|
|
116
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки ответов после обнаружения Promise.
|
|
117
|
-
* @en Asynchronous fallback to process the remaining response chain after encountering a Promise.
|
|
118
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
119
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
120
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
121
|
-
* @param currentResult - Cumulative response result before the Promise step.
|
|
122
|
-
*/
|
|
123
|
-
async applyResponseAsync(startIndex, currentPromise, currentResult) {
|
|
124
|
-
let result = currentResult;
|
|
125
|
-
const resolved = await currentPromise;
|
|
126
|
-
if (resolved)
|
|
127
|
-
result = resolved;
|
|
128
|
-
const len = this.responseInterceptors.length;
|
|
129
|
-
for (let i = startIndex + 1; i < len; i++) {
|
|
130
|
-
const nextResponse = this.responseInterceptors[i](result);
|
|
131
|
-
if (nextResponse instanceof Promise) {
|
|
132
|
-
const res = await nextResponse;
|
|
133
|
-
if (res)
|
|
134
|
-
result = res;
|
|
135
|
-
}
|
|
136
|
-
else if (nextResponse) {
|
|
137
|
-
result = nextResponse;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
return result;
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* @ru Полностью очищает списки зарегистрированных перехватчиков и сбрасывает флаги.
|
|
144
|
-
* @en Completely flushes internal interceptor registers and resets state indicators.
|
|
145
|
-
*/
|
|
146
|
-
clear() {
|
|
147
|
-
this.requestInterceptors = [];
|
|
148
|
-
this.responseInterceptors = [];
|
|
149
|
-
this.hasRequest = false;
|
|
150
|
-
this.hasResponse = false;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
//# sourceMappingURL=InterceptorManager.js.map
|
|
1
|
+
"use strict";export class InterceptorManager{requestInterceptors=[];responseInterceptors=[];hasRequest=!1;hasResponse=!1;addRequest(r){this.requestInterceptors.push(r),this.hasRequest=!0}addResponse(r){this.responseInterceptors.push(r),this.hasResponse=!0}applyRequest(r,p,o){let n=r;for(let s=0;s<this.requestInterceptors.length;s++){const e=this.requestInterceptors[s](n,p,o);if(e instanceof Promise)return this.applyRequestAsync(s+1,e,n,p,o);e&&(n=e)}return n}async applyRequestAsync(r,p,o,n,s){let e=await p??o;for(let t=r;t<this.requestInterceptors.length;t++){const i=this.requestInterceptors[t](e,n,s);e=(i instanceof Promise?await i:i)??e}return e}applyResponse(r,p,o,n){let s=r;for(let e=0;e<this.responseInterceptors.length;e++){const t=this.responseInterceptors[e](s,p,o,n);if(t instanceof Promise)return this.applyResponseAsync(e+1,t,s,p,o,n);t&&(s=t)}return s}async applyResponseAsync(r,p,o,n,s,e){let t=await p??o;for(let i=r;i<this.responseInterceptors.length;i++){const a=this.responseInterceptors[i](t,n,s,e);t=(a instanceof Promise?await a:a)??t}return t}clear(){this.requestInterceptors=[],this.responseInterceptors=[],this.hasRequest=!1,this.hasResponse=!1}}
|
|
2
|
+
//# sourceMappingURL=InterceptorManager.js.map
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/InterceptorManager.ts"],
|
|
4
|
+
"sourcesContent": ["import type {\n PluginContext,\n RequestContext,\n SendRequest,\n UniversalResponse,\n} from \"@hyperttp/types\";\nimport type { RequestInterceptor, ResponseInterceptor } from \"../types/interceptors.js\";\n\nexport class InterceptorManager {\n private requestInterceptors: RequestInterceptor[] = [];\n private responseInterceptors: ResponseInterceptor[] = [];\n public hasRequest = false;\n public hasResponse = false;\n\n addRequest(interceptor: RequestInterceptor): void {\n this.requestInterceptors.push(interceptor);\n this.hasRequest = true;\n }\n\n addResponse(interceptor: ResponseInterceptor): void {\n this.responseInterceptors.push(interceptor);\n this.hasResponse = true;\n }\n\n applyRequest(\n request: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): SendRequest | Promise<SendRequest> {\n let result = request;\n for (let i = 0; i < this.requestInterceptors.length; i++) {\n const next = this.requestInterceptors[i](result, context, requestContext);\n if (next instanceof Promise) {\n return this.applyRequestAsync(i + 1, next, result, context, requestContext);\n }\n if (next) result = next;\n }\n return result;\n }\n\n private async applyRequestAsync(\n startIndex: number,\n currentPromise: Promise<SendRequest | void>,\n currentResult: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): Promise<SendRequest> {\n let result = (await currentPromise) ?? currentResult;\n for (let i = startIndex; i < this.requestInterceptors.length; i++) {\n const next = this.requestInterceptors[i](result, context, requestContext);\n result = (next instanceof Promise ? await next : next) ?? result;\n }\n return result;\n }\n\n applyResponse(\n response: UniversalResponse,\n request?: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): UniversalResponse | Promise<UniversalResponse> {\n let result = response;\n for (let i = 0; i < this.responseInterceptors.length; i++) {\n const nextResponse = this.responseInterceptors[i](result, request, context, requestContext);\n if (nextResponse instanceof Promise) {\n return this.applyResponseAsync(\n i + 1,\n nextResponse,\n result,\n request,\n context,\n requestContext,\n );\n }\n if (nextResponse) result = nextResponse;\n }\n return result;\n }\n\n private async applyResponseAsync(\n startIndex: number,\n currentPromise: Promise<UniversalResponse | void>,\n currentResult: UniversalResponse,\n request?: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): Promise<UniversalResponse> {\n let result = (await currentPromise) ?? currentResult;\n for (let i = startIndex; i < this.responseInterceptors.length; i++) {\n const nextResponse = this.responseInterceptors[i](result, request, context, requestContext);\n result = (nextResponse instanceof Promise ? await nextResponse : nextResponse) ?? result;\n }\n return result;\n }\n\n clear(): void {\n this.requestInterceptors = [];\n this.responseInterceptors = [];\n this.hasRequest = false;\n this.hasResponse = false;\n }\n}\n"],
|
|
5
|
+
"mappings": "aAQM,aAAO,kBAAkB,CACrB,oBAA4C,CAAA,EAC5C,qBAA8C,CAAA,EAC/C,WAAa,GACb,YAAc,GAErB,WAAWA,EAA+B,CACxC,KAAK,oBAAoB,KAAKA,CAAW,EACzC,KAAK,WAAa,EACpB,CAEA,YAAYA,EAAgC,CAC1C,KAAK,qBAAqB,KAAKA,CAAW,EAC1C,KAAK,YAAc,EACrB,CAEA,aACEC,EACAC,EACAC,EAA+B,CAE/B,IAAIC,EAASH,EACb,QAASI,EAAI,EAAGA,EAAI,KAAK,oBAAoB,OAAQA,IAAK,CACxD,MAAMC,EAAO,KAAK,oBAAoBD,CAAC,EAAED,EAAQF,EAASC,CAAc,EACxE,GAAIG,aAAgB,QAClB,OAAO,KAAK,kBAAkBD,EAAI,EAAGC,EAAMF,EAAQF,EAASC,CAAc,EAExEG,IAAMF,EAASE,EACrB,CACA,OAAOF,CACT,CAEQ,MAAM,kBACZG,EACAC,EACAC,EACAP,EACAC,EAA+B,CAE/B,IAAIC,EAAU,MAAMI,GAAmBC,EACvC,QAASJ,EAAIE,EAAYF,EAAI,KAAK,oBAAoB,OAAQA,IAAK,CACjE,MAAMC,EAAO,KAAK,oBAAoBD,CAAC,EAAED,EAAQF,EAASC,CAAc,EACxEC,GAAUE,aAAgB,QAAU,MAAMA,EAAOA,IAASF,CAC5D,CACA,OAAOA,CACT,CAEA,cACEM,EACAT,EACAC,EACAC,EAA+B,CAE/B,IAAIC,EAASM,EACb,QAASL,EAAI,EAAGA,EAAI,KAAK,qBAAqB,OAAQA,IAAK,CACzD,MAAMM,EAAe,KAAK,qBAAqBN,CAAC,EAAED,EAAQH,EAASC,EAASC,CAAc,EAC1F,GAAIQ,aAAwB,QAC1B,OAAO,KAAK,mBACVN,EAAI,EACJM,EACAP,EACAH,EACAC,EACAC,CAAc,EAGdQ,IAAcP,EAASO,EAC7B,CACA,OAAOP,CACT,CAEQ,MAAM,mBACZG,EACAC,EACAC,EACAR,EACAC,EACAC,EAA+B,CAE/B,IAAIC,EAAU,MAAMI,GAAmBC,EACvC,QAAS,EAAIF,EAAY,EAAI,KAAK,qBAAqB,OAAQ,IAAK,CAClE,MAAMI,EAAe,KAAK,qBAAqB,CAAC,EAAEP,EAAQH,EAASC,EAASC,CAAc,EAC1FC,GAAUO,aAAwB,QAAU,MAAMA,EAAeA,IAAiBP,CACpF,CACA,OAAOA,CACT,CAEA,OAAK,CACH,KAAK,oBAAsB,CAAA,EAC3B,KAAK,qBAAuB,CAAA,EAC5B,KAAK,WAAa,GAClB,KAAK,YAAc,EACrB",
|
|
6
|
+
"names": ["interceptor", "request", "context", "requestContext", "result", "i", "next", "startIndex", "currentPromise", "currentResult", "response", "nextResponse"]
|
|
7
|
+
}
|