@ahoo-wang/fetcher-decorator 1.6.0 → 1.6.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.
- package/dist/apiDecorator.d.ts +1 -2
- package/dist/apiDecorator.d.ts.map +1 -1
- package/dist/endpointDecorator.d.ts +1 -2
- package/dist/endpointDecorator.d.ts.map +1 -1
- package/dist/functionMetadata.d.ts +1 -1
- package/dist/functionMetadata.d.ts.map +1 -1
- package/dist/index.es.js +113 -117
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/resultExtractor.d.ts +7 -15
- package/dist/resultExtractor.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/apiDecorator.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { AttributesCapable, Fetcher, RequestHeaders, RequestHeadersCapable, TimeoutCapable } from '@ahoo-wang/fetcher';
|
|
2
|
-
import { ResultExtractorCapable } from './resultExtractor';
|
|
1
|
+
import { AttributesCapable, Fetcher, RequestHeaders, RequestHeadersCapable, ResultExtractorCapable, TimeoutCapable } from '@ahoo-wang/fetcher';
|
|
3
2
|
import { FetcherCapable } from './fetcherCapable';
|
|
4
3
|
/**
|
|
5
4
|
* Metadata for class-level API configuration.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiDecorator.d.ts","sourceRoot":"","sources":["../src/apiDecorator.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,KAAK,iBAAiB,EACtB,OAAO,EACP,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,cAAc,EACpB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,KAAK,
|
|
1
|
+
{"version":3,"file":"apiDecorator.d.ts","sourceRoot":"","sources":["../src/apiDecorator.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,KAAK,iBAAiB,EACtB,OAAO,EACP,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,KAAK,cAAc,EACpB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGvD;;;;;;GAMG;AACH,MAAM,WAAW,WACf,SAAQ,cAAc,EACpB,qBAAqB,EACrB,sBAAsB,EACtB,cAAc,EAAE,iBAAiB;IACnC;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,cAAc,CAAC;IAEzB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CAC5B;AAED,eAAO,MAAM,gBAAgB,eAAyB,CAAC;AAwDvD,wBAAgB,GAAG,CACjB,QAAQ,GAAE,MAAW,EACrB,QAAQ,GAAE,IAAI,CAAC,WAAW,EAAE,UAAU,CAAM,IAE3B,CAAC,SAAS,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAAE,aAAa,CAAC,KAAG,CAAC,CAgB3E"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { HttpMethod } from '@ahoo-wang/fetcher';
|
|
1
|
+
import { HttpMethod, ResultExtractorCapable } from '@ahoo-wang/fetcher';
|
|
2
2
|
import { ApiMetadata } from './apiDecorator';
|
|
3
|
-
import { ResultExtractorCapable } from './resultExtractor';
|
|
4
3
|
export interface PathCapable {
|
|
5
4
|
/**
|
|
6
5
|
* Path for the endpoint (relative to class base path).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpointDecorator.d.ts","sourceRoot":"","sources":["../src/endpointDecorator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":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,GAAE,sBAA2B,YA5BlD,MAAM,eAAe,MAAM,GAAG,MAAM,KAAG,IAAI,CA8BpE;AAED,wBAAgB,KAAK,CACnB,IAAI,GAAE,MAAW,EACjB,QAAQ,GAAE,sBAA2B,YAlCb,MAAM,eAAe,MAAM,GAAG,MAAM,KAAG,IAAI,CAqCpE;AAED,wBAAgB,IAAI,CAAC,IAAI,GAAE,MAAW,EAAE,QAAQ,GAAE,sBAA2B,YAvCnD,MAAM,eAAe,MAAM,GAAG,MAAM,KAAG,IAAI,CAyCpE;AAED,wBAAgB,OAAO,CACrB,IAAI,GAAE,MAAW,EACjB,QAAQ,GAAE,sBAA2B,YA7Cb,MAAM,eAAe,MAAM,GAAG,MAAM,KAAG,IAAI,CAgDpE"}
|
|
@@ -69,7 +69,7 @@ export declare class FunctionMetadata implements NamedCapable {
|
|
|
69
69
|
*/
|
|
70
70
|
resolveTimeout(): number | undefined;
|
|
71
71
|
resolveResultExtractor(): ResultExtractor<any>;
|
|
72
|
-
resolveAttributes():
|
|
72
|
+
resolveAttributes(): Map<string, any>;
|
|
73
73
|
/**
|
|
74
74
|
* Resolves the request configuration from the method arguments.
|
|
75
75
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functionMetadata.d.ts","sourceRoot":"","sources":["../src/functionMetadata.ts"],"names":[],"mappings":"AAaA,OAAO,EAEL,OAAO,EACP,KAAK,iBAAiB,EAGtB,YAAY,EAEZ,eAAe,EAEhB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAmC,MAAM,sBAAsB,CAAC;AAI1F;;;;;;GAMG;AACH,qBAAa,gBAAiB,YAAW,YAAY;IACnD;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,GAAG,EAAE,WAAW,CAAC;IAEjB;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gB,EAC1B,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC;IAQ5C;;;;;;;OAOG;IACH,IAAI,OAAO,IAAI,OAAO,CAErB;IAED;;;;;OAKG;IACH,WAAW,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM;IAW3C;;;;;;;OAOG;IACH,cAAc,IAAI,MAAM,GAAG,SAAS;IAIpC,sBAAsB,IAAI,eAAe,CAAC,GAAG,CAAC;IAQ9C,iBAAiB,IAAI,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC;IAKrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6CG;IACH,mBAAmB,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,QAAQ,CAAC,IAAI,CAAC,iBAAiB,EAAE,SAAS,GAAG,YAAY,CAAC,CAAC;IA2E7F,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,kBAAkB;IAU1B;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,OAAO,CAAC,mBAAmB;IAe3B,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,sBAAsB;CAU/B"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { HttpMethod as u, Fetcher as
|
|
1
|
+
import { HttpMethod as u, Fetcher as x, fetcherRegistrar as D, JsonResultExtractor as T, TextResultExtractor as I, ResponseResultExtractor as O, ExchangeResultExtractor as w, fetcher as U, combineURLs as v, mergeRecordToMap as b, mergeRequest as S } from "@ahoo-wang/fetcher";
|
|
2
2
|
import "reflect-metadata";
|
|
3
|
-
import { JsonEventStreamResultExtractor as
|
|
4
|
-
const
|
|
3
|
+
import { JsonEventStreamResultExtractor as H, EventStreamResultExtractor as F } from "@ahoo-wang/fetcher-eventstream";
|
|
4
|
+
const g = Symbol("endpoint:metadata");
|
|
5
5
|
function h(t, e, r = {}) {
|
|
6
6
|
return function(n, a) {
|
|
7
7
|
const s = {
|
|
@@ -10,36 +10,36 @@ function h(t, e, r = {}) {
|
|
|
10
10
|
...r
|
|
11
11
|
};
|
|
12
12
|
Reflect.defineMetadata(
|
|
13
|
-
|
|
13
|
+
g,
|
|
14
14
|
s,
|
|
15
15
|
n,
|
|
16
16
|
a
|
|
17
17
|
);
|
|
18
18
|
};
|
|
19
19
|
}
|
|
20
|
-
function
|
|
20
|
+
function st(t = "", e = {}) {
|
|
21
21
|
return h(u.GET, t, e);
|
|
22
22
|
}
|
|
23
|
-
function
|
|
23
|
+
function ot(t = "", e = {}) {
|
|
24
24
|
return h(u.POST, t, e);
|
|
25
25
|
}
|
|
26
|
-
function
|
|
26
|
+
function it(t = "", e = {}) {
|
|
27
27
|
return h(u.PUT, t, e);
|
|
28
28
|
}
|
|
29
|
-
function
|
|
29
|
+
function ct(t = "", e = {}) {
|
|
30
30
|
return h(u.DELETE, t, e);
|
|
31
31
|
}
|
|
32
|
-
function
|
|
32
|
+
function ut(t = "", e = {}) {
|
|
33
33
|
return h(u.PATCH, t, e);
|
|
34
34
|
}
|
|
35
|
-
function
|
|
35
|
+
function ht(t = "", e = {}) {
|
|
36
36
|
return h(u.HEAD, t, e);
|
|
37
37
|
}
|
|
38
|
-
function
|
|
38
|
+
function dt(t = "", e = {}) {
|
|
39
39
|
return h(u.OPTIONS, t, e);
|
|
40
40
|
}
|
|
41
|
-
const
|
|
42
|
-
class
|
|
41
|
+
const Y = "fetcher", k = "__decorator_target__";
|
|
42
|
+
class N {
|
|
43
43
|
/**
|
|
44
44
|
* Creates a new RequestExecutor instance.
|
|
45
45
|
*
|
|
@@ -57,8 +57,8 @@ class k {
|
|
|
57
57
|
getTargetFetcher(e) {
|
|
58
58
|
if (!e || typeof e != "object")
|
|
59
59
|
return;
|
|
60
|
-
const r = e[
|
|
61
|
-
if (r instanceof
|
|
60
|
+
const r = e[Y];
|
|
61
|
+
if (r instanceof x)
|
|
62
62
|
return r;
|
|
63
63
|
}
|
|
64
64
|
/**
|
|
@@ -100,57 +100,57 @@ class k {
|
|
|
100
100
|
*/
|
|
101
101
|
async execute(e, r) {
|
|
102
102
|
const n = this.getTargetFetcher(e) || this.metadata.fetcher, a = this.metadata.resolveExchangeInit(r);
|
|
103
|
-
a.attributes
|
|
103
|
+
a.attributes?.set(k, e);
|
|
104
104
|
const s = this.metadata.resolveResultExtractor();
|
|
105
|
-
return n.request(a.request, s, a.attributes);
|
|
105
|
+
return n.request(a.request, { resultExtractor: s, attributes: a.attributes });
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
const E = /* @__PURE__ */ new WeakMap();
|
|
109
|
-
function
|
|
109
|
+
function B(t) {
|
|
110
110
|
if (typeof t != "function")
|
|
111
111
|
throw new TypeError("Expected a function");
|
|
112
112
|
if (E.has(t))
|
|
113
113
|
return E.get(t);
|
|
114
114
|
try {
|
|
115
|
-
const e = t.toString().trim(), r =
|
|
116
|
-
if (!
|
|
115
|
+
const e = t.toString().trim(), r = Q(e);
|
|
116
|
+
if (!G(r)) {
|
|
117
117
|
const a = [];
|
|
118
118
|
return E.set(t, a), a;
|
|
119
119
|
}
|
|
120
|
-
const n =
|
|
120
|
+
const n = j(r);
|
|
121
121
|
return E.set(t, n), n;
|
|
122
122
|
} catch {
|
|
123
123
|
const e = [];
|
|
124
124
|
return E.set(t, e), e;
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
|
-
function
|
|
127
|
+
function C(t, e, r, n) {
|
|
128
128
|
if (n)
|
|
129
129
|
return n;
|
|
130
130
|
try {
|
|
131
131
|
const a = t[e];
|
|
132
132
|
if (a && typeof a == "function") {
|
|
133
|
-
const s =
|
|
133
|
+
const s = B(a);
|
|
134
134
|
if (r < s.length)
|
|
135
135
|
return s[r];
|
|
136
136
|
}
|
|
137
137
|
} catch {
|
|
138
138
|
}
|
|
139
139
|
}
|
|
140
|
-
function
|
|
140
|
+
function G(t) {
|
|
141
141
|
return t != null && t.trim() !== "";
|
|
142
142
|
}
|
|
143
|
-
function
|
|
143
|
+
function Q(t) {
|
|
144
144
|
if (t.startsWith("(")) {
|
|
145
|
-
const n =
|
|
145
|
+
const n = A(t, 0);
|
|
146
146
|
return n === -1 ? "" : t.substring(1, n);
|
|
147
147
|
}
|
|
148
148
|
const e = t.indexOf("(");
|
|
149
149
|
if (e === -1) return "";
|
|
150
|
-
const r =
|
|
150
|
+
const r = A(t, e);
|
|
151
151
|
return r === -1 ? "" : t.substring(e + 1, r);
|
|
152
152
|
}
|
|
153
|
-
function
|
|
153
|
+
function A(t, e) {
|
|
154
154
|
let r = 1;
|
|
155
155
|
for (let n = e + 1; n < t.length; n++) {
|
|
156
156
|
const a = t[n];
|
|
@@ -161,93 +161,93 @@ function T(t, e) {
|
|
|
161
161
|
}
|
|
162
162
|
return -1;
|
|
163
163
|
}
|
|
164
|
-
function Q(t) {
|
|
165
|
-
return t.split(",").map(j).filter(J).map(L);
|
|
166
|
-
}
|
|
167
164
|
function j(t) {
|
|
168
|
-
return t.
|
|
165
|
+
return t.split(",").map(J).filter(L).map(W);
|
|
169
166
|
}
|
|
170
167
|
function J(t) {
|
|
171
|
-
return t.
|
|
168
|
+
return t.trim();
|
|
172
169
|
}
|
|
173
170
|
function L(t) {
|
|
174
|
-
|
|
175
|
-
return e = K(e), e.trim();
|
|
171
|
+
return t.length > 0;
|
|
176
172
|
}
|
|
177
173
|
function W(t) {
|
|
174
|
+
let e = K(t);
|
|
175
|
+
return e = $(e), e.trim();
|
|
176
|
+
}
|
|
177
|
+
function K(t) {
|
|
178
178
|
const e = t.indexOf("=");
|
|
179
179
|
return e !== -1 ? t.substring(0, e) : t;
|
|
180
180
|
}
|
|
181
|
-
function
|
|
181
|
+
function $(t) {
|
|
182
182
|
const e = t.indexOf(":");
|
|
183
183
|
return e !== -1 ? t.substring(0, e) : t;
|
|
184
184
|
}
|
|
185
185
|
var i = /* @__PURE__ */ ((t) => (t.PATH = "path", t.QUERY = "query", t.HEADER = "header", t.BODY = "body", t.REQUEST = "request", t.ATTRIBUTE = "attribute", t.ATTRIBUTES = "attributes", t))(i || {});
|
|
186
|
-
const
|
|
186
|
+
const R = Symbol("parameter:metadata");
|
|
187
187
|
function d(t, e = "") {
|
|
188
188
|
return function(r, n, a) {
|
|
189
|
-
const s =
|
|
189
|
+
const s = C(
|
|
190
190
|
r,
|
|
191
191
|
n,
|
|
192
192
|
a,
|
|
193
193
|
e
|
|
194
|
-
), c = Reflect.getMetadata(
|
|
194
|
+
), c = Reflect.getMetadata(R, r, n) || /* @__PURE__ */ new Map(), f = {
|
|
195
195
|
type: t,
|
|
196
196
|
name: s,
|
|
197
197
|
index: a
|
|
198
198
|
};
|
|
199
199
|
c.set(a, f), Reflect.defineMetadata(
|
|
200
|
-
|
|
200
|
+
R,
|
|
201
201
|
c,
|
|
202
202
|
r,
|
|
203
203
|
n
|
|
204
204
|
);
|
|
205
205
|
};
|
|
206
206
|
}
|
|
207
|
-
function
|
|
207
|
+
function ft(t = "") {
|
|
208
208
|
return d("path", t);
|
|
209
209
|
}
|
|
210
|
-
function
|
|
210
|
+
function pt(t = "") {
|
|
211
211
|
return d("query", t);
|
|
212
212
|
}
|
|
213
|
-
function
|
|
213
|
+
function mt(t = "") {
|
|
214
214
|
return d("header", t);
|
|
215
215
|
}
|
|
216
|
-
function
|
|
216
|
+
function Et() {
|
|
217
217
|
return d(
|
|
218
218
|
"body"
|
|
219
219
|
/* BODY */
|
|
220
220
|
);
|
|
221
221
|
}
|
|
222
|
-
function
|
|
222
|
+
function lt() {
|
|
223
223
|
return d(
|
|
224
224
|
"request"
|
|
225
225
|
/* REQUEST */
|
|
226
226
|
);
|
|
227
227
|
}
|
|
228
|
-
function
|
|
228
|
+
function bt(t = "") {
|
|
229
229
|
return d("attribute", t);
|
|
230
230
|
}
|
|
231
|
-
function
|
|
231
|
+
function Rt() {
|
|
232
232
|
return d(
|
|
233
233
|
"attributes"
|
|
234
234
|
/* ATTRIBUTES */
|
|
235
235
|
);
|
|
236
236
|
}
|
|
237
|
-
function
|
|
237
|
+
function V(t) {
|
|
238
238
|
if (t)
|
|
239
|
-
return t instanceof
|
|
239
|
+
return t instanceof x ? t : D.requiredGet(t);
|
|
240
240
|
}
|
|
241
|
-
const
|
|
242
|
-
Exchange:
|
|
241
|
+
const z = {
|
|
242
|
+
Exchange: w,
|
|
243
243
|
Response: O,
|
|
244
|
-
Json:
|
|
245
|
-
Text:
|
|
246
|
-
EventStream:
|
|
247
|
-
JsonEventStream:
|
|
248
|
-
DEFAULT:
|
|
244
|
+
Json: T,
|
|
245
|
+
Text: I,
|
|
246
|
+
EventStream: F,
|
|
247
|
+
JsonEventStream: H,
|
|
248
|
+
DEFAULT: T
|
|
249
249
|
};
|
|
250
|
-
class
|
|
250
|
+
class X {
|
|
251
251
|
/**
|
|
252
252
|
* Creates a new FunctionMetadata instance.
|
|
253
253
|
*
|
|
@@ -268,7 +268,7 @@ class z {
|
|
|
268
268
|
* @returns The fetcher instance
|
|
269
269
|
*/
|
|
270
270
|
get fetcher() {
|
|
271
|
-
return
|
|
271
|
+
return V(this.endpoint.fetcher ?? this.api.fetcher) ?? U;
|
|
272
272
|
}
|
|
273
273
|
/**
|
|
274
274
|
* Resolves the complete path by combining base path and endpoint path
|
|
@@ -278,7 +278,7 @@ class z {
|
|
|
278
278
|
*/
|
|
279
279
|
resolvePath(e) {
|
|
280
280
|
const r = this.endpoint.basePath || this.api.basePath || "", n = e || this.endpoint.path || "";
|
|
281
|
-
return
|
|
281
|
+
return v(r, n);
|
|
282
282
|
}
|
|
283
283
|
/**
|
|
284
284
|
* Resolves the timeout for the request.
|
|
@@ -292,13 +292,11 @@ class z {
|
|
|
292
292
|
return this.endpoint.timeout || this.api.timeout;
|
|
293
293
|
}
|
|
294
294
|
resolveResultExtractor() {
|
|
295
|
-
return this.endpoint.resultExtractor || this.api.resultExtractor ||
|
|
295
|
+
return this.endpoint.resultExtractor || this.api.resultExtractor || z.DEFAULT;
|
|
296
296
|
}
|
|
297
297
|
resolveAttributes() {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
...this.endpoint.attributes
|
|
301
|
-
};
|
|
298
|
+
const e = b(this.api.attributes);
|
|
299
|
+
return b(this.endpoint.attributes, e);
|
|
302
300
|
}
|
|
303
301
|
/**
|
|
304
302
|
* Resolves the request configuration from the method arguments.
|
|
@@ -353,7 +351,7 @@ class z {
|
|
|
353
351
|
};
|
|
354
352
|
let s, c, f, m = {};
|
|
355
353
|
const l = this.resolveAttributes();
|
|
356
|
-
e.forEach((o,
|
|
354
|
+
e.forEach((o, _) => {
|
|
357
355
|
if (o instanceof AbortSignal) {
|
|
358
356
|
c = o;
|
|
359
357
|
return;
|
|
@@ -362,7 +360,7 @@ class z {
|
|
|
362
360
|
f = o;
|
|
363
361
|
return;
|
|
364
362
|
}
|
|
365
|
-
const p = this.parameters.get(
|
|
363
|
+
const p = this.parameters.get(_);
|
|
366
364
|
if (p)
|
|
367
365
|
switch (p.type) {
|
|
368
366
|
case i.PATH:
|
|
@@ -388,23 +386,23 @@ class z {
|
|
|
388
386
|
break;
|
|
389
387
|
}
|
|
390
388
|
});
|
|
391
|
-
const
|
|
389
|
+
const y = {
|
|
392
390
|
path: r,
|
|
393
391
|
query: n
|
|
394
|
-
},
|
|
392
|
+
}, M = {
|
|
395
393
|
method: this.endpoint.method,
|
|
396
|
-
urlParams:
|
|
394
|
+
urlParams: y,
|
|
397
395
|
headers: a,
|
|
398
396
|
body: s,
|
|
399
397
|
timeout: this.resolveTimeout(),
|
|
400
398
|
signal: c,
|
|
401
399
|
abortController: f
|
|
402
|
-
},
|
|
403
|
-
|
|
400
|
+
}, P = S(
|
|
401
|
+
M,
|
|
404
402
|
m
|
|
405
403
|
), q = m.path;
|
|
406
|
-
return
|
|
407
|
-
request:
|
|
404
|
+
return P.url = this.resolvePath(q), {
|
|
405
|
+
request: P,
|
|
408
406
|
attributes: l
|
|
409
407
|
};
|
|
410
408
|
}
|
|
@@ -454,89 +452,87 @@ class z {
|
|
|
454
452
|
};
|
|
455
453
|
}
|
|
456
454
|
processAttributeParam(e, r, n) {
|
|
457
|
-
e.name && r !== void 0 && (
|
|
455
|
+
e.name && r !== void 0 && n.set(e.name, r);
|
|
458
456
|
}
|
|
459
457
|
processAttributesParam(e, r) {
|
|
460
|
-
if (typeof e != "object")
|
|
461
|
-
throw new Error("@attributes() parameter must be an object");
|
|
462
|
-
|
|
463
|
-
r[n] = e[n];
|
|
464
|
-
});
|
|
458
|
+
if (typeof e != "object" || e instanceof Map)
|
|
459
|
+
throw new Error("@attributes() parameter must be an object or an Map");
|
|
460
|
+
b(e, r);
|
|
465
461
|
}
|
|
466
462
|
}
|
|
467
|
-
const
|
|
468
|
-
function
|
|
463
|
+
const Z = Symbol("api:metadata");
|
|
464
|
+
function tt(t, e, r) {
|
|
469
465
|
const n = t.prototype[e];
|
|
470
466
|
if (e === "constructor" || typeof n != "function")
|
|
471
467
|
return;
|
|
472
468
|
const a = Reflect.getMetadata(
|
|
473
|
-
|
|
469
|
+
g,
|
|
474
470
|
t.prototype,
|
|
475
471
|
e
|
|
476
472
|
);
|
|
477
473
|
if (!a)
|
|
478
474
|
return;
|
|
479
475
|
const s = Reflect.getMetadata(
|
|
480
|
-
|
|
476
|
+
R,
|
|
481
477
|
t.prototype,
|
|
482
478
|
e
|
|
483
|
-
) || /* @__PURE__ */ new Map(), c = new
|
|
479
|
+
) || /* @__PURE__ */ new Map(), c = new X(
|
|
484
480
|
e,
|
|
485
481
|
r,
|
|
486
482
|
a,
|
|
487
483
|
s
|
|
488
|
-
), f = new
|
|
484
|
+
), f = new N(c);
|
|
489
485
|
t.prototype[e] = function(...m) {
|
|
490
486
|
return f.execute(this, m);
|
|
491
487
|
};
|
|
492
488
|
}
|
|
493
|
-
function
|
|
489
|
+
function Pt(t = "", e = {}) {
|
|
494
490
|
return function(r) {
|
|
495
491
|
const n = {
|
|
496
492
|
basePath: t,
|
|
497
493
|
...e
|
|
498
494
|
};
|
|
499
|
-
return Reflect.defineMetadata(
|
|
500
|
-
|
|
495
|
+
return Reflect.defineMetadata(Z, n, r), Object.getOwnPropertyNames(r.prototype).forEach((a) => {
|
|
496
|
+
tt(r, a, n);
|
|
501
497
|
}), r;
|
|
502
498
|
};
|
|
503
499
|
}
|
|
504
|
-
class
|
|
500
|
+
class et extends Error {
|
|
505
501
|
constructor() {
|
|
506
502
|
super("Implementation will be generated automatically."), this.name = "AutoGenerated";
|
|
507
503
|
}
|
|
508
504
|
}
|
|
509
|
-
const
|
|
505
|
+
const Tt = (...t) => new et();
|
|
510
506
|
export {
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
507
|
+
Z as API_METADATA_KEY,
|
|
508
|
+
et as AutoGenerated,
|
|
509
|
+
k as DECORATOR_TARGET_ATTRIBUTE_KEY,
|
|
510
|
+
g as ENDPOINT_METADATA_KEY,
|
|
511
|
+
X as FunctionMetadata,
|
|
512
|
+
R as PARAMETER_METADATA_KEY,
|
|
517
513
|
i as ParameterType,
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
514
|
+
N as RequestExecutor,
|
|
515
|
+
z as ResultExtractors,
|
|
516
|
+
Pt as api,
|
|
517
|
+
bt as attribute,
|
|
518
|
+
Rt as attributes,
|
|
519
|
+
Tt as autoGeneratedError,
|
|
520
|
+
Et as body,
|
|
521
|
+
ct as del,
|
|
526
522
|
h as endpoint,
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
523
|
+
st as get,
|
|
524
|
+
V as getFetcher,
|
|
525
|
+
C as getParameterName,
|
|
526
|
+
B as getParameterNames,
|
|
527
|
+
ht as head,
|
|
528
|
+
mt as header,
|
|
529
|
+
dt as options,
|
|
534
530
|
d as parameter,
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
531
|
+
ut as patch,
|
|
532
|
+
ft as path,
|
|
533
|
+
ot as post,
|
|
534
|
+
it as put,
|
|
535
|
+
pt as query,
|
|
536
|
+
lt as request
|
|
541
537
|
};
|
|
542
538
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/endpointDecorator.ts","../src/requestExecutor.ts","../src/reflection.ts","../src/parameterDecorator.ts","../src/fetcherCapable.ts","../src/resultExtractor.ts","../src/functionMetadata.ts","../src/apiDecorator.ts","../src/generated.ts"],"sourcesContent":["import { HttpMethod } from '@ahoo-wang/fetcher';\nimport { type ApiMetadata } from './apiDecorator';\nimport 'reflect-metadata';\nimport { type ResultExtractorCapable } from './resultExtractor';\n\nexport interface PathCapable {\n /**\n * Path for the endpoint (relative to class base path).\n *\n * This path will be appended to the class's base path to form the complete URL.\n * Path parameters can be specified using curly braces, e.g., '/users/{id}'\n */\n path?: string;\n}\n\n/**\n * Metadata for HTTP endpoints.\n *\n * Defines the configuration options for individual HTTP endpoints (methods).\n * These settings will override any corresponding class-level settings from ApiMetadata.\n */\nexport interface EndpointMetadata\n extends ApiMetadata,\n ResultExtractorCapable,\n PathCapable {\n /**\n * HTTP method for the endpoint.\n *\n * Specifies the HTTP verb to be used for this endpoint (GET, POST, PUT, DELETE, etc.)\n */\n method?: HttpMethod;\n}\n\nexport const ENDPOINT_METADATA_KEY = Symbol('endpoint:metadata');\n\nexport type MethodEndpointMetadata = Omit<EndpointMetadata, 'method' | 'path'>;\n\n/**\n * Decorator factory for defining HTTP endpoints.\n *\n * Creates a decorator that can be used to define HTTP endpoints\n * on class methods. It stores metadata about the endpoint that will be used\n * to generate the actual HTTP request.\n *\n * @param method - The HTTP method for this endpoint\n * @param path - The path for this endpoint (relative to class base path)\n * @param metadata - Additional endpoint metadata (headers, timeout, etc.)\n * @returns A method decorator function\n *\n * @example\n * ```typescript\n * @api('/api/v1')\n * class UserService {\n * @endpoint(HttpMethod.GET, '/users/{id}')\n * getUser(@path('id') id: string): Promise<Response> {\n * // Implementation will be generated automatically\n * throw autoGeneratedError();\n * }\n * }\n * ```\n */\nexport function endpoint(\n method?: HttpMethod,\n path?: string,\n metadata: MethodEndpointMetadata = {},\n) {\n return function(target: object, propertyKey: string | symbol): void {\n // Store metadata directly on the method\n const endpointMetadata = {\n method: method,\n path,\n ...metadata,\n };\n Reflect.defineMetadata(\n ENDPOINT_METADATA_KEY,\n endpointMetadata,\n target,\n propertyKey,\n );\n };\n}\n\nexport function get(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.GET, path, metadata);\n}\n\nexport function post(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.POST, path, metadata);\n}\n\nexport function put(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.PUT, path, metadata);\n}\n\nexport function del(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.DELETE, path, metadata);\n}\n\nexport function patch(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.PATCH, path, metadata);\n}\n\nexport function head(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.HEAD, path, metadata);\n}\n\nexport function options(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.OPTIONS, path, metadata);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Fetcher } from '@ahoo-wang/fetcher';\nimport { FunctionMetadata } from './functionMetadata';\n\nconst TARGET_FETCHER_PROPERTY = 'fetcher';\n\nexport const DECORATOR_TARGET_ATTRIBUTE_KEY = '__decorator_target__';\n\n/**\n * Executor for HTTP requests based on decorated method metadata.\n *\n * This class is responsible for executing HTTP requests based on the metadata\n * collected from decorators. It resolves the path, constructs the request,\n * and executes it using the appropriate fetcher.\n */\nexport class RequestExecutor {\n private readonly metadata: FunctionMetadata;\n\n /**\n * Creates a new RequestExecutor instance.\n *\n * @param metadata - The function metadata containing all request information\n */\n constructor(metadata: FunctionMetadata) {\n this.metadata = metadata;\n }\n\n /**\n * Retrieves the fetcher instance from the target object.\n *\n * @param target - The target object that may contain a fetcher property\n * @returns The fetcher instance if exists, otherwise undefined\n */\n private getTargetFetcher(target: any): Fetcher | undefined {\n if (!target || typeof target !== 'object') {\n return undefined;\n }\n // Extract the fetcher property from the target object\n const fetcher = target[TARGET_FETCHER_PROPERTY];\n\n // Validate that the fetcher is an instance of the Fetcher class\n if (fetcher instanceof Fetcher) {\n return fetcher;\n }\n\n // Return undefined if no valid fetcher instance is found\n return undefined;\n }\n\n /**\n * Executes the HTTP request.\n *\n * This method resolves the path and request configuration from the metadata\n * and arguments, then executes the request using the configured fetcher.\n * It handles the complete request lifecycle from parameter processing to\n * response extraction.\n *\n * @param target - The target object that the method is called on.\n * This can contain a custom fetcher instance in its 'fetcher' property.\n * @param args - The runtime arguments passed to the decorated method.\n * These are mapped to request components based on parameter decorators.\n * @returns A Promise that resolves to the extracted result based on the configured result extractor.\n * By default, this is the Response object, but can be customized to return\n * parsed JSON, the raw exchange object, or any other transformed result.\n *\n * @example\n * ```typescript\n * // Given a decorated service method:\n * class UserService {\n * @get('/users/{id}')\n * getUser(@path('id') id: number): Promise<Response> {\n * // This method body is replaced by the executor at runtime\n * }\n * }\n *\n * // When calling:\n * const userService = new UserService();\n * const response = await userService.getUser(123);\n *\n * // The execute method will:\n * // 1. Resolve the path to '/users/123'\n * // 2. Create a request with method 'GET'\n * // 3. Execute the request using the configured fetcher\n * // 4. Return the Response object\n * ```\n */\n async execute(target: any, args: any[]): Promise<any> {\n const fetcher = this.getTargetFetcher(target) || this.metadata.fetcher;\n const exchangeInit = this.metadata.resolveExchangeInit(args);\n exchangeInit.attributes[DECORATOR_TARGET_ATTRIBUTE_KEY] = target;\n const extractor = this.metadata.resolveResultExtractor();\n return fetcher.request(exchangeInit.request, extractor, exchangeInit.attributes);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Cache for storing previously extracted parameter names to improve performance\nconst parameterNameCache = new WeakMap<Function, string[]>();\n\n/**\n * Extracts parameter names from a function.\n *\n * This function parses the string representation of a function to extract\n * the names of its parameters. It handles various function formats including\n * regular functions, arrow functions, and methods.\n *\n * Note: This implementation provides basic parameter name extraction and may not\n * handle all edge cases of complex TypeScript parameter declarations.\n *\n * @param func - The function to extract parameter names from\n * @returns An array of parameter names, or an empty array if extraction fails\n * @throws {TypeError} If the input is not a function\n *\n * @example\n * ```typescript\n * function example(a, b, c) {}\n * const paramNames = getParameterNames(example);\n * // Returns: ['a', 'b', 'c']\n *\n * const arrowFunc = (x, y) => x + y;\n * const arrowParamNames = getParameterNames(arrowFunc);\n * // Returns: ['x', 'y']\n *\n * function complex(param1: string, param2: number = 10, ...rest: any[]) {}\n * const complexParamNames = getParameterNames(complex);\n * // Returns: ['param1', 'param2', '...rest']\n * ```\n */\nexport function getParameterNames(func: (...args: any[]) => any): string[] {\n // Validate that the input is a function\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n // Check cache first to improve performance\n if (parameterNameCache.has(func)) {\n return parameterNameCache.get(func)!;\n }\n\n try {\n // Convert function to string and trim whitespace\n const fnStr = func.toString().trim();\n\n // Extract parameter string from the function\n const paramsStr = extractParameterString(fnStr);\n\n // Handle empty parameters\n if (!hasParameters(paramsStr)) {\n const emptyResult: string[] = [];\n parameterNameCache.set(func, emptyResult);\n return emptyResult;\n }\n\n // Parse and clean parameter names\n const result = parseParameterNames(paramsStr);\n parameterNameCache.set(func, result);\n return result;\n } catch {\n // Return empty array on any parsing errors to avoid breaking the application\n const errorResult: string[] = [];\n parameterNameCache.set(func, errorResult);\n return errorResult;\n }\n}\n\n/**\n * Helper function to automatically extract parameter name when not provided.\n *\n * @param target - The target object (class prototype)\n * @param propertyKey - The method name\n * @param parameterIndex - The index of the parameter\n * @param providedName - The name explicitly provided by the user (if any)\n * @returns The parameter name, either provided or automatically extracted\n */\nexport function getParameterName(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n providedName?: string,\n): string | undefined {\n // If a name was explicitly provided, use it\n if (providedName) {\n return providedName;\n }\n\n // Try to automatically extract the parameter name\n try {\n const method = target[propertyKey as keyof typeof target];\n if (method && typeof method === 'function') {\n const paramNames = getParameterNames(method);\n if (parameterIndex < paramNames.length) {\n return paramNames[parameterIndex];\n }\n }\n } catch {\n // If we can't get the parameter name, return undefined\n // This will use default naming in the execution logic\n }\n\n return undefined;\n}\n\n/**\n * Checks if a parameter string contains actual parameters.\n *\n * @param paramsStr - The parameter string to check\n * @returns True if the string contains parameters, false otherwise\n */\nfunction hasParameters(paramsStr: string): boolean {\n return (\n paramsStr !== null && paramsStr !== undefined && paramsStr.trim() !== ''\n );\n}\n\n/**\n * Extracts the parameter string from a function string representation.\n *\n * @param fnStr - The string representation of the function\n * @returns The parameter string, or empty string if not found\n */\nfunction extractParameterString(fnStr: string): string {\n // Handle arrow functions that start with parentheses\n if (fnStr.startsWith('(')) {\n const endParenIndex = findClosingParenthesis(fnStr, 0);\n if (endParenIndex === -1) return '';\n return fnStr.substring(1, endParenIndex);\n }\n\n // Handle regular functions, async functions, and methods\n const startParenIndex = fnStr.indexOf('(');\n if (startParenIndex === -1) return '';\n\n const endParenIndex = findClosingParenthesis(fnStr, startParenIndex);\n if (endParenIndex === -1) return '';\n\n return fnStr.substring(startParenIndex + 1, endParenIndex);\n}\n\n/**\n * Finds the matching closing parenthesis for an opening parenthesis.\n *\n * @param str - The string to search in\n * @param openingParenIndex - The index of the opening parenthesis\n * @returns The index of the matching closing parenthesis, or -1 if not found\n */\nfunction findClosingParenthesis(\n str: string,\n openingParenIndex: number,\n): number {\n let parenDepth = 1;\n\n for (let i = openingParenIndex + 1; i < str.length; i++) {\n const char = str[i];\n\n if (char === '(') {\n parenDepth++;\n } else if (char === ')') {\n parenDepth--;\n if (parenDepth === 0) {\n return i;\n }\n }\n }\n\n return -1; // No matching closing parenthesis found\n}\n\n/**\n * Parses and cleans parameter names from a parameter string.\n *\n * @param paramsStr - The parameter string to parse\n * @returns An array of cleaned parameter names\n */\nfunction parseParameterNames(paramsStr: string): string[] {\n return paramsStr\n .split(',')\n .map(trimWhitespace)\n .filter(isNotEmpty)\n .map(extractParameterName);\n}\n\n/**\n * Trims whitespace from a string.\n *\n * @param str - The string to trim\n * @returns The trimmed string\n */\nfunction trimWhitespace(str: string): string {\n return str.trim();\n}\n\n/**\n * Checks if a string is not empty.\n *\n * @param str - The string to check\n * @returns True if the string is not empty, false otherwise\n */\nfunction isNotEmpty(str: string): boolean {\n return str.length > 0;\n}\n\n/**\n * Extracts a clean parameter name by removing type annotations and default values.\n *\n * @param param - The raw parameter string\n * @returns The cleaned parameter name\n */\nfunction extractParameterName(param: string): string {\n // Remove default value assignment (everything after =)\n let cleanedParam = removeDefaultValue(param);\n\n // Remove type annotations (everything after :)\n cleanedParam = removeTypeAnnotation(cleanedParam);\n\n return cleanedParam.trim();\n}\n\n/**\n * Removes default value from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without default value\n */\nfunction removeDefaultValue(param: string): string {\n const equalsIndex = param.indexOf('=');\n if (equalsIndex !== -1) {\n return param.substring(0, equalsIndex);\n }\n return param;\n}\n\n/**\n * Removes type annotation from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without type annotation\n */\nfunction removeTypeAnnotation(param: string): string {\n const colonIndex = param.indexOf(':');\n if (colonIndex !== -1) {\n return param.substring(0, colonIndex);\n }\n return param;\n}\n","import { getParameterName } from './reflection';\nimport 'reflect-metadata';\nimport { type PathCapable } from './endpointDecorator';\nimport { type FetchRequestInit } from '@ahoo-wang/fetcher';\n\n/**\n * Parameter types for decorator parameters.\n *\n * Defines the different types of parameters that can be used\n * in API method decorators to specify how arguments should be handled\n * in the HTTP request.\n */\nexport enum ParameterType {\n /**\n * Path parameter that will be inserted into the URL path.\n *\n * Path parameters are used to specify dynamic parts of the URL path.\n * They are defined using curly braces in the endpoint path.\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n * ```\n */\n PATH = 'path',\n\n /**\n * Query parameter that will be appended to the URL query string.\n *\n * Query parameters are used to pass non-hierarchical data to the server.\n * They appear after the '?' in the URL.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n * ```\n */\n QUERY = 'query',\n\n /**\n * Header parameter that will be added to the request headers.\n *\n * Header parameters are used to pass metadata about the request,\n * such as authentication tokens or content type information.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n * ```\n */\n HEADER = 'header',\n\n /**\n * Body parameter that will be sent as the request body.\n *\n * The body parameter represents the main data payload of the request.\n * It is typically used with POST, PUT, and PATCH requests.\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\n BODY = 'body',\n\n /**\n * Request parameter that will be used as the request object.\n */\n REQUEST = 'request',\n\n\n /**\n * Attribute parameter that will be used as a single attribute in the request attributes.\n *\n * The attribute parameter allows passing a single key-value pair that will be added\n * to the request attributes object. This is useful for passing specific contextual\n * information that can be accessed by interceptors.\n */\n ATTRIBUTE = 'attribute',\n /**\n * Attributes parameter that will be used as the request attributes.\n *\n * The attributes parameter allows passing custom data that can be accessed\n * by interceptors throughout the request lifecycle. This is useful for\n * sharing contextual information between different parts of the request processing.\n */\n ATTRIBUTES = 'attributes'\n}\n\n/**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter\n * decorated with @path, @query, @header, or @body decorators.\n */\nexport interface ParameterMetadata {\n /**\n * Type of parameter (path, query, header, body).\n *\n * Specifies how this parameter should be handled in the HTTP request.\n */\n type: ParameterType;\n\n /**\n * Name of the parameter (used for path, query, and header parameters).\n *\n * For path and query parameters, this corresponds to the key in the URL.\n * For header parameters, this corresponds to the header name.\n * For body parameters, this is not used.\n */\n name?: string;\n\n /**\n * Index of the parameter in the method signature.\n *\n * This is used to map the runtime argument values to the correct parameter metadata.\n */\n index: number;\n}\n\nexport const PARAMETER_METADATA_KEY = Symbol('parameter:metadata');\n\n/**\n * Decorator factory for method parameters.\n *\n * Creates a decorator that can be used to specify how a method parameter\n * should be handled in the HTTP request. It stores metadata about the parameter\n * that will be used during request execution.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param type - The type of parameter (PATH, QUERY, HEADER, or BODY)\n * @param name - The name of the parameter (used for path, query, and header parameters, optional - auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@parameter(ParameterType.PATH, 'id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@parameter(ParameterType.PATH) userId: string): Promise<Response>\n * ```\n */\nexport function parameter(type: ParameterType, name: string = '') {\n return function(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n ) {\n const paramName = getParameterName(\n target,\n propertyKey as string,\n parameterIndex,\n name,\n );\n\n const existingParameters: Map<number, ParameterMetadata> =\n Reflect.getMetadata(PARAMETER_METADATA_KEY, target, propertyKey) ||\n new Map();\n const parameterMetadata: ParameterMetadata = {\n type: type,\n name: paramName,\n index: parameterIndex,\n };\n existingParameters.set(parameterIndex, parameterMetadata);\n Reflect.defineMetadata(\n PARAMETER_METADATA_KEY,\n existingParameters,\n target,\n propertyKey,\n );\n };\n}\n\n/**\n * Path parameter decorator.\n *\n * Defines a path parameter that will be inserted into the URL path.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the path parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@path() userId: string): Promise<Response>\n * ```\n */\nexport function path(name: string = '') {\n return parameter(ParameterType.PATH, name);\n}\n\n/**\n * Query parameter decorator.\n *\n * Defines a query parameter that will be appended to the URL query string.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the query parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@query() limit: number): Promise<Response>\n * ```\n */\nexport function query(name: string = '') {\n return parameter(ParameterType.QUERY, name);\n}\n\n/**\n * Header parameter decorator.\n *\n * Defines a header parameter that will be added to the request headers.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the header parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@header() authorization: string): Promise<Response>\n * ```\n */\nexport function header(name: string = '') {\n return parameter(ParameterType.HEADER, name);\n}\n\n/**\n * Body parameter decorator.\n *\n * Defines a body parameter that will be sent as the request body.\n * Note that body parameters don't have names since there's only one body per request.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\nexport function body() {\n return parameter(ParameterType.BODY);\n}\n\n/**\n * Interface for request parameter objects.\n *\n * Combines FetchRequestInit and PathCapable interfaces to provide\n * a complete request configuration object that can be used with\n * the @request() decorator. This allows full customization of\n * the HTTP request including method, headers, body, and URL parameters.\n */\nexport interface ParameterRequest extends FetchRequestInit, PathCapable {\n}\n\n/**\n * Request parameter decorator.\n *\n * Defines a request parameter that will be used as the base request object.\n * This allows you to pass a complete ParameterRequest object to customize\n * the request configuration.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: ParameterRequest): Promise<Response>\n * ```\n */\nexport function request() {\n return parameter(ParameterType.REQUEST);\n}\n\n/**\n * Parameter decorator for adding a single attribute to the request attributes.\n *\n * This decorator allows you to pass a key-value pair as an attribute that can be accessed\n * by interceptors during the request lifecycle. If no name is provided, the parameter's\n * property name will be used as the attribute key.\n *\n * @param name - Optional name for the attribute. If not provided, the parameter's property name will be used.\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute('userId') userId: string): Promise<Response>\n *\n * // Using property name as attribute key\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute() userId: string): Promise<Response>\n * ```\n */\nexport function attribute(name: string = '') {\n return parameter(ParameterType.ATTRIBUTE, name);\n}\n\n/**\n * Parameter decorator for adding multiple attributes to the request.\n *\n * This decorator allows you to pass an entire object as attributes that can be accessed\n * by interceptors during the request lifecycle. The parameter should be an object whose\n * properties will be merged into the request attributes.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attributes() attrs: Record<string, any>): Promise<Response>\n * ```\n */\nexport function attributes() {\n return parameter(ParameterType.ATTRIBUTES);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';\n\n/**\n * Interface that defines a capability for objects that can have a fetcher.\n * This interface is typically used to mark components or objects that can perform fetching operations\n * and may need access to fetcher functionality.\n */\nexport interface FetcherCapable {\n /**\n * Optional fetcher property that can be either a string identifier or a Fetcher instance.\n * When present, this property indicates the fetcher associated with the implementing object.\n */\n fetcher?: string | Fetcher;\n}\n\n/**\n * Gets a Fetcher instance based on the provided fetcher parameter.\n *\n * @param fetcher - A string identifier or Fetcher instance to resolve\n * @returns A Fetcher instance if found, undefined otherwise\n */\nexport function getFetcher(fetcher?: string | Fetcher): Fetcher | undefined {\n // Return undefined if no fetcher is provided\n if (!fetcher) {\n return undefined;\n }\n\n // Return the fetcher directly if it's already a Fetcher instance,\n // otherwise resolve it through the fetcher registrar\n return fetcher instanceof Fetcher\n ? fetcher\n : fetcherRegistrar.requiredGet(fetcher);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ExchangeResultExtractor,\n JsonResultExtractor,\n ResponseResultExtractor,\n ResultExtractor,\n TextResultExtractor,\n} from '@ahoo-wang/fetcher';\nimport {\n EventStreamResultExtractor,\n JsonEventStreamResultExtractor,\n} from '@ahoo-wang/fetcher-eventstream';\n\n/**\n * Interface with result extractor capability\n * Defines an optional resultExtractor property\n */\nexport interface ResultExtractorCapable {\n resultExtractor?: ResultExtractor<any>;\n}\n\n/**\n * ResultExtractors is an object that maps result extractor names to their corresponding\n * extractor functions. These extractors are used to process and extract data from different\n * types of responses or results in the application.\n *\n * Each property represents a specific type of result extractor:\n * - Exchange: Handles exchange-related result extraction\n * - Response: Handles general response result extraction\n * - Json: Handles JSON format result extraction\n * - Text: Handles plain text result extraction\n * - EventStream: Handles server-sent event stream result extraction\n * - JsonEventStream: Handles JSON server-sent event stream result extraction\n */\nexport const ResultExtractors = {\n Exchange: ExchangeResultExtractor,\n Response: ResponseResultExtractor,\n Json: JsonResultExtractor,\n Text: TextResultExtractor,\n EventStream: EventStreamResultExtractor,\n JsonEventStream: JsonEventStreamResultExtractor,\n DEFAULT: JsonResultExtractor,\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n combineURLs,\n Fetcher, fetcher,\n type FetchExchangeInit,\n FetchRequestInit,\n mergeRequest,\n NamedCapable,\n type RequestHeaders,\n ResultExtractor,\n type UrlParams,\n} from '@ahoo-wang/fetcher';\nimport { ApiMetadata } from './apiDecorator';\nimport { EndpointMetadata } from './endpointDecorator';\nimport { ParameterMetadata, ParameterRequest, ParameterType } from './parameterDecorator';\nimport { getFetcher } from './fetcherCapable';\nimport { ResultExtractors } from './resultExtractor';\n\n/**\n * Metadata container for a function with HTTP endpoint decorators.\n *\n * Encapsulates all the metadata needed to execute an HTTP request\n * for a decorated method, including API-level defaults, endpoint-specific\n * configuration, and parameter metadata.\n */\nexport class FunctionMetadata implements NamedCapable {\n /**\n * Name of the function.\n */\n name: string;\n\n /**\n * API-level metadata (class-level configuration).\n */\n api: ApiMetadata;\n\n /**\n * Endpoint-level metadata (method-level configuration).\n */\n endpoint: EndpointMetadata;\n\n /**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter decorated with @path, @query,\n * @header, or @body decorators. Stored as a Map keyed by parameter index.\n *\n * @remarks\n * The metadata is stored as a Map<number, ParameterMetadata> where the key is\n * the parameter index and the value is the parameter metadata. This ensures\n * correct parameter ordering regardless of decorator application order.\n */\n parameters: Map<number, ParameterMetadata>;\n\n /**\n * Creates a new FunctionMetadata instance.\n *\n * @param name - The name of the function\n * @param api - API-level metadata\n * @param endpoint - Endpoint-level metadata\n * @param parameters - Parameter metadata array\n */\n constructor(\n name: string,\n api: ApiMetadata,\n endpoint: EndpointMetadata,\n parameters: Map<number, ParameterMetadata>,\n ) {\n this.name = name;\n this.api = api;\n this.endpoint = endpoint;\n this.parameters = parameters;\n }\n\n /**\n * Gets the fetcher instance to use for this function.\n *\n * Returns the fetcher specified in the endpoint metadata, or the API metadata,\n * or falls back to the default fetcher if none is specified.\n *\n * @returns The fetcher instance\n */\n get fetcher(): Fetcher {\n return getFetcher(this.endpoint.fetcher ?? this.api.fetcher) ?? fetcher;\n }\n\n /**\n * Resolves the complete path by combining base path and endpoint path\n *\n * @param parameterPath - Optional path parameter to use instead of endpoint path\n * @returns The combined URL path\n */\n resolvePath(parameterPath?: string): string {\n // Get the base path from endpoint, API, or default to empty string\n const basePath = this.endpoint.basePath || this.api.basePath || '';\n\n // Use provided parameter path or fallback to endpoint path\n const endpointPath = parameterPath || this.endpoint.path || '';\n\n // Combine the base path and endpoint path into a complete URL\n return combineURLs(basePath, endpointPath);\n }\n\n /**\n * Resolves the timeout for the request.\n *\n * Returns the timeout specified in the endpoint metadata, or the API metadata,\n * or undefined if no timeout is specified.\n *\n * @returns The timeout value in milliseconds, or undefined\n */\n resolveTimeout(): number | undefined {\n return this.endpoint.timeout || this.api.timeout;\n }\n\n resolveResultExtractor(): ResultExtractor<any> {\n return (\n this.endpoint.resultExtractor ||\n this.api.resultExtractor ||\n ResultExtractors.DEFAULT\n );\n }\n\n resolveAttributes(): Record<string, any> {\n return {\n ...this.api.attributes,\n ...this.endpoint.attributes,\n };\n }\n\n /**\n * Resolves the request configuration from the method arguments.\n *\n * This method processes the runtime arguments according to the parameter metadata\n * and constructs a FetcherRequest object with path parameters, query parameters,\n * headers, body, and timeout. It handles various parameter types including:\n * - Path parameters (@path decorator)\n * - Query parameters (@query decorator)\n * - Header parameters (@header decorator)\n * - Body parameter (@body decorator)\n * - Complete request object (@request decorator)\n * - AbortSignal for request cancellation\n *\n * The method uses mergeRequest to combine the endpoint-specific configuration\n * with the parameter-provided request object, where the parameter request\n * takes precedence over endpoint configuration.\n *\n * @param args - The runtime arguments passed to the method\n * @returns A FetcherRequest object with all request configuration\n *\n * @example\n * ```typescript\n * // For a method decorated like:\n * @get('/users/{id}')\n * getUser(\n * @path('id') id: number,\n * @query('include') include: string,\n * @header('Authorization') auth: string\n * ): Promise<Response>\n *\n * // Calling with: getUser(123, 'profile', 'Bearer token')\n * // Would produce a request with:\n * // {\n * // method: 'GET',\n * // urlParams: {\n * // path: { id: 123 },\n * // query: { include: 'profile' }\n * // },\n * // headers: {\n * // 'Authorization': 'Bearer token',\n * // ...apiHeaders,\n * // ...endpointHeaders\n * // }\n * // }\n * ```\n */\n resolveExchangeInit(args: any[]): Required<Pick<FetchExchangeInit, 'request' | 'attributes'>> {\n const pathParams: Record<string, any> = {};\n const queryParams: Record<string, any> = {};\n const headers: RequestHeaders = {\n ...this.api.headers,\n ...this.endpoint.headers,\n };\n let body: any = undefined;\n let signal: AbortSignal | null | undefined = undefined;\n let abortController: AbortController | null | undefined = undefined;\n let parameterRequest: ParameterRequest = {};\n const attributes: Record<string, any> = this.resolveAttributes();\n // Process parameters based on their decorators\n args.forEach((value, index) => {\n if (value instanceof AbortSignal) {\n signal = value;\n return;\n }\n if (value instanceof AbortController) {\n abortController = value;\n return;\n }\n const funParameter = this.parameters.get(index);\n if (!funParameter) {\n return;\n }\n switch (funParameter.type) {\n case ParameterType.PATH:\n this.processPathParam(funParameter, value, pathParams);\n break;\n case ParameterType.QUERY:\n this.processQueryParam(funParameter, value, queryParams);\n break;\n case ParameterType.HEADER:\n this.processHeaderParam(funParameter, value, headers);\n break;\n case ParameterType.BODY:\n body = value;\n break;\n case ParameterType.REQUEST:\n parameterRequest = this.processRequestParam(value);\n break;\n case ParameterType.ATTRIBUTE:\n this.processAttributeParam(funParameter, value, attributes);\n break;\n case ParameterType.ATTRIBUTES:\n this.processAttributesParam(value, attributes);\n break;\n }\n });\n const urlParams: UrlParams = {\n path: pathParams,\n query: queryParams,\n };\n const endpointRequest: FetchRequestInit = {\n method: this.endpoint.method,\n urlParams,\n headers,\n body,\n timeout: this.resolveTimeout(),\n signal,\n abortController,\n };\n const mergedRequest = mergeRequest(\n endpointRequest,\n parameterRequest,\n ) as any;\n const parameterPath = parameterRequest.path;\n mergedRequest.url = this.resolvePath(parameterPath);\n return {\n request: mergedRequest,\n attributes,\n };\n }\n\n private processPathParam(\n param: ParameterMetadata,\n value: any,\n path: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n path[paramName] = value;\n }\n\n private processQueryParam(\n param: ParameterMetadata,\n value: any,\n query: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n query[paramName] = value;\n }\n\n private processHeaderParam(\n param: ParameterMetadata,\n value: any,\n headers: RequestHeaders,\n ) {\n if (param.name && value !== undefined) {\n headers[param.name] = String(value);\n }\n }\n\n /**\n * Processes a request parameter value.\n *\n * This method handles the @request() decorator parameter by casting\n * the provided value to a FetcherRequest. The @request() decorator\n * allows users to pass a complete FetcherRequest object to customize\n * the request configuration.\n *\n * @param value - The value provided for the @request() parameter\n * @returns The value cast to FetcherRequest type\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: FetcherRequest): Promise<Response>\n *\n * // Usage:\n * const customRequest: FetcherRequest = {\n * headers: { 'X-Custom': 'value' },\n * timeout: 5000\n * };\n * await service.createUsers(customRequest);\n * ```\n */\n private processRequestParam(value: any): ParameterRequest {\n if (!value) {\n return {};\n }\n\n const request = value as ParameterRequest;\n // 确保请求对象中的属性被正确保留\n return {\n ...request,\n headers: request.headers || {},\n urlParams: request.urlParams || { path: {}, query: {} },\n };\n }\n\n\n private processAttributeParam(\n param: ParameterMetadata,\n value: any,\n attributes: Record<string, any>,\n ) {\n if (param.name && value !== undefined) {\n attributes[param.name] = value;\n }\n }\n\n private processAttributesParam(\n value: any,\n attributes: Record<string, any>,\n ) {\n if (typeof value !== 'object') {\n throw new Error('@attributes() parameter must be an object');\n }\n Object.keys(value).forEach(key => {\n attributes[key] = value[key];\n });\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AttributesCapable,\n Fetcher,\n type RequestHeaders,\n type RequestHeadersCapable,\n type TimeoutCapable,\n} from '@ahoo-wang/fetcher';\nimport { ENDPOINT_METADATA_KEY } from './endpointDecorator';\nimport { RequestExecutor } from './requestExecutor';\nimport { PARAMETER_METADATA_KEY } from './parameterDecorator';\nimport 'reflect-metadata';\nimport { type ResultExtractorCapable } from './resultExtractor';\nimport { type FetcherCapable } from './fetcherCapable';\nimport { FunctionMetadata } from './functionMetadata';\n\n/**\n * Metadata for class-level API configuration.\n *\n * Defines the configuration options that can be applied to an entire API class.\n * These settings will be used as defaults for all endpoints within the class unless overridden\n * at the method level.\n */\nexport interface ApiMetadata\n extends TimeoutCapable,\n RequestHeadersCapable,\n ResultExtractorCapable,\n FetcherCapable, AttributesCapable {\n /**\n * Base path for all endpoints in the class.\n *\n * This path will be prepended to all endpoint paths defined in the class.\n * For example, if basePath is '/api/v1' and an endpoint has path '/users',\n * the full path will be '/api/v1/users'.\n */\n basePath?: string;\n\n /**\n * Default headers for all requests in the class.\n *\n * These headers will be included in every request made by methods in this class.\n * They can be overridden or extended at the method level.\n */\n headers?: RequestHeaders;\n\n /**\n * Default timeout for all requests in the class (in milliseconds).\n *\n * This timeout value will be applied to all requests made by methods in this class.\n * Individual methods can specify their own timeout values to override this default.\n */\n timeout?: number;\n\n /**\n * Name of the fetcher instance to use, default: 'default'.\n *\n * This allows you to specify which fetcher instance should be used for requests\n * from this API class. The fetcher must be registered with the FetcherRegistrar.\n */\n fetcher?: string | Fetcher;\n}\n\nexport const API_METADATA_KEY = Symbol('api:metadata');\n\n/**\n * Binds a request executor to a method, replacing the original method with\n * an implementation that makes HTTP requests based on the decorator metadata.\n *\n * @param constructor - The class constructor\n * @param functionName - The name of the method to bind\n * @param apiMetadata - The API metadata for the class\n */\nfunction bindExecutor<T extends new (...args: any[]) => any>(\n constructor: T,\n functionName: string,\n apiMetadata: ApiMetadata,\n) {\n const endpointFunction = constructor.prototype[functionName];\n if (functionName === 'constructor') {\n return;\n }\n if (typeof endpointFunction !== 'function') {\n return;\n }\n\n const endpointMetadata = Reflect.getMetadata(\n ENDPOINT_METADATA_KEY,\n constructor.prototype,\n functionName,\n );\n if (!endpointMetadata) {\n return;\n }\n // Get parameter metadata for this method\n const parameterMetadata =\n Reflect.getMetadata(\n PARAMETER_METADATA_KEY,\n constructor.prototype,\n functionName,\n ) || new Map();\n\n // Create function metadata\n const functionMetadata = new FunctionMetadata(\n functionName,\n apiMetadata,\n endpointMetadata,\n parameterMetadata,\n );\n\n // Create request executor\n const requestExecutor = new RequestExecutor(functionMetadata);\n\n // Replace method with actual implementation\n constructor.prototype[functionName] = function(...args: unknown[]) {\n return requestExecutor.execute(this, args);\n };\n}\n\nexport function api(\n basePath: string = '',\n metadata: Omit<ApiMetadata, 'basePath'> = {},\n) {\n return function <T extends new (...args: any[]) => any>(constructor: T): T {\n const apiMetadata: ApiMetadata = {\n basePath,\n ...metadata,\n };\n\n // Store metadata directly on the class constructor\n Reflect.defineMetadata(API_METADATA_KEY, apiMetadata, constructor);\n\n // Override prototype methods to implement actual HTTP calls\n Object.getOwnPropertyNames(constructor.prototype).forEach(functionName => {\n bindExecutor(constructor, functionName, apiMetadata);\n });\n\n return constructor;\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Custom error class that indicates a method implementation will be automatically generated.\n *\n * @example\n * ```\n * @post()\n * createUser(@body() user: User):Promise<Response> {\n * throw autoGeneratedError(user);\n * }\n * ```\n */\nexport class AutoGenerated extends Error {\n constructor() {\n super('Implementation will be generated automatically.');\n this.name = 'AutoGenerated';\n }\n}\n\n/**\n * Factory function that creates an AutoGenerated error instance.\n * This is typically used in methods that will be automatically implemented,\n * where a placeholder implementation is needed.\n *\n * @param _ignored - Arguments (such as 'user' in the example) are ignored to prevent\n * ESLint no-unused-vars errors in method signatures that will be auto-generated.\n * @returns A new AutoGenerated error instance\n */\nexport const autoGeneratedError = (..._ignored: any[]): AutoGenerated => {\n return new AutoGenerated();\n};\n"],"names":["ENDPOINT_METADATA_KEY","endpoint","method","path","metadata","target","propertyKey","endpointMetadata","get","HttpMethod","post","put","del","patch","head","options","TARGET_FETCHER_PROPERTY","DECORATOR_TARGET_ATTRIBUTE_KEY","RequestExecutor","fetcher","Fetcher","args","exchangeInit","extractor","parameterNameCache","getParameterNames","func","fnStr","paramsStr","extractParameterString","hasParameters","emptyResult","result","parseParameterNames","errorResult","getParameterName","parameterIndex","providedName","paramNames","endParenIndex","findClosingParenthesis","startParenIndex","str","openingParenIndex","parenDepth","i","char","trimWhitespace","isNotEmpty","extractParameterName","param","cleanedParam","removeDefaultValue","removeTypeAnnotation","equalsIndex","colonIndex","ParameterType","PARAMETER_METADATA_KEY","parameter","type","name","paramName","existingParameters","parameterMetadata","query","header","body","request","attribute","attributes","getFetcher","fetcherRegistrar","ResultExtractors","ExchangeResultExtractor","ResponseResultExtractor","JsonResultExtractor","TextResultExtractor","EventStreamResultExtractor","JsonEventStreamResultExtractor","FunctionMetadata","api","parameters","parameterPath","basePath","endpointPath","combineURLs","pathParams","queryParams","headers","signal","abortController","parameterRequest","value","index","funParameter","urlParams","endpointRequest","mergedRequest","mergeRequest","key","API_METADATA_KEY","bindExecutor","constructor","functionName","apiMetadata","endpointFunction","functionMetadata","requestExecutor","AutoGenerated","autoGeneratedError","_ignored"],"mappings":";;;AAiCO,MAAMA,IAAwB,OAAO,mBAAmB;AA4BxD,SAASC,EACdC,GACAC,GACAC,IAAmC,CAAA,GACnC;AACA,SAAO,SAASC,GAAgBC,GAAoC;AAElE,UAAMC,IAAmB;AAAA,MACvB,QAAAL;AAAA,MACA,MAAAC;AAAA,MACA,GAAGC;AAAA,IAAA;AAEL,YAAQ;AAAA,MACNJ;AAAA,MACAO;A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,SAAiDkG,GAAmB;AACzE,UAAME,IAA2B;AAAA,MAC/B,UAAArB;AAAA,MACA,GAAG/E;AAAA,IAAA;AAIL,mBAAQ,eAAegG,GAAkBI,GAAaF,CAAW,GAGjE,OAAO,oBAAoBA,EAAY,SAAS,EAAE,QAAQ,CAAAC,MAAgB;AACxE,MAAAF,EAAaC,GAAaC,GAAcC,CAAW;AAAA,IACrD,CAAC,GAEMF;AAAA,EACT;AACF;AC9HO,MAAMM,WAAsB,MAAM;AAAA,EACvC,cAAc;AACZ,UAAM,iDAAiD,GACvD,KAAK,OAAO;AAAA,EACd;AACF;AAWO,MAAMC,KAAqB,IAAIC,MAC7B,IAAIF,GAAA;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/endpointDecorator.ts","../src/requestExecutor.ts","../src/reflection.ts","../src/parameterDecorator.ts","../src/fetcherCapable.ts","../src/resultExtractor.ts","../src/functionMetadata.ts","../src/apiDecorator.ts","../src/generated.ts"],"sourcesContent":["import { HttpMethod, type ResultExtractorCapable } from '@ahoo-wang/fetcher';\nimport { type ApiMetadata } from './apiDecorator';\nimport 'reflect-metadata';\n\nexport interface PathCapable {\n /**\n * Path for the endpoint (relative to class base path).\n *\n * This path will be appended to the class's base path to form the complete URL.\n * Path parameters can be specified using curly braces, e.g., '/users/{id}'\n */\n path?: string;\n}\n\n/**\n * Metadata for HTTP endpoints.\n *\n * Defines the configuration options for individual HTTP endpoints (methods).\n * These settings will override any corresponding class-level settings from ApiMetadata.\n */\nexport interface EndpointMetadata\n extends ApiMetadata,\n ResultExtractorCapable,\n PathCapable {\n /**\n * HTTP method for the endpoint.\n *\n * Specifies the HTTP verb to be used for this endpoint (GET, POST, PUT, DELETE, etc.)\n */\n method?: HttpMethod;\n}\n\nexport const ENDPOINT_METADATA_KEY = Symbol('endpoint:metadata');\n\nexport type MethodEndpointMetadata = Omit<EndpointMetadata, 'method' | 'path'>;\n\n/**\n * Decorator factory for defining HTTP endpoints.\n *\n * Creates a decorator that can be used to define HTTP endpoints\n * on class methods. It stores metadata about the endpoint that will be used\n * to generate the actual HTTP request.\n *\n * @param method - The HTTP method for this endpoint\n * @param path - The path for this endpoint (relative to class base path)\n * @param metadata - Additional endpoint metadata (headers, timeout, etc.)\n * @returns A method decorator function\n *\n * @example\n * ```typescript\n * @api('/api/v1')\n * class UserService {\n * @endpoint(HttpMethod.GET, '/users/{id}')\n * getUser(@path('id') id: string): Promise<Response> {\n * // Implementation will be generated automatically\n * throw autoGeneratedError();\n * }\n * }\n * ```\n */\nexport function endpoint(\n method?: HttpMethod,\n path?: string,\n metadata: MethodEndpointMetadata = {},\n) {\n return function(target: object, propertyKey: string | symbol): void {\n // Store metadata directly on the method\n const endpointMetadata = {\n method: method,\n path,\n ...metadata,\n };\n Reflect.defineMetadata(\n ENDPOINT_METADATA_KEY,\n endpointMetadata,\n target,\n propertyKey,\n );\n };\n}\n\nexport function get(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.GET, path, metadata);\n}\n\nexport function post(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.POST, path, metadata);\n}\n\nexport function put(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.PUT, path, metadata);\n}\n\nexport function del(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.DELETE, path, metadata);\n}\n\nexport function patch(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.PATCH, path, metadata);\n}\n\nexport function head(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.HEAD, path, metadata);\n}\n\nexport function options(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.OPTIONS, path, metadata);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Fetcher } from '@ahoo-wang/fetcher';\nimport { FunctionMetadata } from './functionMetadata';\n\nconst TARGET_FETCHER_PROPERTY = 'fetcher';\n\nexport const DECORATOR_TARGET_ATTRIBUTE_KEY = '__decorator_target__';\n\n/**\n * Executor for HTTP requests based on decorated method metadata.\n *\n * This class is responsible for executing HTTP requests based on the metadata\n * collected from decorators. It resolves the path, constructs the request,\n * and executes it using the appropriate fetcher.\n */\nexport class RequestExecutor {\n private readonly metadata: FunctionMetadata;\n\n /**\n * Creates a new RequestExecutor instance.\n *\n * @param metadata - The function metadata containing all request information\n */\n constructor(metadata: FunctionMetadata) {\n this.metadata = metadata;\n }\n\n /**\n * Retrieves the fetcher instance from the target object.\n *\n * @param target - The target object that may contain a fetcher property\n * @returns The fetcher instance if exists, otherwise undefined\n */\n private getTargetFetcher(target: any): Fetcher | undefined {\n if (!target || typeof target !== 'object') {\n return undefined;\n }\n // Extract the fetcher property from the target object\n const fetcher = target[TARGET_FETCHER_PROPERTY];\n\n // Validate that the fetcher is an instance of the Fetcher class\n if (fetcher instanceof Fetcher) {\n return fetcher;\n }\n\n // Return undefined if no valid fetcher instance is found\n return undefined;\n }\n\n /**\n * Executes the HTTP request.\n *\n * This method resolves the path and request configuration from the metadata\n * and arguments, then executes the request using the configured fetcher.\n * It handles the complete request lifecycle from parameter processing to\n * response extraction.\n *\n * @param target - The target object that the method is called on.\n * This can contain a custom fetcher instance in its 'fetcher' property.\n * @param args - The runtime arguments passed to the decorated method.\n * These are mapped to request components based on parameter decorators.\n * @returns A Promise that resolves to the extracted result based on the configured result extractor.\n * By default, this is the Response object, but can be customized to return\n * parsed JSON, the raw exchange object, or any other transformed result.\n *\n * @example\n * ```typescript\n * // Given a decorated service method:\n * class UserService {\n * @get('/users/{id}')\n * getUser(@path('id') id: number): Promise<Response> {\n * // This method body is replaced by the executor at runtime\n * }\n * }\n *\n * // When calling:\n * const userService = new UserService();\n * const response = await userService.getUser(123);\n *\n * // The execute method will:\n * // 1. Resolve the path to '/users/123'\n * // 2. Create a request with method 'GET'\n * // 3. Execute the request using the configured fetcher\n * // 4. Return the Response object\n * ```\n */\n async execute(target: any, args: any[]): Promise<any> {\n const fetcher = this.getTargetFetcher(target) || this.metadata.fetcher;\n const exchangeInit = this.metadata.resolveExchangeInit(args);\n exchangeInit.attributes?.set(DECORATOR_TARGET_ATTRIBUTE_KEY, target);\n const extractor = this.metadata.resolveResultExtractor();\n return fetcher.request(exchangeInit.request, { resultExtractor: extractor, attributes: exchangeInit.attributes });\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Cache for storing previously extracted parameter names to improve performance\nconst parameterNameCache = new WeakMap<Function, string[]>();\n\n/**\n * Extracts parameter names from a function.\n *\n * This function parses the string representation of a function to extract\n * the names of its parameters. It handles various function formats including\n * regular functions, arrow functions, and methods.\n *\n * Note: This implementation provides basic parameter name extraction and may not\n * handle all edge cases of complex TypeScript parameter declarations.\n *\n * @param func - The function to extract parameter names from\n * @returns An array of parameter names, or an empty array if extraction fails\n * @throws {TypeError} If the input is not a function\n *\n * @example\n * ```typescript\n * function example(a, b, c) {}\n * const paramNames = getParameterNames(example);\n * // Returns: ['a', 'b', 'c']\n *\n * const arrowFunc = (x, y) => x + y;\n * const arrowParamNames = getParameterNames(arrowFunc);\n * // Returns: ['x', 'y']\n *\n * function complex(param1: string, param2: number = 10, ...rest: any[]) {}\n * const complexParamNames = getParameterNames(complex);\n * // Returns: ['param1', 'param2', '...rest']\n * ```\n */\nexport function getParameterNames(func: (...args: any[]) => any): string[] {\n // Validate that the input is a function\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n // Check cache first to improve performance\n if (parameterNameCache.has(func)) {\n return parameterNameCache.get(func)!;\n }\n\n try {\n // Convert function to string and trim whitespace\n const fnStr = func.toString().trim();\n\n // Extract parameter string from the function\n const paramsStr = extractParameterString(fnStr);\n\n // Handle empty parameters\n if (!hasParameters(paramsStr)) {\n const emptyResult: string[] = [];\n parameterNameCache.set(func, emptyResult);\n return emptyResult;\n }\n\n // Parse and clean parameter names\n const result = parseParameterNames(paramsStr);\n parameterNameCache.set(func, result);\n return result;\n } catch {\n // Return empty array on any parsing errors to avoid breaking the application\n const errorResult: string[] = [];\n parameterNameCache.set(func, errorResult);\n return errorResult;\n }\n}\n\n/**\n * Helper function to automatically extract parameter name when not provided.\n *\n * @param target - The target object (class prototype)\n * @param propertyKey - The method name\n * @param parameterIndex - The index of the parameter\n * @param providedName - The name explicitly provided by the user (if any)\n * @returns The parameter name, either provided or automatically extracted\n */\nexport function getParameterName(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n providedName?: string,\n): string | undefined {\n // If a name was explicitly provided, use it\n if (providedName) {\n return providedName;\n }\n\n // Try to automatically extract the parameter name\n try {\n const method = target[propertyKey as keyof typeof target];\n if (method && typeof method === 'function') {\n const paramNames = getParameterNames(method);\n if (parameterIndex < paramNames.length) {\n return paramNames[parameterIndex];\n }\n }\n } catch {\n // If we can't get the parameter name, return undefined\n // This will use default naming in the execution logic\n }\n\n return undefined;\n}\n\n/**\n * Checks if a parameter string contains actual parameters.\n *\n * @param paramsStr - The parameter string to check\n * @returns True if the string contains parameters, false otherwise\n */\nfunction hasParameters(paramsStr: string): boolean {\n return (\n paramsStr !== null && paramsStr !== undefined && paramsStr.trim() !== ''\n );\n}\n\n/**\n * Extracts the parameter string from a function string representation.\n *\n * @param fnStr - The string representation of the function\n * @returns The parameter string, or empty string if not found\n */\nfunction extractParameterString(fnStr: string): string {\n // Handle arrow functions that start with parentheses\n if (fnStr.startsWith('(')) {\n const endParenIndex = findClosingParenthesis(fnStr, 0);\n if (endParenIndex === -1) return '';\n return fnStr.substring(1, endParenIndex);\n }\n\n // Handle regular functions, async functions, and methods\n const startParenIndex = fnStr.indexOf('(');\n if (startParenIndex === -1) return '';\n\n const endParenIndex = findClosingParenthesis(fnStr, startParenIndex);\n if (endParenIndex === -1) return '';\n\n return fnStr.substring(startParenIndex + 1, endParenIndex);\n}\n\n/**\n * Finds the matching closing parenthesis for an opening parenthesis.\n *\n * @param str - The string to search in\n * @param openingParenIndex - The index of the opening parenthesis\n * @returns The index of the matching closing parenthesis, or -1 if not found\n */\nfunction findClosingParenthesis(\n str: string,\n openingParenIndex: number,\n): number {\n let parenDepth = 1;\n\n for (let i = openingParenIndex + 1; i < str.length; i++) {\n const char = str[i];\n\n if (char === '(') {\n parenDepth++;\n } else if (char === ')') {\n parenDepth--;\n if (parenDepth === 0) {\n return i;\n }\n }\n }\n\n return -1; // No matching closing parenthesis found\n}\n\n/**\n * Parses and cleans parameter names from a parameter string.\n *\n * @param paramsStr - The parameter string to parse\n * @returns An array of cleaned parameter names\n */\nfunction parseParameterNames(paramsStr: string): string[] {\n return paramsStr\n .split(',')\n .map(trimWhitespace)\n .filter(isNotEmpty)\n .map(extractParameterName);\n}\n\n/**\n * Trims whitespace from a string.\n *\n * @param str - The string to trim\n * @returns The trimmed string\n */\nfunction trimWhitespace(str: string): string {\n return str.trim();\n}\n\n/**\n * Checks if a string is not empty.\n *\n * @param str - The string to check\n * @returns True if the string is not empty, false otherwise\n */\nfunction isNotEmpty(str: string): boolean {\n return str.length > 0;\n}\n\n/**\n * Extracts a clean parameter name by removing type annotations and default values.\n *\n * @param param - The raw parameter string\n * @returns The cleaned parameter name\n */\nfunction extractParameterName(param: string): string {\n // Remove default value assignment (everything after =)\n let cleanedParam = removeDefaultValue(param);\n\n // Remove type annotations (everything after :)\n cleanedParam = removeTypeAnnotation(cleanedParam);\n\n return cleanedParam.trim();\n}\n\n/**\n * Removes default value from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without default value\n */\nfunction removeDefaultValue(param: string): string {\n const equalsIndex = param.indexOf('=');\n if (equalsIndex !== -1) {\n return param.substring(0, equalsIndex);\n }\n return param;\n}\n\n/**\n * Removes type annotation from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without type annotation\n */\nfunction removeTypeAnnotation(param: string): string {\n const colonIndex = param.indexOf(':');\n if (colonIndex !== -1) {\n return param.substring(0, colonIndex);\n }\n return param;\n}\n","import { getParameterName } from './reflection';\nimport 'reflect-metadata';\nimport { type PathCapable } from './endpointDecorator';\nimport { type FetchRequestInit } from '@ahoo-wang/fetcher';\n\n/**\n * Parameter types for decorator parameters.\n *\n * Defines the different types of parameters that can be used\n * in API method decorators to specify how arguments should be handled\n * in the HTTP request.\n */\nexport enum ParameterType {\n /**\n * Path parameter that will be inserted into the URL path.\n *\n * Path parameters are used to specify dynamic parts of the URL path.\n * They are defined using curly braces in the endpoint path.\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n * ```\n */\n PATH = 'path',\n\n /**\n * Query parameter that will be appended to the URL query string.\n *\n * Query parameters are used to pass non-hierarchical data to the server.\n * They appear after the '?' in the URL.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n * ```\n */\n QUERY = 'query',\n\n /**\n * Header parameter that will be added to the request headers.\n *\n * Header parameters are used to pass metadata about the request,\n * such as authentication tokens or content type information.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n * ```\n */\n HEADER = 'header',\n\n /**\n * Body parameter that will be sent as the request body.\n *\n * The body parameter represents the main data payload of the request.\n * It is typically used with POST, PUT, and PATCH requests.\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\n BODY = 'body',\n\n /**\n * Request parameter that will be used as the request object.\n */\n REQUEST = 'request',\n\n\n /**\n * Attribute parameter that will be used as a single attribute in the request attributes.\n *\n * The attribute parameter allows passing a single key-value pair that will be added\n * to the request attributes object. This is useful for passing specific contextual\n * information that can be accessed by interceptors.\n */\n ATTRIBUTE = 'attribute',\n /**\n * Attributes parameter that will be used as the request attributes.\n *\n * The attributes parameter allows passing custom data that can be accessed\n * by interceptors throughout the request lifecycle. This is useful for\n * sharing contextual information between different parts of the request processing.\n */\n ATTRIBUTES = 'attributes'\n}\n\n/**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter\n * decorated with @path, @query, @header, or @body decorators.\n */\nexport interface ParameterMetadata {\n /**\n * Type of parameter (path, query, header, body).\n *\n * Specifies how this parameter should be handled in the HTTP request.\n */\n type: ParameterType;\n\n /**\n * Name of the parameter (used for path, query, and header parameters).\n *\n * For path and query parameters, this corresponds to the key in the URL.\n * For header parameters, this corresponds to the header name.\n * For body parameters, this is not used.\n */\n name?: string;\n\n /**\n * Index of the parameter in the method signature.\n *\n * This is used to map the runtime argument values to the correct parameter metadata.\n */\n index: number;\n}\n\nexport const PARAMETER_METADATA_KEY = Symbol('parameter:metadata');\n\n/**\n * Decorator factory for method parameters.\n *\n * Creates a decorator that can be used to specify how a method parameter\n * should be handled in the HTTP request. It stores metadata about the parameter\n * that will be used during request execution.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param type - The type of parameter (PATH, QUERY, HEADER, or BODY)\n * @param name - The name of the parameter (used for path, query, and header parameters, optional - auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@parameter(ParameterType.PATH, 'id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@parameter(ParameterType.PATH) userId: string): Promise<Response>\n * ```\n */\nexport function parameter(type: ParameterType, name: string = '') {\n return function(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n ) {\n const paramName = getParameterName(\n target,\n propertyKey as string,\n parameterIndex,\n name,\n );\n\n const existingParameters: Map<number, ParameterMetadata> =\n Reflect.getMetadata(PARAMETER_METADATA_KEY, target, propertyKey) ||\n new Map();\n const parameterMetadata: ParameterMetadata = {\n type: type,\n name: paramName,\n index: parameterIndex,\n };\n existingParameters.set(parameterIndex, parameterMetadata);\n Reflect.defineMetadata(\n PARAMETER_METADATA_KEY,\n existingParameters,\n target,\n propertyKey,\n );\n };\n}\n\n/**\n * Path parameter decorator.\n *\n * Defines a path parameter that will be inserted into the URL path.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the path parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@path() userId: string): Promise<Response>\n * ```\n */\nexport function path(name: string = '') {\n return parameter(ParameterType.PATH, name);\n}\n\n/**\n * Query parameter decorator.\n *\n * Defines a query parameter that will be appended to the URL query string.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the query parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@query() limit: number): Promise<Response>\n * ```\n */\nexport function query(name: string = '') {\n return parameter(ParameterType.QUERY, name);\n}\n\n/**\n * Header parameter decorator.\n *\n * Defines a header parameter that will be added to the request headers.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the header parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@header() authorization: string): Promise<Response>\n * ```\n */\nexport function header(name: string = '') {\n return parameter(ParameterType.HEADER, name);\n}\n\n/**\n * Body parameter decorator.\n *\n * Defines a body parameter that will be sent as the request body.\n * Note that body parameters don't have names since there's only one body per request.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\nexport function body() {\n return parameter(ParameterType.BODY);\n}\n\n/**\n * Interface for request parameter objects.\n *\n * Combines FetchRequestInit and PathCapable interfaces to provide\n * a complete request configuration object that can be used with\n * the @request() decorator. This allows full customization of\n * the HTTP request including method, headers, body, and URL parameters.\n */\nexport interface ParameterRequest extends FetchRequestInit, PathCapable {\n}\n\n/**\n * Request parameter decorator.\n *\n * Defines a request parameter that will be used as the base request object.\n * This allows you to pass a complete ParameterRequest object to customize\n * the request configuration.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: ParameterRequest): Promise<Response>\n * ```\n */\nexport function request() {\n return parameter(ParameterType.REQUEST);\n}\n\n/**\n * Parameter decorator for adding a single attribute to the request attributes.\n *\n * This decorator allows you to pass a key-value pair as an attribute that can be accessed\n * by interceptors during the request lifecycle. If no name is provided, the parameter's\n * property name will be used as the attribute key.\n *\n * @param name - Optional name for the attribute. If not provided, the parameter's property name will be used.\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute('userId') userId: string): Promise<Response>\n *\n * // Using property name as attribute key\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute() userId: string): Promise<Response>\n * ```\n */\nexport function attribute(name: string = '') {\n return parameter(ParameterType.ATTRIBUTE, name);\n}\n\n/**\n * Parameter decorator for adding multiple attributes to the request.\n *\n * This decorator allows you to pass an entire object as attributes that can be accessed\n * by interceptors during the request lifecycle. The parameter should be an object whose\n * properties will be merged into the request attributes.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attributes() attrs: Record<string, any>): Promise<Response>\n * ```\n */\nexport function attributes() {\n return parameter(ParameterType.ATTRIBUTES);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';\n\n/**\n * Interface that defines a capability for objects that can have a fetcher.\n * This interface is typically used to mark components or objects that can perform fetching operations\n * and may need access to fetcher functionality.\n */\nexport interface FetcherCapable {\n /**\n * Optional fetcher property that can be either a string identifier or a Fetcher instance.\n * When present, this property indicates the fetcher associated with the implementing object.\n */\n fetcher?: string | Fetcher;\n}\n\n/**\n * Gets a Fetcher instance based on the provided fetcher parameter.\n *\n * @param fetcher - A string identifier or Fetcher instance to resolve\n * @returns A Fetcher instance if found, undefined otherwise\n */\nexport function getFetcher(fetcher?: string | Fetcher): Fetcher | undefined {\n // Return undefined if no fetcher is provided\n if (!fetcher) {\n return undefined;\n }\n\n // Return the fetcher directly if it's already a Fetcher instance,\n // otherwise resolve it through the fetcher registrar\n return fetcher instanceof Fetcher\n ? fetcher\n : fetcherRegistrar.requiredGet(fetcher);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ExchangeResultExtractor,\n JsonResultExtractor,\n ResponseResultExtractor,\n TextResultExtractor,\n} from '@ahoo-wang/fetcher';\nimport {\n EventStreamResultExtractor,\n JsonEventStreamResultExtractor,\n} from '@ahoo-wang/fetcher-eventstream';\n\n/**\n * ResultExtractors is an object that maps result extractor names to their corresponding\n * extractor functions. These extractors are used to process and extract data from different\n * types of responses or results in the application.\n *\n * Each property represents a specific type of result extractor:\n * - Exchange: Handles exchange-related result extraction\n * - Response: Handles general response result extraction\n * - Json: Handles JSON format result extraction\n * - Text: Handles plain text result extraction\n * - EventStream: Handles server-sent event stream result extraction\n * - JsonEventStream: Handles JSON server-sent event stream result extraction\n */\nexport const ResultExtractors = {\n Exchange: ExchangeResultExtractor,\n Response: ResponseResultExtractor,\n Json: JsonResultExtractor,\n Text: TextResultExtractor,\n EventStream: EventStreamResultExtractor,\n JsonEventStream: JsonEventStreamResultExtractor,\n DEFAULT: JsonResultExtractor,\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n combineURLs,\n Fetcher, fetcher,\n type FetchExchangeInit,\n FetchRequestInit, mergeRecordToMap,\n mergeRequest,\n NamedCapable,\n type RequestHeaders,\n ResultExtractor,\n type UrlParams,\n} from '@ahoo-wang/fetcher';\nimport { ApiMetadata } from './apiDecorator';\nimport { EndpointMetadata } from './endpointDecorator';\nimport { ParameterMetadata, ParameterRequest, ParameterType } from './parameterDecorator';\nimport { getFetcher } from './fetcherCapable';\nimport { ResultExtractors } from './resultExtractor';\n\n/**\n * Metadata container for a function with HTTP endpoint decorators.\n *\n * Encapsulates all the metadata needed to execute an HTTP request\n * for a decorated method, including API-level defaults, endpoint-specific\n * configuration, and parameter metadata.\n */\nexport class FunctionMetadata implements NamedCapable {\n /**\n * Name of the function.\n */\n name: string;\n\n /**\n * API-level metadata (class-level configuration).\n */\n api: ApiMetadata;\n\n /**\n * Endpoint-level metadata (method-level configuration).\n */\n endpoint: EndpointMetadata;\n\n /**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter decorated with @path, @query,\n * @header, or @body decorators. Stored as a Map keyed by parameter index.\n *\n * @remarks\n * The metadata is stored as a Map<number, ParameterMetadata> where the key is\n * the parameter index and the value is the parameter metadata. This ensures\n * correct parameter ordering regardless of decorator application order.\n */\n parameters: Map<number, ParameterMetadata>;\n\n /**\n * Creates a new FunctionMetadata instance.\n *\n * @param name - The name of the function\n * @param api - API-level metadata\n * @param endpoint - Endpoint-level metadata\n * @param parameters - Parameter metadata array\n */\n constructor(\n name: string,\n api: ApiMetadata,\n endpoint: EndpointMetadata,\n parameters: Map<number, ParameterMetadata>,\n ) {\n this.name = name;\n this.api = api;\n this.endpoint = endpoint;\n this.parameters = parameters;\n }\n\n /**\n * Gets the fetcher instance to use for this function.\n *\n * Returns the fetcher specified in the endpoint metadata, or the API metadata,\n * or falls back to the default fetcher if none is specified.\n *\n * @returns The fetcher instance\n */\n get fetcher(): Fetcher {\n return getFetcher(this.endpoint.fetcher ?? this.api.fetcher) ?? fetcher;\n }\n\n /**\n * Resolves the complete path by combining base path and endpoint path\n *\n * @param parameterPath - Optional path parameter to use instead of endpoint path\n * @returns The combined URL path\n */\n resolvePath(parameterPath?: string): string {\n // Get the base path from endpoint, API, or default to empty string\n const basePath = this.endpoint.basePath || this.api.basePath || '';\n\n // Use provided parameter path or fallback to endpoint path\n const endpointPath = parameterPath || this.endpoint.path || '';\n\n // Combine the base path and endpoint path into a complete URL\n return combineURLs(basePath, endpointPath);\n }\n\n /**\n * Resolves the timeout for the request.\n *\n * Returns the timeout specified in the endpoint metadata, or the API metadata,\n * or undefined if no timeout is specified.\n *\n * @returns The timeout value in milliseconds, or undefined\n */\n resolveTimeout(): number | undefined {\n return this.endpoint.timeout || this.api.timeout;\n }\n\n resolveResultExtractor(): ResultExtractor<any> {\n return (\n this.endpoint.resultExtractor ||\n this.api.resultExtractor ||\n ResultExtractors.DEFAULT\n );\n }\n\n resolveAttributes(): Map<string, any> {\n const resolvedAttributes = mergeRecordToMap(this.api.attributes);\n return mergeRecordToMap(this.endpoint.attributes, resolvedAttributes);\n }\n\n /**\n * Resolves the request configuration from the method arguments.\n *\n * This method processes the runtime arguments according to the parameter metadata\n * and constructs a FetcherRequest object with path parameters, query parameters,\n * headers, body, and timeout. It handles various parameter types including:\n * - Path parameters (@path decorator)\n * - Query parameters (@query decorator)\n * - Header parameters (@header decorator)\n * - Body parameter (@body decorator)\n * - Complete request object (@request decorator)\n * - AbortSignal for request cancellation\n *\n * The method uses mergeRequest to combine the endpoint-specific configuration\n * with the parameter-provided request object, where the parameter request\n * takes precedence over endpoint configuration.\n *\n * @param args - The runtime arguments passed to the method\n * @returns A FetcherRequest object with all request configuration\n *\n * @example\n * ```typescript\n * // For a method decorated like:\n * @get('/users/{id}')\n * getUser(\n * @path('id') id: number,\n * @query('include') include: string,\n * @header('Authorization') auth: string\n * ): Promise<Response>\n *\n * // Calling with: getUser(123, 'profile', 'Bearer token')\n * // Would produce a request with:\n * // {\n * // method: 'GET',\n * // urlParams: {\n * // path: { id: 123 },\n * // query: { include: 'profile' }\n * // },\n * // headers: {\n * // 'Authorization': 'Bearer token',\n * // ...apiHeaders,\n * // ...endpointHeaders\n * // }\n * // }\n * ```\n */\n resolveExchangeInit(args: any[]): Required<Pick<FetchExchangeInit, 'request' | 'attributes'>> {\n const pathParams: Record<string, any> = {};\n const queryParams: Record<string, any> = {};\n const headers: RequestHeaders = {\n ...this.api.headers,\n ...this.endpoint.headers,\n };\n let body: any = undefined;\n let signal: AbortSignal | null | undefined = undefined;\n let abortController: AbortController | null | undefined = undefined;\n let parameterRequest: ParameterRequest = {};\n const attributes: Map<string, any> = this.resolveAttributes();\n // Process parameters based on their decorators\n args.forEach((value, index) => {\n if (value instanceof AbortSignal) {\n signal = value;\n return;\n }\n if (value instanceof AbortController) {\n abortController = value;\n return;\n }\n const funParameter = this.parameters.get(index);\n if (!funParameter) {\n return;\n }\n switch (funParameter.type) {\n case ParameterType.PATH:\n this.processPathParam(funParameter, value, pathParams);\n break;\n case ParameterType.QUERY:\n this.processQueryParam(funParameter, value, queryParams);\n break;\n case ParameterType.HEADER:\n this.processHeaderParam(funParameter, value, headers);\n break;\n case ParameterType.BODY:\n body = value;\n break;\n case ParameterType.REQUEST:\n parameterRequest = this.processRequestParam(value);\n break;\n case ParameterType.ATTRIBUTE:\n this.processAttributeParam(funParameter, value, attributes);\n break;\n case ParameterType.ATTRIBUTES:\n this.processAttributesParam(value, attributes);\n break;\n }\n });\n const urlParams: UrlParams = {\n path: pathParams,\n query: queryParams,\n };\n const endpointRequest: FetchRequestInit = {\n method: this.endpoint.method,\n urlParams,\n headers,\n body,\n timeout: this.resolveTimeout(),\n signal,\n abortController,\n };\n const mergedRequest = mergeRequest(\n endpointRequest,\n parameterRequest,\n ) as any;\n const parameterPath = parameterRequest.path;\n mergedRequest.url = this.resolvePath(parameterPath);\n return {\n request: mergedRequest,\n attributes,\n };\n }\n\n private processPathParam(\n param: ParameterMetadata,\n value: any,\n path: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n path[paramName] = value;\n }\n\n private processQueryParam(\n param: ParameterMetadata,\n value: any,\n query: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n query[paramName] = value;\n }\n\n private processHeaderParam(\n param: ParameterMetadata,\n value: any,\n headers: RequestHeaders,\n ) {\n if (param.name && value !== undefined) {\n headers[param.name] = String(value);\n }\n }\n\n /**\n * Processes a request parameter value.\n *\n * This method handles the @request() decorator parameter by casting\n * the provided value to a FetcherRequest. The @request() decorator\n * allows users to pass a complete FetcherRequest object to customize\n * the request configuration.\n *\n * @param value - The value provided for the @request() parameter\n * @returns The value cast to FetcherRequest type\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: FetcherRequest): Promise<Response>\n *\n * // Usage:\n * const customRequest: FetcherRequest = {\n * headers: { 'X-Custom': 'value' },\n * timeout: 5000\n * };\n * await service.createUsers(customRequest);\n * ```\n */\n private processRequestParam(value: any): ParameterRequest {\n if (!value) {\n return {};\n }\n\n const request = value as ParameterRequest;\n // 确保请求对象中的属性被正确保留\n return {\n ...request,\n headers: request.headers || {},\n urlParams: request.urlParams || { path: {}, query: {} },\n };\n }\n\n\n private processAttributeParam(\n param: ParameterMetadata,\n value: any,\n attributes: Map<string, any>,\n ) {\n if (param.name && value !== undefined) {\n attributes.set(param.name, value);\n }\n }\n\n private processAttributesParam(\n value: any,\n attributes: Map<string, any>,\n ) {\n if (typeof value !== 'object' || value ! instanceof Map) {\n throw new Error('@attributes() parameter must be an object or an Map');\n }\n mergeRecordToMap(value, attributes);\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AttributesCapable,\n Fetcher,\n type RequestHeaders,\n type RequestHeadersCapable,\n type ResultExtractorCapable,\n type TimeoutCapable,\n} from '@ahoo-wang/fetcher';\nimport { ENDPOINT_METADATA_KEY } from './endpointDecorator';\nimport { RequestExecutor } from './requestExecutor';\nimport { PARAMETER_METADATA_KEY } from './parameterDecorator';\nimport 'reflect-metadata';\nimport { type FetcherCapable } from './fetcherCapable';\nimport { FunctionMetadata } from './functionMetadata';\n\n/**\n * Metadata for class-level API configuration.\n *\n * Defines the configuration options that can be applied to an entire API class.\n * These settings will be used as defaults for all endpoints within the class unless overridden\n * at the method level.\n */\nexport interface ApiMetadata\n extends TimeoutCapable,\n RequestHeadersCapable,\n ResultExtractorCapable,\n FetcherCapable, AttributesCapable {\n /**\n * Base path for all endpoints in the class.\n *\n * This path will be prepended to all endpoint paths defined in the class.\n * For example, if basePath is '/api/v1' and an endpoint has path '/users',\n * the full path will be '/api/v1/users'.\n */\n basePath?: string;\n\n /**\n * Default headers for all requests in the class.\n *\n * These headers will be included in every request made by methods in this class.\n * They can be overridden or extended at the method level.\n */\n headers?: RequestHeaders;\n\n /**\n * Default timeout for all requests in the class (in milliseconds).\n *\n * This timeout value will be applied to all requests made by methods in this class.\n * Individual methods can specify their own timeout values to override this default.\n */\n timeout?: number;\n\n /**\n * Name of the fetcher instance to use, default: 'default'.\n *\n * This allows you to specify which fetcher instance should be used for requests\n * from this API class. The fetcher must be registered with the FetcherRegistrar.\n */\n fetcher?: string | Fetcher;\n}\n\nexport const API_METADATA_KEY = Symbol('api:metadata');\n\n/**\n * Binds a request executor to a method, replacing the original method with\n * an implementation that makes HTTP requests based on the decorator metadata.\n *\n * @param constructor - The class constructor\n * @param functionName - The name of the method to bind\n * @param apiMetadata - The API metadata for the class\n */\nfunction bindExecutor<T extends new (...args: any[]) => any>(\n constructor: T,\n functionName: string,\n apiMetadata: ApiMetadata,\n) {\n const endpointFunction = constructor.prototype[functionName];\n if (functionName === 'constructor') {\n return;\n }\n if (typeof endpointFunction !== 'function') {\n return;\n }\n\n const endpointMetadata = Reflect.getMetadata(\n ENDPOINT_METADATA_KEY,\n constructor.prototype,\n functionName,\n );\n if (!endpointMetadata) {\n return;\n }\n // Get parameter metadata for this method\n const parameterMetadata =\n Reflect.getMetadata(\n PARAMETER_METADATA_KEY,\n constructor.prototype,\n functionName,\n ) || new Map();\n\n // Create function metadata\n const functionMetadata = new FunctionMetadata(\n functionName,\n apiMetadata,\n endpointMetadata,\n parameterMetadata,\n );\n\n // Create request executor\n const requestExecutor = new RequestExecutor(functionMetadata);\n\n // Replace method with actual implementation\n constructor.prototype[functionName] = function(...args: unknown[]) {\n return requestExecutor.execute(this, args);\n };\n}\n\nexport function api(\n basePath: string = '',\n metadata: Omit<ApiMetadata, 'basePath'> = {},\n) {\n return function <T extends new (...args: any[]) => any>(constructor: T): T {\n const apiMetadata: ApiMetadata = {\n basePath,\n ...metadata,\n };\n\n // Store metadata directly on the class constructor\n Reflect.defineMetadata(API_METADATA_KEY, apiMetadata, constructor);\n\n // Override prototype methods to implement actual HTTP calls\n Object.getOwnPropertyNames(constructor.prototype).forEach(functionName => {\n bindExecutor(constructor, functionName, apiMetadata);\n });\n\n return constructor;\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Custom error class that indicates a method implementation will be automatically generated.\n *\n * @example\n * ```\n * @post()\n * createUser(@body() user: User):Promise<Response> {\n * throw autoGeneratedError(user);\n * }\n * ```\n */\nexport class AutoGenerated extends Error {\n constructor() {\n super('Implementation will be generated automatically.');\n this.name = 'AutoGenerated';\n }\n}\n\n/**\n * Factory function that creates an AutoGenerated error instance.\n * This is typically used in methods that will be automatically implemented,\n * where a placeholder implementation is needed.\n *\n * @param _ignored - Arguments (such as 'user' in the example) are ignored to prevent\n * ESLint no-unused-vars errors in method signatures that will be auto-generated.\n * @returns A new AutoGenerated error instance\n */\nexport const autoGeneratedError = (..._ignored: any[]): AutoGenerated => {\n return new AutoGenerated();\n};\n"],"names":["ENDPOINT_METADATA_KEY","endpoint","method","path","metadata","target","propertyKey","endpointMetadata","get","HttpMethod","post","put","del","patch","head","options","TARGET_FETCHER_PROPERTY","DECORATOR_TARGET_ATTRIBUTE_KEY","RequestExecutor","fetcher","Fetcher","args","exchangeInit","extractor","parameterNameCache","getParameterNames","func","fnStr","paramsStr","extractParameterString","hasParameters","emptyResult","result","parseParameterNames","errorResult","getParameterName","parameterIndex","providedName","paramNames","endParenIndex","findClosingParenthesis","startParenIndex","str","openingParenIndex","parenDepth","i","char","trimWhitespace","isNotEmpty","extractParameterName","param","cleanedParam","removeDefaultValue","removeTypeAnnotation","equalsIndex","colonIndex","ParameterType","PARAMETER_METADATA_KEY","parameter","type","name","paramName","existingParameters","parameterMetadata","query","header","body","request","attribute","attributes","getFetcher","fetcherRegistrar","ResultExtractors","ExchangeResultExtractor","ResponseResultExtractor","JsonResultExtractor","TextResultExtractor","EventStreamResultExtractor","JsonEventStreamResultExtractor","FunctionMetadata","api","parameters","parameterPath","basePath","endpointPath","combineURLs","resolvedAttributes","mergeRecordToMap","pathParams","queryParams","headers","signal","abortController","parameterRequest","value","index","funParameter","urlParams","endpointRequest","mergedRequest","mergeRequest","API_METADATA_KEY","bindExecutor","constructor","functionName","apiMetadata","endpointFunction","functionMetadata","requestExecutor","AutoGenerated","autoGeneratedError","_ignored"],"mappings":";;;AAgCO,MAAMA,IAAwB,OAAO,mBAAmB;AA4BxD,SAASC,EACdC,GACAC,GACAC,IAAmC,CAAA,GACnC;AACA,S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B;AACjE,WAAOuF,EAAgB,QAAQ,MAAMvF,CAAI;AAAA,EAC3C;AACF;AAEO,SAAS2D,GACdG,IAAmB,IACnB/E,IAA0C,CAAA,GAC1C;AACA,SAAO,SAAiDmG,GAAmB;AACzE,UAAME,IAA2B;AAAA,MAC/B,UAAAtB;AAAA,MACA,GAAG/E;AAAA,IAAA;AAIL,mBAAQ,eAAeiG,GAAkBI,GAAaF,CAAW,GAGjE,OAAO,oBAAoBA,EAAY,SAAS,EAAE,QAAQ,CAAAC,MAAgB;AACxE,MAAAF,GAAaC,GAAaC,GAAcC,CAAW;AAAA,IACrD,CAAC,GAEMF;AAAA,EACT;AACF;AC9HO,MAAMM,WAAsB,MAAM;AAAA,EACvC,cAAc;AACZ,UAAM,iDAAiD,GACvD,KAAK,OAAO;AAAA,EACd;AACF;AAWO,MAAMC,KAAqB,IAAIC,MAC7B,IAAIF,GAAA;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(a,
|
|
1
|
+
(function(a,s){typeof exports=="object"&&typeof module<"u"?s(exports,require("@ahoo-wang/fetcher"),require("reflect-metadata"),require("@ahoo-wang/fetcher-eventstream")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher","reflect-metadata","@ahoo-wang/fetcher-eventstream"],s):(a=typeof globalThis<"u"?globalThis:a||self,s(a.FetcherDecorator={},a.Fetcher,a["reflect-metadata"],a.FetcherEventStream))})(this,(function(a,s,ut,b){"use strict";const R=Symbol("endpoint:metadata");function d(t,e,r={}){return function(n,o){const i={method:t,path:e,...r};Reflect.defineMetadata(R,i,n,o)}}function v(t="",e={}){return d(s.HttpMethod.GET,t,e)}function F(t="",e={}){return d(s.HttpMethod.POST,t,e)}function S(t="",e={}){return d(s.HttpMethod.PUT,t,e)}function x(t="",e={}){return d(s.HttpMethod.DELETE,t,e)}function U(t="",e={}){return d(s.HttpMethod.PATCH,t,e)}function Y(t="",e={}){return d(s.HttpMethod.HEAD,t,e)}function N(t="",e={}){return d(s.HttpMethod.OPTIONS,t,e)}const G="fetcher",P="__decorator_target__";class g{constructor(e){this.metadata=e}getTargetFetcher(e){if(!e||typeof e!="object")return;const r=e[G];if(r instanceof s.Fetcher)return r}async execute(e,r){const n=this.getTargetFetcher(e)||this.metadata.fetcher,o=this.metadata.resolveExchangeInit(r);o.attributes?.set(P,e);const i=this.metadata.resolveResultExtractor();return n.request(o.request,{resultExtractor:i,attributes:o.attributes})}}const p=new WeakMap;function M(t){if(typeof t!="function")throw new TypeError("Expected a function");if(p.has(t))return p.get(t);try{const e=t.toString().trim(),r=B(e);if(!k(r)){const o=[];return p.set(t,o),o}const n=C(r);return p.set(t,n),n}catch{const e=[];return p.set(t,e),e}}function y(t,e,r,n){if(n)return n;try{const o=t[e];if(o&&typeof o=="function"){const i=M(o);if(r<i.length)return i[r]}}catch{}}function k(t){return t!=null&&t.trim()!==""}function B(t){if(t.startsWith("(")){const n=q(t,0);return n===-1?"":t.substring(1,n)}const e=t.indexOf("(");if(e===-1)return"";const r=q(t,e);return r===-1?"":t.substring(e+1,r)}function q(t,e){let r=1;for(let n=e+1;n<t.length;n++){const o=t[n];if(o==="(")r++;else if(o===")"&&(r--,r===0))return n}return-1}function C(t){return t.split(",").map(j).filter(K).map(Q)}function j(t){return t.trim()}function K(t){return t.length>0}function Q(t){let e=J(t);return e=L(e),e.trim()}function J(t){const e=t.indexOf("=");return e!==-1?t.substring(0,e):t}function L(t){const e=t.indexOf(":");return e!==-1?t.substring(0,e):t}var c=(t=>(t.PATH="path",t.QUERY="query",t.HEADER="header",t.BODY="body",t.REQUEST="request",t.ATTRIBUTE="attribute",t.ATTRIBUTES="attributes",t))(c||{});const T=Symbol("parameter:metadata");function h(t,e=""){return function(r,n,o){const i=y(r,n,o,e),m=Reflect.getMetadata(T,r,n)||new Map,f={type:t,name:i,index:o};m.set(o,f),Reflect.defineMetadata(T,m,r,n)}}function W(t=""){return h("path",t)}function V(t=""){return h("query",t)}function z(t=""){return h("header",t)}function X(){return h("body")}function Z(){return h("request")}function $(t=""){return h("attribute",t)}function tt(){return h("attributes")}function _(t){if(t)return t instanceof s.Fetcher?t:s.fetcherRegistrar.requiredGet(t)}const D={Exchange:s.ExchangeResultExtractor,Response:s.ResponseResultExtractor,Json:s.JsonResultExtractor,Text:s.TextResultExtractor,EventStream:b.EventStreamResultExtractor,JsonEventStream:b.JsonEventStreamResultExtractor,DEFAULT:s.JsonResultExtractor};class O{constructor(e,r,n,o){this.name=e,this.api=r,this.endpoint=n,this.parameters=o}get fetcher(){return _(this.endpoint.fetcher??this.api.fetcher)??s.fetcher}resolvePath(e){const r=this.endpoint.basePath||this.api.basePath||"",n=e||this.endpoint.path||"";return s.combineURLs(r,n)}resolveTimeout(){return this.endpoint.timeout||this.api.timeout}resolveResultExtractor(){return this.endpoint.resultExtractor||this.api.resultExtractor||D.DEFAULT}resolveAttributes(){const e=s.mergeRecordToMap(this.api.attributes);return s.mergeRecordToMap(this.endpoint.attributes,e)}resolveExchangeInit(e){const r={},n={},o={...this.api.headers,...this.endpoint.headers};let i,m,f,l={};const A=this.resolveAttributes();e.forEach((u,it)=>{if(u instanceof AbortSignal){m=u;return}if(u instanceof AbortController){f=u;return}const E=this.parameters.get(it);if(E)switch(E.type){case c.PATH:this.processPathParam(E,u,r);break;case c.QUERY:this.processQueryParam(E,u,n);break;case c.HEADER:this.processHeaderParam(E,u,o);break;case c.BODY:i=u;break;case c.REQUEST:l=this.processRequestParam(u);break;case c.ATTRIBUTE:this.processAttributeParam(E,u,A);break;case c.ATTRIBUTES:this.processAttributesParam(u,A);break}});const at={path:r,query:n},ot={method:this.endpoint.method,urlParams:at,headers:o,body:i,timeout:this.resolveTimeout(),signal:m,abortController:f},H=s.mergeRequest(ot,l),st=l.path;return H.url=this.resolvePath(st),{request:H,attributes:A}}processPathParam(e,r,n){const o=e.name||`param${e.index}`;n[o]=r}processQueryParam(e,r,n){const o=e.name||`param${e.index}`;n[o]=r}processHeaderParam(e,r,n){e.name&&r!==void 0&&(n[e.name]=String(r))}processRequestParam(e){if(!e)return{};const r=e;return{...r,headers:r.headers||{},urlParams:r.urlParams||{path:{},query:{}}}}processAttributeParam(e,r,n){e.name&&r!==void 0&&n.set(e.name,r)}processAttributesParam(e,r){if(typeof e!="object"||e instanceof Map)throw new Error("@attributes() parameter must be an object or an Map");s.mergeRecordToMap(e,r)}}const w=Symbol("api:metadata");function et(t,e,r){const n=t.prototype[e];if(e==="constructor"||typeof n!="function")return;const o=Reflect.getMetadata(R,t.prototype,e);if(!o)return;const i=Reflect.getMetadata(T,t.prototype,e)||new Map,m=new O(e,r,o,i),f=new g(m);t.prototype[e]=function(...l){return f.execute(this,l)}}function rt(t="",e={}){return function(r){const n={basePath:t,...e};return Reflect.defineMetadata(w,n,r),Object.getOwnPropertyNames(r.prototype).forEach(o=>{et(r,o,n)}),r}}class I extends Error{constructor(){super("Implementation will be generated automatically."),this.name="AutoGenerated"}}const nt=(...t)=>new I;a.API_METADATA_KEY=w,a.AutoGenerated=I,a.DECORATOR_TARGET_ATTRIBUTE_KEY=P,a.ENDPOINT_METADATA_KEY=R,a.FunctionMetadata=O,a.PARAMETER_METADATA_KEY=T,a.ParameterType=c,a.RequestExecutor=g,a.ResultExtractors=D,a.api=rt,a.attribute=$,a.attributes=tt,a.autoGeneratedError=nt,a.body=X,a.del=x,a.endpoint=d,a.get=v,a.getFetcher=_,a.getParameterName=y,a.getParameterNames=M,a.head=Y,a.header=z,a.options=N,a.parameter=h,a.patch=U,a.path=W,a.post=F,a.put=S,a.query=V,a.request=Z,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/endpointDecorator.ts","../src/requestExecutor.ts","../src/reflection.ts","../src/parameterDecorator.ts","../src/fetcherCapable.ts","../src/resultExtractor.ts","../src/functionMetadata.ts","../src/apiDecorator.ts","../src/generated.ts"],"sourcesContent":["import { HttpMethod } from '@ahoo-wang/fetcher';\nimport { type ApiMetadata } from './apiDecorator';\nimport 'reflect-metadata';\nimport { type ResultExtractorCapable } from './resultExtractor';\n\nexport interface PathCapable {\n /**\n * Path for the endpoint (relative to class base path).\n *\n * This path will be appended to the class's base path to form the complete URL.\n * Path parameters can be specified using curly braces, e.g., '/users/{id}'\n */\n path?: string;\n}\n\n/**\n * Metadata for HTTP endpoints.\n *\n * Defines the configuration options for individual HTTP endpoints (methods).\n * These settings will override any corresponding class-level settings from ApiMetadata.\n */\nexport interface EndpointMetadata\n extends ApiMetadata,\n ResultExtractorCapable,\n PathCapable {\n /**\n * HTTP method for the endpoint.\n *\n * Specifies the HTTP verb to be used for this endpoint (GET, POST, PUT, DELETE, etc.)\n */\n method?: HttpMethod;\n}\n\nexport const ENDPOINT_METADATA_KEY = Symbol('endpoint:metadata');\n\nexport type MethodEndpointMetadata = Omit<EndpointMetadata, 'method' | 'path'>;\n\n/**\n * Decorator factory for defining HTTP endpoints.\n *\n * Creates a decorator that can be used to define HTTP endpoints\n * on class methods. It stores metadata about the endpoint that will be used\n * to generate the actual HTTP request.\n *\n * @param method - The HTTP method for this endpoint\n * @param path - The path for this endpoint (relative to class base path)\n * @param metadata - Additional endpoint metadata (headers, timeout, etc.)\n * @returns A method decorator function\n *\n * @example\n * ```typescript\n * @api('/api/v1')\n * class UserService {\n * @endpoint(HttpMethod.GET, '/users/{id}')\n * getUser(@path('id') id: string): Promise<Response> {\n * // Implementation will be generated automatically\n * throw autoGeneratedError();\n * }\n * }\n * ```\n */\nexport function endpoint(\n method?: HttpMethod,\n path?: string,\n metadata: MethodEndpointMetadata = {},\n) {\n return function(target: object, propertyKey: string | symbol): void {\n // Store metadata directly on the method\n const endpointMetadata = {\n method: method,\n path,\n ...metadata,\n };\n Reflect.defineMetadata(\n ENDPOINT_METADATA_KEY,\n endpointMetadata,\n target,\n propertyKey,\n );\n };\n}\n\nexport function get(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.GET, path, metadata);\n}\n\nexport function post(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.POST, path, metadata);\n}\n\nexport function put(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.PUT, path, metadata);\n}\n\nexport function del(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.DELETE, path, metadata);\n}\n\nexport function patch(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.PATCH, path, metadata);\n}\n\nexport function head(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.HEAD, path, metadata);\n}\n\nexport function options(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.OPTIONS, path, metadata);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Fetcher } from '@ahoo-wang/fetcher';\nimport { FunctionMetadata } from './functionMetadata';\n\nconst TARGET_FETCHER_PROPERTY = 'fetcher';\n\nexport const DECORATOR_TARGET_ATTRIBUTE_KEY = '__decorator_target__';\n\n/**\n * Executor for HTTP requests based on decorated method metadata.\n *\n * This class is responsible for executing HTTP requests based on the metadata\n * collected from decorators. It resolves the path, constructs the request,\n * and executes it using the appropriate fetcher.\n */\nexport class RequestExecutor {\n private readonly metadata: FunctionMetadata;\n\n /**\n * Creates a new RequestExecutor instance.\n *\n * @param metadata - The function metadata containing all request information\n */\n constructor(metadata: FunctionMetadata) {\n this.metadata = metadata;\n }\n\n /**\n * Retrieves the fetcher instance from the target object.\n *\n * @param target - The target object that may contain a fetcher property\n * @returns The fetcher instance if exists, otherwise undefined\n */\n private getTargetFetcher(target: any): Fetcher | undefined {\n if (!target || typeof target !== 'object') {\n return undefined;\n }\n // Extract the fetcher property from the target object\n const fetcher = target[TARGET_FETCHER_PROPERTY];\n\n // Validate that the fetcher is an instance of the Fetcher class\n if (fetcher instanceof Fetcher) {\n return fetcher;\n }\n\n // Return undefined if no valid fetcher instance is found\n return undefined;\n }\n\n /**\n * Executes the HTTP request.\n *\n * This method resolves the path and request configuration from the metadata\n * and arguments, then executes the request using the configured fetcher.\n * It handles the complete request lifecycle from parameter processing to\n * response extraction.\n *\n * @param target - The target object that the method is called on.\n * This can contain a custom fetcher instance in its 'fetcher' property.\n * @param args - The runtime arguments passed to the decorated method.\n * These are mapped to request components based on parameter decorators.\n * @returns A Promise that resolves to the extracted result based on the configured result extractor.\n * By default, this is the Response object, but can be customized to return\n * parsed JSON, the raw exchange object, or any other transformed result.\n *\n * @example\n * ```typescript\n * // Given a decorated service method:\n * class UserService {\n * @get('/users/{id}')\n * getUser(@path('id') id: number): Promise<Response> {\n * // This method body is replaced by the executor at runtime\n * }\n * }\n *\n * // When calling:\n * const userService = new UserService();\n * const response = await userService.getUser(123);\n *\n * // The execute method will:\n * // 1. Resolve the path to '/users/123'\n * // 2. Create a request with method 'GET'\n * // 3. Execute the request using the configured fetcher\n * // 4. Return the Response object\n * ```\n */\n async execute(target: any, args: any[]): Promise<any> {\n const fetcher = this.getTargetFetcher(target) || this.metadata.fetcher;\n const exchangeInit = this.metadata.resolveExchangeInit(args);\n exchangeInit.attributes[DECORATOR_TARGET_ATTRIBUTE_KEY] = target;\n const extractor = this.metadata.resolveResultExtractor();\n return fetcher.request(exchangeInit.request, extractor, exchangeInit.attributes);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Cache for storing previously extracted parameter names to improve performance\nconst parameterNameCache = new WeakMap<Function, string[]>();\n\n/**\n * Extracts parameter names from a function.\n *\n * This function parses the string representation of a function to extract\n * the names of its parameters. It handles various function formats including\n * regular functions, arrow functions, and methods.\n *\n * Note: This implementation provides basic parameter name extraction and may not\n * handle all edge cases of complex TypeScript parameter declarations.\n *\n * @param func - The function to extract parameter names from\n * @returns An array of parameter names, or an empty array if extraction fails\n * @throws {TypeError} If the input is not a function\n *\n * @example\n * ```typescript\n * function example(a, b, c) {}\n * const paramNames = getParameterNames(example);\n * // Returns: ['a', 'b', 'c']\n *\n * const arrowFunc = (x, y) => x + y;\n * const arrowParamNames = getParameterNames(arrowFunc);\n * // Returns: ['x', 'y']\n *\n * function complex(param1: string, param2: number = 10, ...rest: any[]) {}\n * const complexParamNames = getParameterNames(complex);\n * // Returns: ['param1', 'param2', '...rest']\n * ```\n */\nexport function getParameterNames(func: (...args: any[]) => any): string[] {\n // Validate that the input is a function\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n // Check cache first to improve performance\n if (parameterNameCache.has(func)) {\n return parameterNameCache.get(func)!;\n }\n\n try {\n // Convert function to string and trim whitespace\n const fnStr = func.toString().trim();\n\n // Extract parameter string from the function\n const paramsStr = extractParameterString(fnStr);\n\n // Handle empty parameters\n if (!hasParameters(paramsStr)) {\n const emptyResult: string[] = [];\n parameterNameCache.set(func, emptyResult);\n return emptyResult;\n }\n\n // Parse and clean parameter names\n const result = parseParameterNames(paramsStr);\n parameterNameCache.set(func, result);\n return result;\n } catch {\n // Return empty array on any parsing errors to avoid breaking the application\n const errorResult: string[] = [];\n parameterNameCache.set(func, errorResult);\n return errorResult;\n }\n}\n\n/**\n * Helper function to automatically extract parameter name when not provided.\n *\n * @param target - The target object (class prototype)\n * @param propertyKey - The method name\n * @param parameterIndex - The index of the parameter\n * @param providedName - The name explicitly provided by the user (if any)\n * @returns The parameter name, either provided or automatically extracted\n */\nexport function getParameterName(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n providedName?: string,\n): string | undefined {\n // If a name was explicitly provided, use it\n if (providedName) {\n return providedName;\n }\n\n // Try to automatically extract the parameter name\n try {\n const method = target[propertyKey as keyof typeof target];\n if (method && typeof method === 'function') {\n const paramNames = getParameterNames(method);\n if (parameterIndex < paramNames.length) {\n return paramNames[parameterIndex];\n }\n }\n } catch {\n // If we can't get the parameter name, return undefined\n // This will use default naming in the execution logic\n }\n\n return undefined;\n}\n\n/**\n * Checks if a parameter string contains actual parameters.\n *\n * @param paramsStr - The parameter string to check\n * @returns True if the string contains parameters, false otherwise\n */\nfunction hasParameters(paramsStr: string): boolean {\n return (\n paramsStr !== null && paramsStr !== undefined && paramsStr.trim() !== ''\n );\n}\n\n/**\n * Extracts the parameter string from a function string representation.\n *\n * @param fnStr - The string representation of the function\n * @returns The parameter string, or empty string if not found\n */\nfunction extractParameterString(fnStr: string): string {\n // Handle arrow functions that start with parentheses\n if (fnStr.startsWith('(')) {\n const endParenIndex = findClosingParenthesis(fnStr, 0);\n if (endParenIndex === -1) return '';\n return fnStr.substring(1, endParenIndex);\n }\n\n // Handle regular functions, async functions, and methods\n const startParenIndex = fnStr.indexOf('(');\n if (startParenIndex === -1) return '';\n\n const endParenIndex = findClosingParenthesis(fnStr, startParenIndex);\n if (endParenIndex === -1) return '';\n\n return fnStr.substring(startParenIndex + 1, endParenIndex);\n}\n\n/**\n * Finds the matching closing parenthesis for an opening parenthesis.\n *\n * @param str - The string to search in\n * @param openingParenIndex - The index of the opening parenthesis\n * @returns The index of the matching closing parenthesis, or -1 if not found\n */\nfunction findClosingParenthesis(\n str: string,\n openingParenIndex: number,\n): number {\n let parenDepth = 1;\n\n for (let i = openingParenIndex + 1; i < str.length; i++) {\n const char = str[i];\n\n if (char === '(') {\n parenDepth++;\n } else if (char === ')') {\n parenDepth--;\n if (parenDepth === 0) {\n return i;\n }\n }\n }\n\n return -1; // No matching closing parenthesis found\n}\n\n/**\n * Parses and cleans parameter names from a parameter string.\n *\n * @param paramsStr - The parameter string to parse\n * @returns An array of cleaned parameter names\n */\nfunction parseParameterNames(paramsStr: string): string[] {\n return paramsStr\n .split(',')\n .map(trimWhitespace)\n .filter(isNotEmpty)\n .map(extractParameterName);\n}\n\n/**\n * Trims whitespace from a string.\n *\n * @param str - The string to trim\n * @returns The trimmed string\n */\nfunction trimWhitespace(str: string): string {\n return str.trim();\n}\n\n/**\n * Checks if a string is not empty.\n *\n * @param str - The string to check\n * @returns True if the string is not empty, false otherwise\n */\nfunction isNotEmpty(str: string): boolean {\n return str.length > 0;\n}\n\n/**\n * Extracts a clean parameter name by removing type annotations and default values.\n *\n * @param param - The raw parameter string\n * @returns The cleaned parameter name\n */\nfunction extractParameterName(param: string): string {\n // Remove default value assignment (everything after =)\n let cleanedParam = removeDefaultValue(param);\n\n // Remove type annotations (everything after :)\n cleanedParam = removeTypeAnnotation(cleanedParam);\n\n return cleanedParam.trim();\n}\n\n/**\n * Removes default value from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without default value\n */\nfunction removeDefaultValue(param: string): string {\n const equalsIndex = param.indexOf('=');\n if (equalsIndex !== -1) {\n return param.substring(0, equalsIndex);\n }\n return param;\n}\n\n/**\n * Removes type annotation from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without type annotation\n */\nfunction removeTypeAnnotation(param: string): string {\n const colonIndex = param.indexOf(':');\n if (colonIndex !== -1) {\n return param.substring(0, colonIndex);\n }\n return param;\n}\n","import { getParameterName } from './reflection';\nimport 'reflect-metadata';\nimport { type PathCapable } from './endpointDecorator';\nimport { type FetchRequestInit } from '@ahoo-wang/fetcher';\n\n/**\n * Parameter types for decorator parameters.\n *\n * Defines the different types of parameters that can be used\n * in API method decorators to specify how arguments should be handled\n * in the HTTP request.\n */\nexport enum ParameterType {\n /**\n * Path parameter that will be inserted into the URL path.\n *\n * Path parameters are used to specify dynamic parts of the URL path.\n * They are defined using curly braces in the endpoint path.\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n * ```\n */\n PATH = 'path',\n\n /**\n * Query parameter that will be appended to the URL query string.\n *\n * Query parameters are used to pass non-hierarchical data to the server.\n * They appear after the '?' in the URL.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n * ```\n */\n QUERY = 'query',\n\n /**\n * Header parameter that will be added to the request headers.\n *\n * Header parameters are used to pass metadata about the request,\n * such as authentication tokens or content type information.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n * ```\n */\n HEADER = 'header',\n\n /**\n * Body parameter that will be sent as the request body.\n *\n * The body parameter represents the main data payload of the request.\n * It is typically used with POST, PUT, and PATCH requests.\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\n BODY = 'body',\n\n /**\n * Request parameter that will be used as the request object.\n */\n REQUEST = 'request',\n\n\n /**\n * Attribute parameter that will be used as a single attribute in the request attributes.\n *\n * The attribute parameter allows passing a single key-value pair that will be added\n * to the request attributes object. This is useful for passing specific contextual\n * information that can be accessed by interceptors.\n */\n ATTRIBUTE = 'attribute',\n /**\n * Attributes parameter that will be used as the request attributes.\n *\n * The attributes parameter allows passing custom data that can be accessed\n * by interceptors throughout the request lifecycle. This is useful for\n * sharing contextual information between different parts of the request processing.\n */\n ATTRIBUTES = 'attributes'\n}\n\n/**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter\n * decorated with @path, @query, @header, or @body decorators.\n */\nexport interface ParameterMetadata {\n /**\n * Type of parameter (path, query, header, body).\n *\n * Specifies how this parameter should be handled in the HTTP request.\n */\n type: ParameterType;\n\n /**\n * Name of the parameter (used for path, query, and header parameters).\n *\n * For path and query parameters, this corresponds to the key in the URL.\n * For header parameters, this corresponds to the header name.\n * For body parameters, this is not used.\n */\n name?: string;\n\n /**\n * Index of the parameter in the method signature.\n *\n * This is used to map the runtime argument values to the correct parameter metadata.\n */\n index: number;\n}\n\nexport const PARAMETER_METADATA_KEY = Symbol('parameter:metadata');\n\n/**\n * Decorator factory for method parameters.\n *\n * Creates a decorator that can be used to specify how a method parameter\n * should be handled in the HTTP request. It stores metadata about the parameter\n * that will be used during request execution.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param type - The type of parameter (PATH, QUERY, HEADER, or BODY)\n * @param name - The name of the parameter (used for path, query, and header parameters, optional - auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@parameter(ParameterType.PATH, 'id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@parameter(ParameterType.PATH) userId: string): Promise<Response>\n * ```\n */\nexport function parameter(type: ParameterType, name: string = '') {\n return function(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n ) {\n const paramName = getParameterName(\n target,\n propertyKey as string,\n parameterIndex,\n name,\n );\n\n const existingParameters: Map<number, ParameterMetadata> =\n Reflect.getMetadata(PARAMETER_METADATA_KEY, target, propertyKey) ||\n new Map();\n const parameterMetadata: ParameterMetadata = {\n type: type,\n name: paramName,\n index: parameterIndex,\n };\n existingParameters.set(parameterIndex, parameterMetadata);\n Reflect.defineMetadata(\n PARAMETER_METADATA_KEY,\n existingParameters,\n target,\n propertyKey,\n );\n };\n}\n\n/**\n * Path parameter decorator.\n *\n * Defines a path parameter that will be inserted into the URL path.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the path parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@path() userId: string): Promise<Response>\n * ```\n */\nexport function path(name: string = '') {\n return parameter(ParameterType.PATH, name);\n}\n\n/**\n * Query parameter decorator.\n *\n * Defines a query parameter that will be appended to the URL query string.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the query parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@query() limit: number): Promise<Response>\n * ```\n */\nexport function query(name: string = '') {\n return parameter(ParameterType.QUERY, name);\n}\n\n/**\n * Header parameter decorator.\n *\n * Defines a header parameter that will be added to the request headers.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the header parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@header() authorization: string): Promise<Response>\n * ```\n */\nexport function header(name: string = '') {\n return parameter(ParameterType.HEADER, name);\n}\n\n/**\n * Body parameter decorator.\n *\n * Defines a body parameter that will be sent as the request body.\n * Note that body parameters don't have names since there's only one body per request.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\nexport function body() {\n return parameter(ParameterType.BODY);\n}\n\n/**\n * Interface for request parameter objects.\n *\n * Combines FetchRequestInit and PathCapable interfaces to provide\n * a complete request configuration object that can be used with\n * the @request() decorator. This allows full customization of\n * the HTTP request including method, headers, body, and URL parameters.\n */\nexport interface ParameterRequest extends FetchRequestInit, PathCapable {\n}\n\n/**\n * Request parameter decorator.\n *\n * Defines a request parameter that will be used as the base request object.\n * This allows you to pass a complete ParameterRequest object to customize\n * the request configuration.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: ParameterRequest): Promise<Response>\n * ```\n */\nexport function request() {\n return parameter(ParameterType.REQUEST);\n}\n\n/**\n * Parameter decorator for adding a single attribute to the request attributes.\n *\n * This decorator allows you to pass a key-value pair as an attribute that can be accessed\n * by interceptors during the request lifecycle. If no name is provided, the parameter's\n * property name will be used as the attribute key.\n *\n * @param name - Optional name for the attribute. If not provided, the parameter's property name will be used.\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute('userId') userId: string): Promise<Response>\n *\n * // Using property name as attribute key\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute() userId: string): Promise<Response>\n * ```\n */\nexport function attribute(name: string = '') {\n return parameter(ParameterType.ATTRIBUTE, name);\n}\n\n/**\n * Parameter decorator for adding multiple attributes to the request.\n *\n * This decorator allows you to pass an entire object as attributes that can be accessed\n * by interceptors during the request lifecycle. The parameter should be an object whose\n * properties will be merged into the request attributes.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attributes() attrs: Record<string, any>): Promise<Response>\n * ```\n */\nexport function attributes() {\n return parameter(ParameterType.ATTRIBUTES);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';\n\n/**\n * Interface that defines a capability for objects that can have a fetcher.\n * This interface is typically used to mark components or objects that can perform fetching operations\n * and may need access to fetcher functionality.\n */\nexport interface FetcherCapable {\n /**\n * Optional fetcher property that can be either a string identifier or a Fetcher instance.\n * When present, this property indicates the fetcher associated with the implementing object.\n */\n fetcher?: string | Fetcher;\n}\n\n/**\n * Gets a Fetcher instance based on the provided fetcher parameter.\n *\n * @param fetcher - A string identifier or Fetcher instance to resolve\n * @returns A Fetcher instance if found, undefined otherwise\n */\nexport function getFetcher(fetcher?: string | Fetcher): Fetcher | undefined {\n // Return undefined if no fetcher is provided\n if (!fetcher) {\n return undefined;\n }\n\n // Return the fetcher directly if it's already a Fetcher instance,\n // otherwise resolve it through the fetcher registrar\n return fetcher instanceof Fetcher\n ? fetcher\n : fetcherRegistrar.requiredGet(fetcher);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ExchangeResultExtractor,\n JsonResultExtractor,\n ResponseResultExtractor,\n ResultExtractor,\n TextResultExtractor,\n} from '@ahoo-wang/fetcher';\nimport {\n EventStreamResultExtractor,\n JsonEventStreamResultExtractor,\n} from '@ahoo-wang/fetcher-eventstream';\n\n/**\n * Interface with result extractor capability\n * Defines an optional resultExtractor property\n */\nexport interface ResultExtractorCapable {\n resultExtractor?: ResultExtractor<any>;\n}\n\n/**\n * ResultExtractors is an object that maps result extractor names to their corresponding\n * extractor functions. These extractors are used to process and extract data from different\n * types of responses or results in the application.\n *\n * Each property represents a specific type of result extractor:\n * - Exchange: Handles exchange-related result extraction\n * - Response: Handles general response result extraction\n * - Json: Handles JSON format result extraction\n * - Text: Handles plain text result extraction\n * - EventStream: Handles server-sent event stream result extraction\n * - JsonEventStream: Handles JSON server-sent event stream result extraction\n */\nexport const ResultExtractors = {\n Exchange: ExchangeResultExtractor,\n Response: ResponseResultExtractor,\n Json: JsonResultExtractor,\n Text: TextResultExtractor,\n EventStream: EventStreamResultExtractor,\n JsonEventStream: JsonEventStreamResultExtractor,\n DEFAULT: JsonResultExtractor,\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n combineURLs,\n Fetcher, fetcher,\n type FetchExchangeInit,\n FetchRequestInit,\n mergeRequest,\n NamedCapable,\n type RequestHeaders,\n ResultExtractor,\n type UrlParams,\n} from '@ahoo-wang/fetcher';\nimport { ApiMetadata } from './apiDecorator';\nimport { EndpointMetadata } from './endpointDecorator';\nimport { ParameterMetadata, ParameterRequest, ParameterType } from './parameterDecorator';\nimport { getFetcher } from './fetcherCapable';\nimport { ResultExtractors } from './resultExtractor';\n\n/**\n * Metadata container for a function with HTTP endpoint decorators.\n *\n * Encapsulates all the metadata needed to execute an HTTP request\n * for a decorated method, including API-level defaults, endpoint-specific\n * configuration, and parameter metadata.\n */\nexport class FunctionMetadata implements NamedCapable {\n /**\n * Name of the function.\n */\n name: string;\n\n /**\n * API-level metadata (class-level configuration).\n */\n api: ApiMetadata;\n\n /**\n * Endpoint-level metadata (method-level configuration).\n */\n endpoint: EndpointMetadata;\n\n /**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter decorated with @path, @query,\n * @header, or @body decorators. Stored as a Map keyed by parameter index.\n *\n * @remarks\n * The metadata is stored as a Map<number, ParameterMetadata> where the key is\n * the parameter index and the value is the parameter metadata. This ensures\n * correct parameter ordering regardless of decorator application order.\n */\n parameters: Map<number, ParameterMetadata>;\n\n /**\n * Creates a new FunctionMetadata instance.\n *\n * @param name - The name of the function\n * @param api - API-level metadata\n * @param endpoint - Endpoint-level metadata\n * @param parameters - Parameter metadata array\n */\n constructor(\n name: string,\n api: ApiMetadata,\n endpoint: EndpointMetadata,\n parameters: Map<number, ParameterMetadata>,\n ) {\n this.name = name;\n this.api = api;\n this.endpoint = endpoint;\n this.parameters = parameters;\n }\n\n /**\n * Gets the fetcher instance to use for this function.\n *\n * Returns the fetcher specified in the endpoint metadata, or the API metadata,\n * or falls back to the default fetcher if none is specified.\n *\n * @returns The fetcher instance\n */\n get fetcher(): Fetcher {\n return getFetcher(this.endpoint.fetcher ?? this.api.fetcher) ?? fetcher;\n }\n\n /**\n * Resolves the complete path by combining base path and endpoint path\n *\n * @param parameterPath - Optional path parameter to use instead of endpoint path\n * @returns The combined URL path\n */\n resolvePath(parameterPath?: string): string {\n // Get the base path from endpoint, API, or default to empty string\n const basePath = this.endpoint.basePath || this.api.basePath || '';\n\n // Use provided parameter path or fallback to endpoint path\n const endpointPath = parameterPath || this.endpoint.path || '';\n\n // Combine the base path and endpoint path into a complete URL\n return combineURLs(basePath, endpointPath);\n }\n\n /**\n * Resolves the timeout for the request.\n *\n * Returns the timeout specified in the endpoint metadata, or the API metadata,\n * or undefined if no timeout is specified.\n *\n * @returns The timeout value in milliseconds, or undefined\n */\n resolveTimeout(): number | undefined {\n return this.endpoint.timeout || this.api.timeout;\n }\n\n resolveResultExtractor(): ResultExtractor<any> {\n return (\n this.endpoint.resultExtractor ||\n this.api.resultExtractor ||\n ResultExtractors.DEFAULT\n );\n }\n\n resolveAttributes(): Record<string, any> {\n return {\n ...this.api.attributes,\n ...this.endpoint.attributes,\n };\n }\n\n /**\n * Resolves the request configuration from the method arguments.\n *\n * This method processes the runtime arguments according to the parameter metadata\n * and constructs a FetcherRequest object with path parameters, query parameters,\n * headers, body, and timeout. It handles various parameter types including:\n * - Path parameters (@path decorator)\n * - Query parameters (@query decorator)\n * - Header parameters (@header decorator)\n * - Body parameter (@body decorator)\n * - Complete request object (@request decorator)\n * - AbortSignal for request cancellation\n *\n * The method uses mergeRequest to combine the endpoint-specific configuration\n * with the parameter-provided request object, where the parameter request\n * takes precedence over endpoint configuration.\n *\n * @param args - The runtime arguments passed to the method\n * @returns A FetcherRequest object with all request configuration\n *\n * @example\n * ```typescript\n * // For a method decorated like:\n * @get('/users/{id}')\n * getUser(\n * @path('id') id: number,\n * @query('include') include: string,\n * @header('Authorization') auth: string\n * ): Promise<Response>\n *\n * // Calling with: getUser(123, 'profile', 'Bearer token')\n * // Would produce a request with:\n * // {\n * // method: 'GET',\n * // urlParams: {\n * // path: { id: 123 },\n * // query: { include: 'profile' }\n * // },\n * // headers: {\n * // 'Authorization': 'Bearer token',\n * // ...apiHeaders,\n * // ...endpointHeaders\n * // }\n * // }\n * ```\n */\n resolveExchangeInit(args: any[]): Required<Pick<FetchExchangeInit, 'request' | 'attributes'>> {\n const pathParams: Record<string, any> = {};\n const queryParams: Record<string, any> = {};\n const headers: RequestHeaders = {\n ...this.api.headers,\n ...this.endpoint.headers,\n };\n let body: any = undefined;\n let signal: AbortSignal | null | undefined = undefined;\n let abortController: AbortController | null | undefined = undefined;\n let parameterRequest: ParameterRequest = {};\n const attributes: Record<string, any> = this.resolveAttributes();\n // Process parameters based on their decorators\n args.forEach((value, index) => {\n if (value instanceof AbortSignal) {\n signal = value;\n return;\n }\n if (value instanceof AbortController) {\n abortController = value;\n return;\n }\n const funParameter = this.parameters.get(index);\n if (!funParameter) {\n return;\n }\n switch (funParameter.type) {\n case ParameterType.PATH:\n this.processPathParam(funParameter, value, pathParams);\n break;\n case ParameterType.QUERY:\n this.processQueryParam(funParameter, value, queryParams);\n break;\n case ParameterType.HEADER:\n this.processHeaderParam(funParameter, value, headers);\n break;\n case ParameterType.BODY:\n body = value;\n break;\n case ParameterType.REQUEST:\n parameterRequest = this.processRequestParam(value);\n break;\n case ParameterType.ATTRIBUTE:\n this.processAttributeParam(funParameter, value, attributes);\n break;\n case ParameterType.ATTRIBUTES:\n this.processAttributesParam(value, attributes);\n break;\n }\n });\n const urlParams: UrlParams = {\n path: pathParams,\n query: queryParams,\n };\n const endpointRequest: FetchRequestInit = {\n method: this.endpoint.method,\n urlParams,\n headers,\n body,\n timeout: this.resolveTimeout(),\n signal,\n abortController,\n };\n const mergedRequest = mergeRequest(\n endpointRequest,\n parameterRequest,\n ) as any;\n const parameterPath = parameterRequest.path;\n mergedRequest.url = this.resolvePath(parameterPath);\n return {\n request: mergedRequest,\n attributes,\n };\n }\n\n private processPathParam(\n param: ParameterMetadata,\n value: any,\n path: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n path[paramName] = value;\n }\n\n private processQueryParam(\n param: ParameterMetadata,\n value: any,\n query: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n query[paramName] = value;\n }\n\n private processHeaderParam(\n param: ParameterMetadata,\n value: any,\n headers: RequestHeaders,\n ) {\n if (param.name && value !== undefined) {\n headers[param.name] = String(value);\n }\n }\n\n /**\n * Processes a request parameter value.\n *\n * This method handles the @request() decorator parameter by casting\n * the provided value to a FetcherRequest. The @request() decorator\n * allows users to pass a complete FetcherRequest object to customize\n * the request configuration.\n *\n * @param value - The value provided for the @request() parameter\n * @returns The value cast to FetcherRequest type\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: FetcherRequest): Promise<Response>\n *\n * // Usage:\n * const customRequest: FetcherRequest = {\n * headers: { 'X-Custom': 'value' },\n * timeout: 5000\n * };\n * await service.createUsers(customRequest);\n * ```\n */\n private processRequestParam(value: any): ParameterRequest {\n if (!value) {\n return {};\n }\n\n const request = value as ParameterRequest;\n // 确保请求对象中的属性被正确保留\n return {\n ...request,\n headers: request.headers || {},\n urlParams: request.urlParams || { path: {}, query: {} },\n };\n }\n\n\n private processAttributeParam(\n param: ParameterMetadata,\n value: any,\n attributes: Record<string, any>,\n ) {\n if (param.name && value !== undefined) {\n attributes[param.name] = value;\n }\n }\n\n private processAttributesParam(\n value: any,\n attributes: Record<string, any>,\n ) {\n if (typeof value !== 'object') {\n throw new Error('@attributes() parameter must be an object');\n }\n Object.keys(value).forEach(key => {\n attributes[key] = value[key];\n });\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AttributesCapable,\n Fetcher,\n type RequestHeaders,\n type RequestHeadersCapable,\n type TimeoutCapable,\n} from '@ahoo-wang/fetcher';\nimport { ENDPOINT_METADATA_KEY } from './endpointDecorator';\nimport { RequestExecutor } from './requestExecutor';\nimport { PARAMETER_METADATA_KEY } from './parameterDecorator';\nimport 'reflect-metadata';\nimport { type ResultExtractorCapable } from './resultExtractor';\nimport { type FetcherCapable } from './fetcherCapable';\nimport { FunctionMetadata } from './functionMetadata';\n\n/**\n * Metadata for class-level API configuration.\n *\n * Defines the configuration options that can be applied to an entire API class.\n * These settings will be used as defaults for all endpoints within the class unless overridden\n * at the method level.\n */\nexport interface ApiMetadata\n extends TimeoutCapable,\n RequestHeadersCapable,\n ResultExtractorCapable,\n FetcherCapable, AttributesCapable {\n /**\n * Base path for all endpoints in the class.\n *\n * This path will be prepended to all endpoint paths defined in the class.\n * For example, if basePath is '/api/v1' and an endpoint has path '/users',\n * the full path will be '/api/v1/users'.\n */\n basePath?: string;\n\n /**\n * Default headers for all requests in the class.\n *\n * These headers will be included in every request made by methods in this class.\n * They can be overridden or extended at the method level.\n */\n headers?: RequestHeaders;\n\n /**\n * Default timeout for all requests in the class (in milliseconds).\n *\n * This timeout value will be applied to all requests made by methods in this class.\n * Individual methods can specify their own timeout values to override this default.\n */\n timeout?: number;\n\n /**\n * Name of the fetcher instance to use, default: 'default'.\n *\n * This allows you to specify which fetcher instance should be used for requests\n * from this API class. The fetcher must be registered with the FetcherRegistrar.\n */\n fetcher?: string | Fetcher;\n}\n\nexport const API_METADATA_KEY = Symbol('api:metadata');\n\n/**\n * Binds a request executor to a method, replacing the original method with\n * an implementation that makes HTTP requests based on the decorator metadata.\n *\n * @param constructor - The class constructor\n * @param functionName - The name of the method to bind\n * @param apiMetadata - The API metadata for the class\n */\nfunction bindExecutor<T extends new (...args: any[]) => any>(\n constructor: T,\n functionName: string,\n apiMetadata: ApiMetadata,\n) {\n const endpointFunction = constructor.prototype[functionName];\n if (functionName === 'constructor') {\n return;\n }\n if (typeof endpointFunction !== 'function') {\n return;\n }\n\n const endpointMetadata = Reflect.getMetadata(\n ENDPOINT_METADATA_KEY,\n constructor.prototype,\n functionName,\n );\n if (!endpointMetadata) {\n return;\n }\n // Get parameter metadata for this method\n const parameterMetadata =\n Reflect.getMetadata(\n PARAMETER_METADATA_KEY,\n constructor.prototype,\n functionName,\n ) || new Map();\n\n // Create function metadata\n const functionMetadata = new FunctionMetadata(\n functionName,\n apiMetadata,\n endpointMetadata,\n parameterMetadata,\n );\n\n // Create request executor\n const requestExecutor = new RequestExecutor(functionMetadata);\n\n // Replace method with actual implementation\n constructor.prototype[functionName] = function(...args: unknown[]) {\n return requestExecutor.execute(this, args);\n };\n}\n\nexport function api(\n basePath: string = '',\n metadata: Omit<ApiMetadata, 'basePath'> = {},\n) {\n return function <T extends new (...args: any[]) => any>(constructor: T): T {\n const apiMetadata: ApiMetadata = {\n basePath,\n ...metadata,\n };\n\n // Store metadata directly on the class constructor\n Reflect.defineMetadata(API_METADATA_KEY, apiMetadata, constructor);\n\n // Override prototype methods to implement actual HTTP calls\n Object.getOwnPropertyNames(constructor.prototype).forEach(functionName => {\n bindExecutor(constructor, functionName, apiMetadata);\n });\n\n return constructor;\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Custom error class that indicates a method implementation will be automatically generated.\n *\n * @example\n * ```\n * @post()\n * createUser(@body() user: User):Promise<Response> {\n * throw autoGeneratedError(user);\n * }\n * ```\n */\nexport class AutoGenerated extends Error {\n constructor() {\n super('Implementation will be generated automatically.');\n this.name = 'AutoGenerated';\n }\n}\n\n/**\n * Factory function that creates an AutoGenerated error instance.\n * This is typically used in methods that will be automatically implemented,\n * where a placeholder implementation is needed.\n *\n * @param _ignored - Arguments (such as 'user' in the example) are ignored to prevent\n * ESLint no-unused-vars errors in method signatures that will be auto-generated.\n * @returns A new AutoGenerated error instance\n */\nexport const autoGeneratedError = (..._ignored: any[]): AutoGenerated => {\n return new AutoGenerated();\n};\n"],"names":["ENDPOINT_METADATA_KEY","endpoint","method","path","metadata","target","propertyKey","endpointMetadata","get","HttpMethod","post","put","del","patch","head","options","TARGET_FETCHER_PROPERTY","DECORATOR_TARGET_ATTRIBUTE_KEY","RequestExecutor","fetcher","Fetcher","args","exchangeInit","extractor","parameterNameCache","getParameterNames","func","fnStr","paramsStr","extractParameterString","hasParameters","emptyResult","result","parseParameterNames","errorResult","getParameterName","parameterIndex","providedName","paramNames","endParenIndex","findClosingParenthesis","startParenIndex","str","openingParenIndex","parenDepth","i","char","trimWhitespace","isNotEmpty","extractParameterName","param","cleanedParam","removeDefaultValue","removeTypeAnnotation","equalsIndex","colonIndex","ParameterType","PARAMETER_METADATA_KEY","parameter","type","name","paramName","existingParameters","parameterMetadata","query","header","body","request","attribute","attributes","getFetcher","fetcherRegistrar","ResultExtractors","ExchangeResultExtractor","ResponseResultExtractor","JsonResultExtractor","TextResultExtractor","EventStreamResultExtractor","JsonEventStreamResultExtractor","FunctionMetadata","api","parameters","parameterPath","basePath","endpointPath","combineURLs","pathParams","queryParams","headers","signal","abortController","parameterRequest","value","index","funParameter","urlParams","endpointRequest","mergedRequest","mergeRequest","key","API_METADATA_KEY","bindExecutor","constructor","functionName","apiMetadata","endpointFunction","functionMetadata","requestExecutor","AutoGenerated","autoGeneratedError","_ignored"],"mappings":"kdAiCO,MAAMA,EAAwB,OAAO,mBAAmB,EA4BxD,SAASC,EACdC,EACAC,EACAC,EAAmC,CAAA,EACnC,CACA,OAAO,SAASC,EAAgBC,EAAoC,CAElE,MAAMC,EAAmB,CACvB,OAAAL,EACA,KAAAC,EACA,GAAGC,CAAA,EAEL,QAAQ,eACNJ,EACAO,EACAF,EACAC,CAAA,CAEJ,CACF,CAEO,SAASE,EAAIL,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC5E,OAAOH,EAASQ,EAAAA,WAAW,IAAKN,EAAMC,CAAQ,CAChD,CAEO,SAASM,EAAKP,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC7E,OAAOH,EAASQ,EAAAA,WAAW,KAAMN,EAAMC,CAAQ,CACjD,CAEO,SAASO,EAAIR,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC5E,OAAOH,EAASQ,EAAAA,WAAW,IAAKN,EAAMC,CAAQ,CAChD,CAEO,SAASQ,EAAIT,EAAe,GA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,WAC9B,OAGF,MAAMlG,EAAmB,QAAQ,YAC/BP,EACAsG,EAAY,UACZC,CAAA,EAEF,GAAI,CAAChG,EACH,OAGF,MAAMwD,EACJ,QAAQ,YACNN,EACA6C,EAAY,UACZC,CAAA,OACO,IAGLG,EAAmB,IAAI3B,EAC3BwB,EACAC,EACAjG,EACAwD,CAAA,EAII4C,EAAkB,IAAIzF,EAAgBwF,CAAgB,EAG5DJ,EAAY,UAAUC,CAAY,EAAI,YAAYlF,EAAiB,CACjE,OAAOsF,EAAgB,QAAQ,KAAMtF,CAAI,CAC3C,CACF,CAEO,SAAS2D,GACdG,EAAmB,GACnB/E,EAA0C,CAAA,EAC1C,CACA,OAAO,SAAiDkG,EAAmB,CACzE,MAAME,EAA2B,CAC/B,SAAArB,EACA,GAAG/E,CAAA,EAIL,eAAQ,eAAegG,EAAkBI,EAAaF,CAAW,EAGjE,OAAO,oBAAoBA,EAAY,SAAS,EAAE,QAAQC,GAAgB,CACxEF,GAAaC,EAAaC,EAAcC,CAAW,CACrD,CAAC,EAEMF,CACT,CACF,CC9HO,MAAMM,UAAsB,KAAM,CACvC,aAAc,CACZ,MAAM,iDAAiD,EACvD,KAAK,KAAO,eACd,CACF,CAWO,MAAMC,GAAqB,IAAIC,IAC7B,IAAIF"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/endpointDecorator.ts","../src/requestExecutor.ts","../src/reflection.ts","../src/parameterDecorator.ts","../src/fetcherCapable.ts","../src/resultExtractor.ts","../src/functionMetadata.ts","../src/apiDecorator.ts","../src/generated.ts"],"sourcesContent":["import { HttpMethod, type ResultExtractorCapable } from '@ahoo-wang/fetcher';\nimport { type ApiMetadata } from './apiDecorator';\nimport 'reflect-metadata';\n\nexport interface PathCapable {\n /**\n * Path for the endpoint (relative to class base path).\n *\n * This path will be appended to the class's base path to form the complete URL.\n * Path parameters can be specified using curly braces, e.g., '/users/{id}'\n */\n path?: string;\n}\n\n/**\n * Metadata for HTTP endpoints.\n *\n * Defines the configuration options for individual HTTP endpoints (methods).\n * These settings will override any corresponding class-level settings from ApiMetadata.\n */\nexport interface EndpointMetadata\n extends ApiMetadata,\n ResultExtractorCapable,\n PathCapable {\n /**\n * HTTP method for the endpoint.\n *\n * Specifies the HTTP verb to be used for this endpoint (GET, POST, PUT, DELETE, etc.)\n */\n method?: HttpMethod;\n}\n\nexport const ENDPOINT_METADATA_KEY = Symbol('endpoint:metadata');\n\nexport type MethodEndpointMetadata = Omit<EndpointMetadata, 'method' | 'path'>;\n\n/**\n * Decorator factory for defining HTTP endpoints.\n *\n * Creates a decorator that can be used to define HTTP endpoints\n * on class methods. It stores metadata about the endpoint that will be used\n * to generate the actual HTTP request.\n *\n * @param method - The HTTP method for this endpoint\n * @param path - The path for this endpoint (relative to class base path)\n * @param metadata - Additional endpoint metadata (headers, timeout, etc.)\n * @returns A method decorator function\n *\n * @example\n * ```typescript\n * @api('/api/v1')\n * class UserService {\n * @endpoint(HttpMethod.GET, '/users/{id}')\n * getUser(@path('id') id: string): Promise<Response> {\n * // Implementation will be generated automatically\n * throw autoGeneratedError();\n * }\n * }\n * ```\n */\nexport function endpoint(\n method?: HttpMethod,\n path?: string,\n metadata: MethodEndpointMetadata = {},\n) {\n return function(target: object, propertyKey: string | symbol): void {\n // Store metadata directly on the method\n const endpointMetadata = {\n method: method,\n path,\n ...metadata,\n };\n Reflect.defineMetadata(\n ENDPOINT_METADATA_KEY,\n endpointMetadata,\n target,\n propertyKey,\n );\n };\n}\n\nexport function get(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.GET, path, metadata);\n}\n\nexport function post(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.POST, path, metadata);\n}\n\nexport function put(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.PUT, path, metadata);\n}\n\nexport function del(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.DELETE, path, metadata);\n}\n\nexport function patch(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.PATCH, path, metadata);\n}\n\nexport function head(path: string = '', metadata: MethodEndpointMetadata = {}) {\n return endpoint(HttpMethod.HEAD, path, metadata);\n}\n\nexport function options(\n path: string = '',\n metadata: MethodEndpointMetadata = {},\n) {\n return endpoint(HttpMethod.OPTIONS, path, metadata);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Fetcher } from '@ahoo-wang/fetcher';\nimport { FunctionMetadata } from './functionMetadata';\n\nconst TARGET_FETCHER_PROPERTY = 'fetcher';\n\nexport const DECORATOR_TARGET_ATTRIBUTE_KEY = '__decorator_target__';\n\n/**\n * Executor for HTTP requests based on decorated method metadata.\n *\n * This class is responsible for executing HTTP requests based on the metadata\n * collected from decorators. It resolves the path, constructs the request,\n * and executes it using the appropriate fetcher.\n */\nexport class RequestExecutor {\n private readonly metadata: FunctionMetadata;\n\n /**\n * Creates a new RequestExecutor instance.\n *\n * @param metadata - The function metadata containing all request information\n */\n constructor(metadata: FunctionMetadata) {\n this.metadata = metadata;\n }\n\n /**\n * Retrieves the fetcher instance from the target object.\n *\n * @param target - The target object that may contain a fetcher property\n * @returns The fetcher instance if exists, otherwise undefined\n */\n private getTargetFetcher(target: any): Fetcher | undefined {\n if (!target || typeof target !== 'object') {\n return undefined;\n }\n // Extract the fetcher property from the target object\n const fetcher = target[TARGET_FETCHER_PROPERTY];\n\n // Validate that the fetcher is an instance of the Fetcher class\n if (fetcher instanceof Fetcher) {\n return fetcher;\n }\n\n // Return undefined if no valid fetcher instance is found\n return undefined;\n }\n\n /**\n * Executes the HTTP request.\n *\n * This method resolves the path and request configuration from the metadata\n * and arguments, then executes the request using the configured fetcher.\n * It handles the complete request lifecycle from parameter processing to\n * response extraction.\n *\n * @param target - The target object that the method is called on.\n * This can contain a custom fetcher instance in its 'fetcher' property.\n * @param args - The runtime arguments passed to the decorated method.\n * These are mapped to request components based on parameter decorators.\n * @returns A Promise that resolves to the extracted result based on the configured result extractor.\n * By default, this is the Response object, but can be customized to return\n * parsed JSON, the raw exchange object, or any other transformed result.\n *\n * @example\n * ```typescript\n * // Given a decorated service method:\n * class UserService {\n * @get('/users/{id}')\n * getUser(@path('id') id: number): Promise<Response> {\n * // This method body is replaced by the executor at runtime\n * }\n * }\n *\n * // When calling:\n * const userService = new UserService();\n * const response = await userService.getUser(123);\n *\n * // The execute method will:\n * // 1. Resolve the path to '/users/123'\n * // 2. Create a request with method 'GET'\n * // 3. Execute the request using the configured fetcher\n * // 4. Return the Response object\n * ```\n */\n async execute(target: any, args: any[]): Promise<any> {\n const fetcher = this.getTargetFetcher(target) || this.metadata.fetcher;\n const exchangeInit = this.metadata.resolveExchangeInit(args);\n exchangeInit.attributes?.set(DECORATOR_TARGET_ATTRIBUTE_KEY, target);\n const extractor = this.metadata.resolveResultExtractor();\n return fetcher.request(exchangeInit.request, { resultExtractor: extractor, attributes: exchangeInit.attributes });\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Cache for storing previously extracted parameter names to improve performance\nconst parameterNameCache = new WeakMap<Function, string[]>();\n\n/**\n * Extracts parameter names from a function.\n *\n * This function parses the string representation of a function to extract\n * the names of its parameters. It handles various function formats including\n * regular functions, arrow functions, and methods.\n *\n * Note: This implementation provides basic parameter name extraction and may not\n * handle all edge cases of complex TypeScript parameter declarations.\n *\n * @param func - The function to extract parameter names from\n * @returns An array of parameter names, or an empty array if extraction fails\n * @throws {TypeError} If the input is not a function\n *\n * @example\n * ```typescript\n * function example(a, b, c) {}\n * const paramNames = getParameterNames(example);\n * // Returns: ['a', 'b', 'c']\n *\n * const arrowFunc = (x, y) => x + y;\n * const arrowParamNames = getParameterNames(arrowFunc);\n * // Returns: ['x', 'y']\n *\n * function complex(param1: string, param2: number = 10, ...rest: any[]) {}\n * const complexParamNames = getParameterNames(complex);\n * // Returns: ['param1', 'param2', '...rest']\n * ```\n */\nexport function getParameterNames(func: (...args: any[]) => any): string[] {\n // Validate that the input is a function\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n // Check cache first to improve performance\n if (parameterNameCache.has(func)) {\n return parameterNameCache.get(func)!;\n }\n\n try {\n // Convert function to string and trim whitespace\n const fnStr = func.toString().trim();\n\n // Extract parameter string from the function\n const paramsStr = extractParameterString(fnStr);\n\n // Handle empty parameters\n if (!hasParameters(paramsStr)) {\n const emptyResult: string[] = [];\n parameterNameCache.set(func, emptyResult);\n return emptyResult;\n }\n\n // Parse and clean parameter names\n const result = parseParameterNames(paramsStr);\n parameterNameCache.set(func, result);\n return result;\n } catch {\n // Return empty array on any parsing errors to avoid breaking the application\n const errorResult: string[] = [];\n parameterNameCache.set(func, errorResult);\n return errorResult;\n }\n}\n\n/**\n * Helper function to automatically extract parameter name when not provided.\n *\n * @param target - The target object (class prototype)\n * @param propertyKey - The method name\n * @param parameterIndex - The index of the parameter\n * @param providedName - The name explicitly provided by the user (if any)\n * @returns The parameter name, either provided or automatically extracted\n */\nexport function getParameterName(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n providedName?: string,\n): string | undefined {\n // If a name was explicitly provided, use it\n if (providedName) {\n return providedName;\n }\n\n // Try to automatically extract the parameter name\n try {\n const method = target[propertyKey as keyof typeof target];\n if (method && typeof method === 'function') {\n const paramNames = getParameterNames(method);\n if (parameterIndex < paramNames.length) {\n return paramNames[parameterIndex];\n }\n }\n } catch {\n // If we can't get the parameter name, return undefined\n // This will use default naming in the execution logic\n }\n\n return undefined;\n}\n\n/**\n * Checks if a parameter string contains actual parameters.\n *\n * @param paramsStr - The parameter string to check\n * @returns True if the string contains parameters, false otherwise\n */\nfunction hasParameters(paramsStr: string): boolean {\n return (\n paramsStr !== null && paramsStr !== undefined && paramsStr.trim() !== ''\n );\n}\n\n/**\n * Extracts the parameter string from a function string representation.\n *\n * @param fnStr - The string representation of the function\n * @returns The parameter string, or empty string if not found\n */\nfunction extractParameterString(fnStr: string): string {\n // Handle arrow functions that start with parentheses\n if (fnStr.startsWith('(')) {\n const endParenIndex = findClosingParenthesis(fnStr, 0);\n if (endParenIndex === -1) return '';\n return fnStr.substring(1, endParenIndex);\n }\n\n // Handle regular functions, async functions, and methods\n const startParenIndex = fnStr.indexOf('(');\n if (startParenIndex === -1) return '';\n\n const endParenIndex = findClosingParenthesis(fnStr, startParenIndex);\n if (endParenIndex === -1) return '';\n\n return fnStr.substring(startParenIndex + 1, endParenIndex);\n}\n\n/**\n * Finds the matching closing parenthesis for an opening parenthesis.\n *\n * @param str - The string to search in\n * @param openingParenIndex - The index of the opening parenthesis\n * @returns The index of the matching closing parenthesis, or -1 if not found\n */\nfunction findClosingParenthesis(\n str: string,\n openingParenIndex: number,\n): number {\n let parenDepth = 1;\n\n for (let i = openingParenIndex + 1; i < str.length; i++) {\n const char = str[i];\n\n if (char === '(') {\n parenDepth++;\n } else if (char === ')') {\n parenDepth--;\n if (parenDepth === 0) {\n return i;\n }\n }\n }\n\n return -1; // No matching closing parenthesis found\n}\n\n/**\n * Parses and cleans parameter names from a parameter string.\n *\n * @param paramsStr - The parameter string to parse\n * @returns An array of cleaned parameter names\n */\nfunction parseParameterNames(paramsStr: string): string[] {\n return paramsStr\n .split(',')\n .map(trimWhitespace)\n .filter(isNotEmpty)\n .map(extractParameterName);\n}\n\n/**\n * Trims whitespace from a string.\n *\n * @param str - The string to trim\n * @returns The trimmed string\n */\nfunction trimWhitespace(str: string): string {\n return str.trim();\n}\n\n/**\n * Checks if a string is not empty.\n *\n * @param str - The string to check\n * @returns True if the string is not empty, false otherwise\n */\nfunction isNotEmpty(str: string): boolean {\n return str.length > 0;\n}\n\n/**\n * Extracts a clean parameter name by removing type annotations and default values.\n *\n * @param param - The raw parameter string\n * @returns The cleaned parameter name\n */\nfunction extractParameterName(param: string): string {\n // Remove default value assignment (everything after =)\n let cleanedParam = removeDefaultValue(param);\n\n // Remove type annotations (everything after :)\n cleanedParam = removeTypeAnnotation(cleanedParam);\n\n return cleanedParam.trim();\n}\n\n/**\n * Removes default value from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without default value\n */\nfunction removeDefaultValue(param: string): string {\n const equalsIndex = param.indexOf('=');\n if (equalsIndex !== -1) {\n return param.substring(0, equalsIndex);\n }\n return param;\n}\n\n/**\n * Removes type annotation from a parameter string.\n *\n * @param param - The parameter string\n * @returns The parameter string without type annotation\n */\nfunction removeTypeAnnotation(param: string): string {\n const colonIndex = param.indexOf(':');\n if (colonIndex !== -1) {\n return param.substring(0, colonIndex);\n }\n return param;\n}\n","import { getParameterName } from './reflection';\nimport 'reflect-metadata';\nimport { type PathCapable } from './endpointDecorator';\nimport { type FetchRequestInit } from '@ahoo-wang/fetcher';\n\n/**\n * Parameter types for decorator parameters.\n *\n * Defines the different types of parameters that can be used\n * in API method decorators to specify how arguments should be handled\n * in the HTTP request.\n */\nexport enum ParameterType {\n /**\n * Path parameter that will be inserted into the URL path.\n *\n * Path parameters are used to specify dynamic parts of the URL path.\n * They are defined using curly braces in the endpoint path.\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n * ```\n */\n PATH = 'path',\n\n /**\n * Query parameter that will be appended to the URL query string.\n *\n * Query parameters are used to pass non-hierarchical data to the server.\n * They appear after the '?' in the URL.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n * ```\n */\n QUERY = 'query',\n\n /**\n * Header parameter that will be added to the request headers.\n *\n * Header parameters are used to pass metadata about the request,\n * such as authentication tokens or content type information.\n *\n * @example\n * ```typescript\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n * ```\n */\n HEADER = 'header',\n\n /**\n * Body parameter that will be sent as the request body.\n *\n * The body parameter represents the main data payload of the request.\n * It is typically used with POST, PUT, and PATCH requests.\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\n BODY = 'body',\n\n /**\n * Request parameter that will be used as the request object.\n */\n REQUEST = 'request',\n\n\n /**\n * Attribute parameter that will be used as a single attribute in the request attributes.\n *\n * The attribute parameter allows passing a single key-value pair that will be added\n * to the request attributes object. This is useful for passing specific contextual\n * information that can be accessed by interceptors.\n */\n ATTRIBUTE = 'attribute',\n /**\n * Attributes parameter that will be used as the request attributes.\n *\n * The attributes parameter allows passing custom data that can be accessed\n * by interceptors throughout the request lifecycle. This is useful for\n * sharing contextual information between different parts of the request processing.\n */\n ATTRIBUTES = 'attributes'\n}\n\n/**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter\n * decorated with @path, @query, @header, or @body decorators.\n */\nexport interface ParameterMetadata {\n /**\n * Type of parameter (path, query, header, body).\n *\n * Specifies how this parameter should be handled in the HTTP request.\n */\n type: ParameterType;\n\n /**\n * Name of the parameter (used for path, query, and header parameters).\n *\n * For path and query parameters, this corresponds to the key in the URL.\n * For header parameters, this corresponds to the header name.\n * For body parameters, this is not used.\n */\n name?: string;\n\n /**\n * Index of the parameter in the method signature.\n *\n * This is used to map the runtime argument values to the correct parameter metadata.\n */\n index: number;\n}\n\nexport const PARAMETER_METADATA_KEY = Symbol('parameter:metadata');\n\n/**\n * Decorator factory for method parameters.\n *\n * Creates a decorator that can be used to specify how a method parameter\n * should be handled in the HTTP request. It stores metadata about the parameter\n * that will be used during request execution.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param type - The type of parameter (PATH, QUERY, HEADER, or BODY)\n * @param name - The name of the parameter (used for path, query, and header parameters, optional - auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@parameter(ParameterType.PATH, 'id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@parameter(ParameterType.PATH) userId: string): Promise<Response>\n * ```\n */\nexport function parameter(type: ParameterType, name: string = '') {\n return function(\n target: object,\n propertyKey: string | symbol,\n parameterIndex: number,\n ) {\n const paramName = getParameterName(\n target,\n propertyKey as string,\n parameterIndex,\n name,\n );\n\n const existingParameters: Map<number, ParameterMetadata> =\n Reflect.getMetadata(PARAMETER_METADATA_KEY, target, propertyKey) ||\n new Map();\n const parameterMetadata: ParameterMetadata = {\n type: type,\n name: paramName,\n index: parameterIndex,\n };\n existingParameters.set(parameterIndex, parameterMetadata);\n Reflect.defineMetadata(\n PARAMETER_METADATA_KEY,\n existingParameters,\n target,\n propertyKey,\n );\n };\n}\n\n/**\n * Path parameter decorator.\n *\n * Defines a path parameter that will be inserted into the URL path.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the path parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users/{id}')\n * getUser(@path('id') userId: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users/{userId}')\n * getUser(@path() userId: string): Promise<Response>\n * ```\n */\nexport function path(name: string = '') {\n return parameter(ParameterType.PATH, name);\n}\n\n/**\n * Query parameter decorator.\n *\n * Defines a query parameter that will be appended to the URL query string.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the query parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@query('limit') limit: number): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@query() limit: number): Promise<Response>\n * ```\n */\nexport function query(name: string = '') {\n return parameter(ParameterType.QUERY, name);\n}\n\n/**\n * Header parameter decorator.\n *\n * Defines a header parameter that will be added to the request headers.\n * The name is optional - if not provided, it will be automatically extracted\n * from the method parameter name using reflection.\n *\n * @param name - The name of the header parameter (optional, auto-extracted if not provided)\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * // With explicit name\n * @get('/users')\n * getUsers(@header('Authorization') token: string): Promise<Response>\n *\n * // With auto-extracted name\n * @get('/users')\n * getUsers(@header() authorization: string): Promise<Response>\n * ```\n */\nexport function header(name: string = '') {\n return parameter(ParameterType.HEADER, name);\n}\n\n/**\n * Body parameter decorator.\n *\n * Defines a body parameter that will be sent as the request body.\n * Note that body parameters don't have names since there's only one body per request.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUser(@body() user: User): Promise<Response>\n * ```\n */\nexport function body() {\n return parameter(ParameterType.BODY);\n}\n\n/**\n * Interface for request parameter objects.\n *\n * Combines FetchRequestInit and PathCapable interfaces to provide\n * a complete request configuration object that can be used with\n * the @request() decorator. This allows full customization of\n * the HTTP request including method, headers, body, and URL parameters.\n */\nexport interface ParameterRequest extends FetchRequestInit, PathCapable {\n}\n\n/**\n * Request parameter decorator.\n *\n * Defines a request parameter that will be used as the base request object.\n * This allows you to pass a complete ParameterRequest object to customize\n * the request configuration.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: ParameterRequest): Promise<Response>\n * ```\n */\nexport function request() {\n return parameter(ParameterType.REQUEST);\n}\n\n/**\n * Parameter decorator for adding a single attribute to the request attributes.\n *\n * This decorator allows you to pass a key-value pair as an attribute that can be accessed\n * by interceptors during the request lifecycle. If no name is provided, the parameter's\n * property name will be used as the attribute key.\n *\n * @param name - Optional name for the attribute. If not provided, the parameter's property name will be used.\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute('userId') userId: string): Promise<Response>\n *\n * // Using property name as attribute key\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attribute() userId: string): Promise<Response>\n * ```\n */\nexport function attribute(name: string = '') {\n return parameter(ParameterType.ATTRIBUTE, name);\n}\n\n/**\n * Parameter decorator for adding multiple attributes to the request.\n *\n * This decorator allows you to pass an entire object as attributes that can be accessed\n * by interceptors during the request lifecycle. The parameter should be an object whose\n * properties will be merged into the request attributes.\n *\n * @returns A parameter decorator function\n *\n * @example\n * ```typescript\n * @get('/users/{id}')\n * getUser(@path('id') id: string, @attributes() attrs: Record<string, any>): Promise<Response>\n * ```\n */\nexport function attributes() {\n return parameter(ParameterType.ATTRIBUTES);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';\n\n/**\n * Interface that defines a capability for objects that can have a fetcher.\n * This interface is typically used to mark components or objects that can perform fetching operations\n * and may need access to fetcher functionality.\n */\nexport interface FetcherCapable {\n /**\n * Optional fetcher property that can be either a string identifier or a Fetcher instance.\n * When present, this property indicates the fetcher associated with the implementing object.\n */\n fetcher?: string | Fetcher;\n}\n\n/**\n * Gets a Fetcher instance based on the provided fetcher parameter.\n *\n * @param fetcher - A string identifier or Fetcher instance to resolve\n * @returns A Fetcher instance if found, undefined otherwise\n */\nexport function getFetcher(fetcher?: string | Fetcher): Fetcher | undefined {\n // Return undefined if no fetcher is provided\n if (!fetcher) {\n return undefined;\n }\n\n // Return the fetcher directly if it's already a Fetcher instance,\n // otherwise resolve it through the fetcher registrar\n return fetcher instanceof Fetcher\n ? fetcher\n : fetcherRegistrar.requiredGet(fetcher);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ExchangeResultExtractor,\n JsonResultExtractor,\n ResponseResultExtractor,\n TextResultExtractor,\n} from '@ahoo-wang/fetcher';\nimport {\n EventStreamResultExtractor,\n JsonEventStreamResultExtractor,\n} from '@ahoo-wang/fetcher-eventstream';\n\n/**\n * ResultExtractors is an object that maps result extractor names to their corresponding\n * extractor functions. These extractors are used to process and extract data from different\n * types of responses or results in the application.\n *\n * Each property represents a specific type of result extractor:\n * - Exchange: Handles exchange-related result extraction\n * - Response: Handles general response result extraction\n * - Json: Handles JSON format result extraction\n * - Text: Handles plain text result extraction\n * - EventStream: Handles server-sent event stream result extraction\n * - JsonEventStream: Handles JSON server-sent event stream result extraction\n */\nexport const ResultExtractors = {\n Exchange: ExchangeResultExtractor,\n Response: ResponseResultExtractor,\n Json: JsonResultExtractor,\n Text: TextResultExtractor,\n EventStream: EventStreamResultExtractor,\n JsonEventStream: JsonEventStreamResultExtractor,\n DEFAULT: JsonResultExtractor,\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n combineURLs,\n Fetcher, fetcher,\n type FetchExchangeInit,\n FetchRequestInit, mergeRecordToMap,\n mergeRequest,\n NamedCapable,\n type RequestHeaders,\n ResultExtractor,\n type UrlParams,\n} from '@ahoo-wang/fetcher';\nimport { ApiMetadata } from './apiDecorator';\nimport { EndpointMetadata } from './endpointDecorator';\nimport { ParameterMetadata, ParameterRequest, ParameterType } from './parameterDecorator';\nimport { getFetcher } from './fetcherCapable';\nimport { ResultExtractors } from './resultExtractor';\n\n/**\n * Metadata container for a function with HTTP endpoint decorators.\n *\n * Encapsulates all the metadata needed to execute an HTTP request\n * for a decorated method, including API-level defaults, endpoint-specific\n * configuration, and parameter metadata.\n */\nexport class FunctionMetadata implements NamedCapable {\n /**\n * Name of the function.\n */\n name: string;\n\n /**\n * API-level metadata (class-level configuration).\n */\n api: ApiMetadata;\n\n /**\n * Endpoint-level metadata (method-level configuration).\n */\n endpoint: EndpointMetadata;\n\n /**\n * Metadata for method parameters.\n *\n * Defines the metadata stored for each parameter decorated with @path, @query,\n * @header, or @body decorators. Stored as a Map keyed by parameter index.\n *\n * @remarks\n * The metadata is stored as a Map<number, ParameterMetadata> where the key is\n * the parameter index and the value is the parameter metadata. This ensures\n * correct parameter ordering regardless of decorator application order.\n */\n parameters: Map<number, ParameterMetadata>;\n\n /**\n * Creates a new FunctionMetadata instance.\n *\n * @param name - The name of the function\n * @param api - API-level metadata\n * @param endpoint - Endpoint-level metadata\n * @param parameters - Parameter metadata array\n */\n constructor(\n name: string,\n api: ApiMetadata,\n endpoint: EndpointMetadata,\n parameters: Map<number, ParameterMetadata>,\n ) {\n this.name = name;\n this.api = api;\n this.endpoint = endpoint;\n this.parameters = parameters;\n }\n\n /**\n * Gets the fetcher instance to use for this function.\n *\n * Returns the fetcher specified in the endpoint metadata, or the API metadata,\n * or falls back to the default fetcher if none is specified.\n *\n * @returns The fetcher instance\n */\n get fetcher(): Fetcher {\n return getFetcher(this.endpoint.fetcher ?? this.api.fetcher) ?? fetcher;\n }\n\n /**\n * Resolves the complete path by combining base path and endpoint path\n *\n * @param parameterPath - Optional path parameter to use instead of endpoint path\n * @returns The combined URL path\n */\n resolvePath(parameterPath?: string): string {\n // Get the base path from endpoint, API, or default to empty string\n const basePath = this.endpoint.basePath || this.api.basePath || '';\n\n // Use provided parameter path or fallback to endpoint path\n const endpointPath = parameterPath || this.endpoint.path || '';\n\n // Combine the base path and endpoint path into a complete URL\n return combineURLs(basePath, endpointPath);\n }\n\n /**\n * Resolves the timeout for the request.\n *\n * Returns the timeout specified in the endpoint metadata, or the API metadata,\n * or undefined if no timeout is specified.\n *\n * @returns The timeout value in milliseconds, or undefined\n */\n resolveTimeout(): number | undefined {\n return this.endpoint.timeout || this.api.timeout;\n }\n\n resolveResultExtractor(): ResultExtractor<any> {\n return (\n this.endpoint.resultExtractor ||\n this.api.resultExtractor ||\n ResultExtractors.DEFAULT\n );\n }\n\n resolveAttributes(): Map<string, any> {\n const resolvedAttributes = mergeRecordToMap(this.api.attributes);\n return mergeRecordToMap(this.endpoint.attributes, resolvedAttributes);\n }\n\n /**\n * Resolves the request configuration from the method arguments.\n *\n * This method processes the runtime arguments according to the parameter metadata\n * and constructs a FetcherRequest object with path parameters, query parameters,\n * headers, body, and timeout. It handles various parameter types including:\n * - Path parameters (@path decorator)\n * - Query parameters (@query decorator)\n * - Header parameters (@header decorator)\n * - Body parameter (@body decorator)\n * - Complete request object (@request decorator)\n * - AbortSignal for request cancellation\n *\n * The method uses mergeRequest to combine the endpoint-specific configuration\n * with the parameter-provided request object, where the parameter request\n * takes precedence over endpoint configuration.\n *\n * @param args - The runtime arguments passed to the method\n * @returns A FetcherRequest object with all request configuration\n *\n * @example\n * ```typescript\n * // For a method decorated like:\n * @get('/users/{id}')\n * getUser(\n * @path('id') id: number,\n * @query('include') include: string,\n * @header('Authorization') auth: string\n * ): Promise<Response>\n *\n * // Calling with: getUser(123, 'profile', 'Bearer token')\n * // Would produce a request with:\n * // {\n * // method: 'GET',\n * // urlParams: {\n * // path: { id: 123 },\n * // query: { include: 'profile' }\n * // },\n * // headers: {\n * // 'Authorization': 'Bearer token',\n * // ...apiHeaders,\n * // ...endpointHeaders\n * // }\n * // }\n * ```\n */\n resolveExchangeInit(args: any[]): Required<Pick<FetchExchangeInit, 'request' | 'attributes'>> {\n const pathParams: Record<string, any> = {};\n const queryParams: Record<string, any> = {};\n const headers: RequestHeaders = {\n ...this.api.headers,\n ...this.endpoint.headers,\n };\n let body: any = undefined;\n let signal: AbortSignal | null | undefined = undefined;\n let abortController: AbortController | null | undefined = undefined;\n let parameterRequest: ParameterRequest = {};\n const attributes: Map<string, any> = this.resolveAttributes();\n // Process parameters based on their decorators\n args.forEach((value, index) => {\n if (value instanceof AbortSignal) {\n signal = value;\n return;\n }\n if (value instanceof AbortController) {\n abortController = value;\n return;\n }\n const funParameter = this.parameters.get(index);\n if (!funParameter) {\n return;\n }\n switch (funParameter.type) {\n case ParameterType.PATH:\n this.processPathParam(funParameter, value, pathParams);\n break;\n case ParameterType.QUERY:\n this.processQueryParam(funParameter, value, queryParams);\n break;\n case ParameterType.HEADER:\n this.processHeaderParam(funParameter, value, headers);\n break;\n case ParameterType.BODY:\n body = value;\n break;\n case ParameterType.REQUEST:\n parameterRequest = this.processRequestParam(value);\n break;\n case ParameterType.ATTRIBUTE:\n this.processAttributeParam(funParameter, value, attributes);\n break;\n case ParameterType.ATTRIBUTES:\n this.processAttributesParam(value, attributes);\n break;\n }\n });\n const urlParams: UrlParams = {\n path: pathParams,\n query: queryParams,\n };\n const endpointRequest: FetchRequestInit = {\n method: this.endpoint.method,\n urlParams,\n headers,\n body,\n timeout: this.resolveTimeout(),\n signal,\n abortController,\n };\n const mergedRequest = mergeRequest(\n endpointRequest,\n parameterRequest,\n ) as any;\n const parameterPath = parameterRequest.path;\n mergedRequest.url = this.resolvePath(parameterPath);\n return {\n request: mergedRequest,\n attributes,\n };\n }\n\n private processPathParam(\n param: ParameterMetadata,\n value: any,\n path: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n path[paramName] = value;\n }\n\n private processQueryParam(\n param: ParameterMetadata,\n value: any,\n query: Record<string, any>,\n ) {\n const paramName = param.name || `param${param.index}`;\n query[paramName] = value;\n }\n\n private processHeaderParam(\n param: ParameterMetadata,\n value: any,\n headers: RequestHeaders,\n ) {\n if (param.name && value !== undefined) {\n headers[param.name] = String(value);\n }\n }\n\n /**\n * Processes a request parameter value.\n *\n * This method handles the @request() decorator parameter by casting\n * the provided value to a FetcherRequest. The @request() decorator\n * allows users to pass a complete FetcherRequest object to customize\n * the request configuration.\n *\n * @param value - The value provided for the @request() parameter\n * @returns The value cast to FetcherRequest type\n *\n * @example\n * ```typescript\n * @post('/users')\n * createUsers(@request() request: FetcherRequest): Promise<Response>\n *\n * // Usage:\n * const customRequest: FetcherRequest = {\n * headers: { 'X-Custom': 'value' },\n * timeout: 5000\n * };\n * await service.createUsers(customRequest);\n * ```\n */\n private processRequestParam(value: any): ParameterRequest {\n if (!value) {\n return {};\n }\n\n const request = value as ParameterRequest;\n // 确保请求对象中的属性被正确保留\n return {\n ...request,\n headers: request.headers || {},\n urlParams: request.urlParams || { path: {}, query: {} },\n };\n }\n\n\n private processAttributeParam(\n param: ParameterMetadata,\n value: any,\n attributes: Map<string, any>,\n ) {\n if (param.name && value !== undefined) {\n attributes.set(param.name, value);\n }\n }\n\n private processAttributesParam(\n value: any,\n attributes: Map<string, any>,\n ) {\n if (typeof value !== 'object' || value ! instanceof Map) {\n throw new Error('@attributes() parameter must be an object or an Map');\n }\n mergeRecordToMap(value, attributes);\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AttributesCapable,\n Fetcher,\n type RequestHeaders,\n type RequestHeadersCapable,\n type ResultExtractorCapable,\n type TimeoutCapable,\n} from '@ahoo-wang/fetcher';\nimport { ENDPOINT_METADATA_KEY } from './endpointDecorator';\nimport { RequestExecutor } from './requestExecutor';\nimport { PARAMETER_METADATA_KEY } from './parameterDecorator';\nimport 'reflect-metadata';\nimport { type FetcherCapable } from './fetcherCapable';\nimport { FunctionMetadata } from './functionMetadata';\n\n/**\n * Metadata for class-level API configuration.\n *\n * Defines the configuration options that can be applied to an entire API class.\n * These settings will be used as defaults for all endpoints within the class unless overridden\n * at the method level.\n */\nexport interface ApiMetadata\n extends TimeoutCapable,\n RequestHeadersCapable,\n ResultExtractorCapable,\n FetcherCapable, AttributesCapable {\n /**\n * Base path for all endpoints in the class.\n *\n * This path will be prepended to all endpoint paths defined in the class.\n * For example, if basePath is '/api/v1' and an endpoint has path '/users',\n * the full path will be '/api/v1/users'.\n */\n basePath?: string;\n\n /**\n * Default headers for all requests in the class.\n *\n * These headers will be included in every request made by methods in this class.\n * They can be overridden or extended at the method level.\n */\n headers?: RequestHeaders;\n\n /**\n * Default timeout for all requests in the class (in milliseconds).\n *\n * This timeout value will be applied to all requests made by methods in this class.\n * Individual methods can specify their own timeout values to override this default.\n */\n timeout?: number;\n\n /**\n * Name of the fetcher instance to use, default: 'default'.\n *\n * This allows you to specify which fetcher instance should be used for requests\n * from this API class. The fetcher must be registered with the FetcherRegistrar.\n */\n fetcher?: string | Fetcher;\n}\n\nexport const API_METADATA_KEY = Symbol('api:metadata');\n\n/**\n * Binds a request executor to a method, replacing the original method with\n * an implementation that makes HTTP requests based on the decorator metadata.\n *\n * @param constructor - The class constructor\n * @param functionName - The name of the method to bind\n * @param apiMetadata - The API metadata for the class\n */\nfunction bindExecutor<T extends new (...args: any[]) => any>(\n constructor: T,\n functionName: string,\n apiMetadata: ApiMetadata,\n) {\n const endpointFunction = constructor.prototype[functionName];\n if (functionName === 'constructor') {\n return;\n }\n if (typeof endpointFunction !== 'function') {\n return;\n }\n\n const endpointMetadata = Reflect.getMetadata(\n ENDPOINT_METADATA_KEY,\n constructor.prototype,\n functionName,\n );\n if (!endpointMetadata) {\n return;\n }\n // Get parameter metadata for this method\n const parameterMetadata =\n Reflect.getMetadata(\n PARAMETER_METADATA_KEY,\n constructor.prototype,\n functionName,\n ) || new Map();\n\n // Create function metadata\n const functionMetadata = new FunctionMetadata(\n functionName,\n apiMetadata,\n endpointMetadata,\n parameterMetadata,\n );\n\n // Create request executor\n const requestExecutor = new RequestExecutor(functionMetadata);\n\n // Replace method with actual implementation\n constructor.prototype[functionName] = function(...args: unknown[]) {\n return requestExecutor.execute(this, args);\n };\n}\n\nexport function api(\n basePath: string = '',\n metadata: Omit<ApiMetadata, 'basePath'> = {},\n) {\n return function <T extends new (...args: any[]) => any>(constructor: T): T {\n const apiMetadata: ApiMetadata = {\n basePath,\n ...metadata,\n };\n\n // Store metadata directly on the class constructor\n Reflect.defineMetadata(API_METADATA_KEY, apiMetadata, constructor);\n\n // Override prototype methods to implement actual HTTP calls\n Object.getOwnPropertyNames(constructor.prototype).forEach(functionName => {\n bindExecutor(constructor, functionName, apiMetadata);\n });\n\n return constructor;\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Custom error class that indicates a method implementation will be automatically generated.\n *\n * @example\n * ```\n * @post()\n * createUser(@body() user: User):Promise<Response> {\n * throw autoGeneratedError(user);\n * }\n * ```\n */\nexport class AutoGenerated extends Error {\n constructor() {\n super('Implementation will be generated automatically.');\n this.name = 'AutoGenerated';\n }\n}\n\n/**\n * Factory function that creates an AutoGenerated error instance.\n * This is typically used in methods that will be automatically implemented,\n * where a placeholder implementation is needed.\n *\n * @param _ignored - Arguments (such as 'user' in the example) are ignored to prevent\n * ESLint no-unused-vars errors in method signatures that will be auto-generated.\n * @returns A new AutoGenerated error instance\n */\nexport const autoGeneratedError = (..._ignored: any[]): AutoGenerated => {\n return new AutoGenerated();\n};\n"],"names":["ENDPOINT_METADATA_KEY","endpoint","method","path","metadata","target","propertyKey","endpointMetadata","get","HttpMethod","post","put","del","patch","head","options","TARGET_FETCHER_PROPERTY","DECORATOR_TARGET_ATTRIBUTE_KEY","RequestExecutor","fetcher","Fetcher","args","exchangeInit","extractor","parameterNameCache","getParameterNames","func","fnStr","paramsStr","extractParameterString","hasParameters","emptyResult","result","parseParameterNames","errorResult","getParameterName","parameterIndex","providedName","paramNames","endParenIndex","findClosingParenthesis","startParenIndex","str","openingParenIndex","parenDepth","i","char","trimWhitespace","isNotEmpty","extractParameterName","param","cleanedParam","removeDefaultValue","removeTypeAnnotation","equalsIndex","colonIndex","ParameterType","PARAMETER_METADATA_KEY","parameter","type","name","paramName","existingParameters","parameterMetadata","query","header","body","request","attribute","attributes","getFetcher","fetcherRegistrar","ResultExtractors","ExchangeResultExtractor","ResponseResultExtractor","JsonResultExtractor","TextResultExtractor","EventStreamResultExtractor","JsonEventStreamResultExtractor","FunctionMetadata","api","parameters","parameterPath","basePath","endpointPath","combineURLs","resolvedAttributes","mergeRecordToMap","pathParams","queryParams","headers","signal","abortController","parameterRequest","value","index","funParameter","urlParams","endpointRequest","mergedRequest","mergeRequest","API_METADATA_KEY","bindExecutor","constructor","functionName","apiMetadata","endpointFunction","functionMetadata","requestExecutor","AutoGenerated","autoGeneratedError","_ignored"],"mappings":"kdAgCO,MAAMA,EAAwB,OAAO,mBAAmB,EA4BxD,SAASC,EACdC,EACAC,EACAC,EAAmC,CAAA,EACnC,CACA,OAAO,SAASC,EAAgBC,EAAoC,CAElE,MAAMC,EAAmB,CACvB,OAAAL,EACA,KAAAC,EACA,GAAGC,CAAA,EAEL,QAAQ,eACNJ,EACAO,EACAF,EACAC,CAAA,CAEJ,CACF,CAEO,SAASE,EAAIL,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC5E,OAAOH,EAASQ,EAAAA,WAAW,IAAKN,EAAMC,CAAQ,CAChD,CAEO,SAASM,EAAKP,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC7E,OAAOH,EAASQ,EAAAA,WAAW,KAAMN,EAAMC,CAAQ,CACjD,CAEO,SAASO,EAAIR,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC5E,OAAOH,EAASQ,EAAAA,WAAW,IAAKN,EAAMC,CAAQ,CAChD,CAEO,SAASQ,EAAIT,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC5E,OAAOH,EAASQ,EAAAA,WAAW,OAAQN,EAAMC,CAAQ,CACnD,CAEO,SAASS,EACdV,EAAe,GACfC,EAAmC,CAAA,EACnC,CACA,OAAOH,EAASQ,EAAAA,WAAW,MAAON,EAAMC,CAAQ,CAClD,CAEO,SAASU,EAAKX,EAAe,GAAIC,EAAmC,CAAA,EAAI,CAC7E,OAAOH,EAASQ,EAAAA,WAAW,KAAMN,EAAMC,CAAQ,CACjD,CAEO,SAASW,EACdZ,EAAe,GACfC,EAAmC,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AAOuF,EAAgB,QAAQ,KAAMvF,CAAI,CAC3C,CACF,CAEO,SAAS2D,GACdG,EAAmB,GACnB/E,EAA0C,CAAA,EAC1C,CACA,OAAO,SAAiDmG,EAAmB,CACzE,MAAME,EAA2B,CAC/B,SAAAtB,EACA,GAAG/E,CAAA,EAIL,eAAQ,eAAeiG,EAAkBI,EAAaF,CAAW,EAGjE,OAAO,oBAAoBA,EAAY,SAAS,EAAE,QAAQC,GAAgB,CACxEF,GAAaC,EAAaC,EAAcC,CAAW,CACrD,CAAC,EAEMF,CACT,CACF,CC9HO,MAAMM,UAAsB,KAAM,CACvC,aAAc,CACZ,MAAM,iDAAiD,EACvD,KAAK,KAAO,eACd,CACF,CAWO,MAAMC,GAAqB,IAAIC,IAC7B,IAAIF"}
|
|
@@ -1,11 +1,3 @@
|
|
|
1
|
-
import { ResultExtractor } from '@ahoo-wang/fetcher';
|
|
2
|
-
/**
|
|
3
|
-
* Interface with result extractor capability
|
|
4
|
-
* Defines an optional resultExtractor property
|
|
5
|
-
*/
|
|
6
|
-
export interface ResultExtractorCapable {
|
|
7
|
-
resultExtractor?: ResultExtractor<any>;
|
|
8
|
-
}
|
|
9
1
|
/**
|
|
10
2
|
* ResultExtractors is an object that maps result extractor names to their corresponding
|
|
11
3
|
* extractor functions. These extractors are used to process and extract data from different
|
|
@@ -20,12 +12,12 @@ export interface ResultExtractorCapable {
|
|
|
20
12
|
* - JsonEventStream: Handles JSON server-sent event stream result extraction
|
|
21
13
|
*/
|
|
22
14
|
export declare const ResultExtractors: {
|
|
23
|
-
Exchange: ResultExtractor<import('@ahoo-wang/fetcher').FetchExchange>;
|
|
24
|
-
Response: ResultExtractor<Response>;
|
|
25
|
-
Json: ResultExtractor<Promise<any>>;
|
|
26
|
-
Text: ResultExtractor<Promise<string>>;
|
|
27
|
-
EventStream: ResultExtractor<import('@ahoo-wang/fetcher-eventstream').ServerSentEventStream>;
|
|
28
|
-
JsonEventStream: ResultExtractor<import('@ahoo-wang/fetcher-eventstream').JsonServerSentEventStream<any>>;
|
|
29
|
-
DEFAULT: ResultExtractor<Promise<any>>;
|
|
15
|
+
Exchange: import('@ahoo-wang/fetcher').ResultExtractor<import('@ahoo-wang/fetcher').FetchExchange>;
|
|
16
|
+
Response: import('@ahoo-wang/fetcher').ResultExtractor<Response>;
|
|
17
|
+
Json: import('@ahoo-wang/fetcher').ResultExtractor<Promise<any>>;
|
|
18
|
+
Text: import('@ahoo-wang/fetcher').ResultExtractor<Promise<string>>;
|
|
19
|
+
EventStream: import('@ahoo-wang/fetcher').ResultExtractor<import('@ahoo-wang/fetcher-eventstream').ServerSentEventStream>;
|
|
20
|
+
JsonEventStream: import('@ahoo-wang/fetcher').ResultExtractor<import('@ahoo-wang/fetcher-eventstream').JsonServerSentEventStream<any>>;
|
|
21
|
+
DEFAULT: import('@ahoo-wang/fetcher').ResultExtractor<Promise<any>>;
|
|
30
22
|
};
|
|
31
23
|
//# sourceMappingURL=resultExtractor.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resultExtractor.d.ts","sourceRoot":"","sources":["../src/resultExtractor.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"resultExtractor.d.ts","sourceRoot":"","sources":["../src/resultExtractor.ts"],"names":[],"mappings":"AAwBA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;CAQ5B,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/fetcher-decorator",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.2",
|
|
4
4
|
"description": "TypeScript decorators for clean, declarative API service definitions with Fetcher HTTP client. Enables automatic parameter binding, method mapping, and type-safe API interactions.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"fetch",
|
|
@@ -40,8 +40,8 @@
|
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"reflect-metadata": "^0.2.2",
|
|
43
|
-
"@ahoo-wang/fetcher": "1.6.
|
|
44
|
-
"@ahoo-wang/fetcher
|
|
43
|
+
"@ahoo-wang/fetcher-eventstream": "1.6.2",
|
|
44
|
+
"@ahoo-wang/fetcher": "1.6.2"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@vitest/coverage-v8": "^3.2.4",
|