@djiji/freq 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README-cn.md +402 -0
- package/README.md +402 -2
- package/dist/constants.d.ts +9 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/core.d.ts +13 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/errorType.d.ts +31 -0
- package/dist/errorType.d.ts.map +1 -0
- package/dist/hooks.d.ts +7 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/parse.d.ts +8 -0
- package/dist/parse.d.ts.map +1 -0
- package/dist/types.d.ts +78 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils.d.ts +7 -0
- package/dist/utils.d.ts.map +1 -0
- package/package.json +51 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 djiji
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice (including the next
|
|
13
|
+
paragraph) shall be included in all copies or substantial portions of the
|
|
14
|
+
Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README-cn.md
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
# freq
|
|
2
|
+
|
|
3
|
+
命名:`fetch-request -> freq`
|
|
4
|
+
|
|
5
|
+
零依赖的 TypeScript HTTP请求库,基于原生 `fetch` ,自带SSE解析。
|
|
6
|
+
|
|
7
|
+
[English](https://github.com/xinghenyu/freq/blob/master/README.md)
|
|
8
|
+
|
|
9
|
+
- 非 2xx 直接抛错,不用自己判 `ok`
|
|
10
|
+
- `baseURL` 前缀与 `query` 自动拼接
|
|
11
|
+
- `get` / `post` / `put` / `del` 便捷方法,`path` 也能直接传 `http(s)://` 开头的完整 URL
|
|
12
|
+
- 类型友好:`api.get<User>()` 直接拿到 `User`
|
|
13
|
+
- 按 `content-type` 自动解析响应
|
|
14
|
+
- 重试、超时、取消
|
|
15
|
+
- Hooks 四个时机
|
|
16
|
+
- 自带 SSE 解析与断线重连
|
|
17
|
+
- `raw()` 导出原生 `Response`
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm i @djiji/freq
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Node >= 20。
|
|
24
|
+
|
|
25
|
+
## 快速开始
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createClient } from "@djiji/freq";
|
|
29
|
+
|
|
30
|
+
// 创建一个全局的连接配置,这是必要步骤
|
|
31
|
+
const api = createClient({ baseURL: "https://example.com" });
|
|
32
|
+
|
|
33
|
+
// 定义一个用户接口
|
|
34
|
+
interface User {
|
|
35
|
+
name: string;
|
|
36
|
+
age: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// 发送一个 GET 请求,返回一个用户列表
|
|
40
|
+
const res = await api.get<User[]>("/users", {
|
|
41
|
+
query: { page: "2", size: "10" },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
res.code; // 200
|
|
45
|
+
res.data; // [{name: "djiji", age: 18}, {...}]
|
|
46
|
+
res.url; // https://example.com/users?page=2&size=10
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
...
|
|
51
|
+
const api = createClient({}); // 可以传空值
|
|
52
|
+
...
|
|
53
|
+
const res = await api.get<User[]>("https://example.com/users", {
|
|
54
|
+
query: { page: "2", size: "10" },
|
|
55
|
+
});
|
|
56
|
+
...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## 便捷方法
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
api.get("/users", { query: { page: "1" } });
|
|
63
|
+
api.get("https://example.com/users", { query: { page: "1" } }); // 支持绝对路径
|
|
64
|
+
api.post("/users", { body: { name: "djiji" } });
|
|
65
|
+
api.put("/users/1", { body: { age: 19 } });
|
|
66
|
+
api.del("/users/1");
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
四个都是 `api.request()` 加 `method` 的包装:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// 等价关系
|
|
73
|
+
api.request("/users", { method: "GET" });
|
|
74
|
+
api.get("/users");
|
|
75
|
+
...
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## 请求及响应参数
|
|
79
|
+
|
|
80
|
+
注意.get(), post(), put(), del() 等便捷方法传参几乎一致
|
|
81
|
+
|
|
82
|
+
**请求参数**
|
|
83
|
+
` const api = createClient(options?: HttpConfig) `
|
|
84
|
+
```ts
|
|
85
|
+
baseURL?: string; // URL 前缀
|
|
86
|
+
headers?: HeadersInit; // 默认请求头
|
|
87
|
+
timeout?: number; // 请求超时时间
|
|
88
|
+
signal?: AbortSignal; // 取消信号
|
|
89
|
+
retry?: number; // 重试次数, 默认0
|
|
90
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // 重试延迟时间
|
|
91
|
+
retryCodes?: number[]; // 重试状态码
|
|
92
|
+
hooks?: Hooks; // 四个Hook
|
|
93
|
+
sseReconnect?: SSEReconnect; // SSE 断线重连
|
|
94
|
+
responseType?: ResponseType; // 响应体类型,json、text...
|
|
95
|
+
```
|
|
96
|
+
` api.request(path: string, options?: RequestInit) `
|
|
97
|
+
```ts
|
|
98
|
+
method?: string; // 请求方法
|
|
99
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null; // 请求体,普通对象自动格式化并添加Content-Type
|
|
100
|
+
headers?: HeadersInit; // 请求头
|
|
101
|
+
timeout?: number; // 请求超时时间,优先级高于全局
|
|
102
|
+
signal?: AbortSignal; // 取消信号
|
|
103
|
+
query?: Record<string, string>; // 查询参数,自动拼接及编码
|
|
104
|
+
responseType?: ResponseType; // 响应体类型,json、text...,优先级高于全局
|
|
105
|
+
retry?: number; // 重试次数, 默认0
|
|
106
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // 重试延迟时间
|
|
107
|
+
retryCodes?: number[]; // 重试状态码
|
|
108
|
+
hooks?: Hooks; // 四个Hook
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**返回参数**
|
|
112
|
+
```ts
|
|
113
|
+
data: T; // 解析后的响应体,泛型支持
|
|
114
|
+
ok: boolean; // 恒为 `true`,失败一律抛错
|
|
115
|
+
code: number; // 状态码
|
|
116
|
+
url: string; // 最终地址,跟随重定向后
|
|
117
|
+
headers: Headers; // 响应头
|
|
118
|
+
redirected: boolean; // 是否发生过重定向
|
|
119
|
+
```
|
|
120
|
+
## SSE
|
|
121
|
+
|
|
122
|
+
底层用法:自己拿流,用自带解析器处理。
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
const res = await api.request<ReadableStream>("/events", {
|
|
126
|
+
headers: { accept: "text/event-stream" },
|
|
127
|
+
responseType: "stream",
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
for await (const ev of parseSSE(res.data!)) {
|
|
131
|
+
console.log(ev.event, ev.data, ev.id);
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
简便方法,请求和解析一步到位:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
for await (const ev of api.sse("/events")) {
|
|
139
|
+
console.log(ev.event, ev.data, ev.id);
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
加 `reconnect`,断了会自己重连并带上 `Last-Event-ID` 续传:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
for await (const ev of api.sse("/events", { reconnect: { retry: 3 } })) {
|
|
147
|
+
console.log(ev.data);
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
**请求参数**
|
|
152
|
+
` for await (const ev of api.sse(path: string, options?: SSEOptions)) `
|
|
153
|
+
```ts
|
|
154
|
+
path: string; // 相对路径或 http(s):// 完整 URL
|
|
155
|
+
method?: string; // 请求方法,默认 GET
|
|
156
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null; // 请求体
|
|
157
|
+
headers?: HeadersInit; // 请求头,不传自动补 accept: text/event-stream
|
|
158
|
+
timeout?: number; // 默认 0,不会被全局 timeout 掐断;传了才生效
|
|
159
|
+
signal?: AbortSignal; // 取消信号,取消后抛 AbortError
|
|
160
|
+
query?: Record<string, string>; // 查询参数,自动拼接及编码
|
|
161
|
+
retry?: number; // 底层单次请求的重试次数;配了 reconnect 时固定为 0
|
|
162
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // 重连延迟的兜底
|
|
163
|
+
retryCodes?: number[]; // 重连状态码的兜底
|
|
164
|
+
hooks?: Hooks; // 四个Hook
|
|
165
|
+
reconnect?: SSEReconnect; // 断线重连,不传则断流直接抛错;不传时沿用全局 sseReconnect
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`reconnect` 三个字段:
|
|
169
|
+
```ts
|
|
170
|
+
retry?: number; // 最多重连次数,默认 0
|
|
171
|
+
delay?: number | ((attempt: number) => number | Promise<number>); // 实际等待 Math.max(你的值, 服务端 retry)
|
|
172
|
+
codes?: number[]; // 命中这些状态码才重连,默认沿用 retryCodes
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
**返回参数**
|
|
176
|
+
```ts
|
|
177
|
+
// AsyncGenerator<SSEMessage>,用 for await 逐条取
|
|
178
|
+
event: string; // 事件名,没写就是 "message"
|
|
179
|
+
data: string; // 多行 data 已用 \n 拼好
|
|
180
|
+
id: string | undefined; // 事件 id,跨事件粘性
|
|
181
|
+
retry: number | undefined; // 服务端建议的重连间隔,给一次就一直带
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## raw
|
|
185
|
+
|
|
186
|
+
拿到未消费的原生 `Response`
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
const res = await api.raw("/big.zip");
|
|
190
|
+
await res.arrayBuffer();
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
**请求参数**
|
|
194
|
+
` const res = await api.raw(path: string, options?: RequestOptions) `
|
|
195
|
+
```ts
|
|
196
|
+
path: string; // 相对路径或 http(s):// 完整 URL
|
|
197
|
+
options?: RequestOptions; // 同 api.request,见上文
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
**返回参数**
|
|
201
|
+
```ts
|
|
202
|
+
// 原生 Response,body 未消费
|
|
203
|
+
status: number;
|
|
204
|
+
ok: boolean;
|
|
205
|
+
headers: Headers;
|
|
206
|
+
body: ReadableStream<Uint8Array> | null; // 自己读
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
**注意事项**
|
|
210
|
+
|
|
211
|
+
- 不检查状态码:4xx、5xx 正常返回,要自己判 `res.ok`
|
|
212
|
+
- 不解析 body
|
|
213
|
+
- 不触发 `Response` 和 `ResponseError` 钩子
|
|
214
|
+
- 不按状态码重试:只有超时(`TimeoutError`)会重试,网络层连不上(`TypeError`)不重试
|
|
215
|
+
|
|
216
|
+
## 钩子
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
const api = createClient({
|
|
220
|
+
baseURL: "https://api.example.com",
|
|
221
|
+
hooks: {
|
|
222
|
+
Request: [({ headers }) => headers.set("authorization", `Bearer ${token}`)],
|
|
223
|
+
Response: [({ result }) => console.log(result.code)],
|
|
224
|
+
RequestError: [({ error }) => console.warn("没发出去", error)],
|
|
225
|
+
ResponseError: [({ error, code }) => console.warn(code, error)],
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**请求参数**
|
|
231
|
+
` hooks?: Hooks `
|
|
232
|
+
```ts
|
|
233
|
+
Request?: RequestHook[]; // 发请求前,改 url / method / headers / body
|
|
234
|
+
Response?: ResponseHook[]; // 解析完成后,改 result
|
|
235
|
+
RequestError?: RequestErrorHook[]; // fetch 本身失败
|
|
236
|
+
ResponseError?: ResponseErrorHook[]; // 非 2xx 或解析失败
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
各钩子收到的上下文:
|
|
240
|
+
```ts
|
|
241
|
+
// Request
|
|
242
|
+
url: string; method: string; headers: Headers; body: string | undefined;
|
|
243
|
+
// Response
|
|
244
|
+
result: HttpResult<unknown>;
|
|
245
|
+
// RequestError
|
|
246
|
+
error: unknown; url: string; method: string;
|
|
247
|
+
// ResponseError
|
|
248
|
+
error: unknown; code: number; headers: Headers; url: string;
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
**返回参数**
|
|
252
|
+
```ts
|
|
253
|
+
void | Promise<void>; // 不接收返回值,靠改上下文生效
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
**注意事项**
|
|
257
|
+
|
|
258
|
+
- 串行执行,前一个抛错会中断后面的
|
|
259
|
+
- 钩子抛错会被包成 `HookError`,且不触发重试
|
|
260
|
+
- `RequestError`,`ResponseError`钩子抛错会被吞掉,不影响其它钩子
|
|
261
|
+
- 全局钩子与单次请求的钩子叠加,先全局后单次
|
|
262
|
+
|
|
263
|
+
## 错误处理
|
|
264
|
+
|
|
265
|
+
失败一律抛异常,所以 `HttpResult.ok` 恒为 `true`:
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
import {
|
|
269
|
+
HttpError,
|
|
270
|
+
TimeoutError,
|
|
271
|
+
AbortError,
|
|
272
|
+
ParseError,
|
|
273
|
+
HookError,
|
|
274
|
+
} from "@djiji/freq";
|
|
275
|
+
|
|
276
|
+
try {
|
|
277
|
+
await api.get("/missing");
|
|
278
|
+
} catch (e) {
|
|
279
|
+
if (e instanceof HttpError) console.error(e.status, e.body); // 非 2xx
|
|
280
|
+
else if (e instanceof TimeoutError) console.error(e.timeout); // 超时
|
|
281
|
+
else if (e instanceof AbortError) console.error("已取消"); // 主动取消
|
|
282
|
+
else if (e instanceof ParseError) console.error(e.body); // 解析失败
|
|
283
|
+
else if (e instanceof HookError) console.error(e.hook); // 钩子抛错
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
**抛出类型**
|
|
288
|
+
```ts
|
|
289
|
+
HttpError: { status: number; path: string; method: string; body: string; headers: Headers }; // 非 2xx
|
|
290
|
+
TimeoutError: { timeout: number; path: string; method: string }; // 超时
|
|
291
|
+
AbortError: { path: string; method: string }; // 主动取消
|
|
292
|
+
ParseError: { path: string; method: string; body: string; headers: Headers }; // 解析失败
|
|
293
|
+
HookError: { hook: string; cause: unknown }; // 钩子抛错
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
`body` 只保留前 500 字符。
|
|
297
|
+
|
|
298
|
+
## 重试
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
const api = createClient({
|
|
302
|
+
baseURL: "https://api.example.com",
|
|
303
|
+
retry: 3,
|
|
304
|
+
retryDelay: (attempt) => attempt * 500,
|
|
305
|
+
retryCodes: [429, 500, 502, 503, 504, 508],
|
|
306
|
+
});
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
**请求参数**
|
|
310
|
+
```ts
|
|
311
|
+
retry?: number; // 最多重试次数,默认 0;总请求次数是 retry + 1
|
|
312
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // 默认 1000 * 2 ** (attempt - 1),即 1s、2s、4s……
|
|
313
|
+
retryCodes?: number[]; // 命中才重试,默认 [429, 500, 502, 503, 504, 508]
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
**注意事项**
|
|
317
|
+
|
|
318
|
+
- 只有超时、以及命中 `retryCodes` 的状态码会重试
|
|
319
|
+
- 取消、解析失败、钩子抛错、网络层连不上都不重试
|
|
320
|
+
- 单次请求传的同名字段覆盖全局
|
|
321
|
+
- 重试耗尽后抛最后一次的错误
|
|
322
|
+
|
|
323
|
+
## 超时与取消
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
const api = createClient({ timeout: 10_000 });
|
|
327
|
+
|
|
328
|
+
const ac = new AbortController();
|
|
329
|
+
const pending = api.get("/slow", { signal: ac.signal });
|
|
330
|
+
ac.abort();
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
**请求参数**
|
|
334
|
+
```ts
|
|
335
|
+
timeout?: number; // 毫秒,0 或负数表示不限时;单次传的覆盖全局
|
|
336
|
+
signal?: AbortSignal; // 与全局的合并,任一触发就取消
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
**抛出类型**
|
|
340
|
+
```ts
|
|
341
|
+
TimeoutError: { timeout: number; path: string; method: string; cause: unknown }; // 超时
|
|
342
|
+
AbortError: { path: string; method: string; cause: unknown }; // 主动取消,cause 是原始 DOMException
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
**注意事项**
|
|
346
|
+
|
|
347
|
+
- 重试等待期间取消也会立即中断
|
|
348
|
+
- `api.sse` 的 `timeout` 默认 `0`,长连接不会被全局超时掐断
|
|
349
|
+
|
|
350
|
+
## 请求体自动解析
|
|
351
|
+
|
|
352
|
+
**判定规则**
|
|
353
|
+
```ts
|
|
354
|
+
纯对象、数组 → JSON.stringify,并自动补 content-type: application/json
|
|
355
|
+
字符串 → 原样发送,content-type 由 fetch 补
|
|
356
|
+
FormData、URLSearchParams、Blob → 原样发送,content-type 由 fetch 补(含 boundary)
|
|
357
|
+
null、undefined → 不发 body
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
## 响应自动解析
|
|
361
|
+
|
|
362
|
+
**可传参指定解析类型**
|
|
363
|
+
```ts
|
|
364
|
+
responseType?: "json" | "text" | "blob" | "arrayBuffer" | "bytes" | "stream"; // 不传则按 content-type 自动判断
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
**判定规则**
|
|
368
|
+
```ts
|
|
369
|
+
// 不传 responseType 时,按 content-type 从上往下匹配
|
|
370
|
+
含 event-stream → ReadableStream | null
|
|
371
|
+
含 json → 解析结果,空 body 给 undefined
|
|
372
|
+
text/*、xml、html、svg、form-urlencoded、无 content-type → string,空 body 给 undefined
|
|
373
|
+
其余(图片、pdf、octet-stream……)→ Blob
|
|
374
|
+
|
|
375
|
+
// 传了 responseType 时
|
|
376
|
+
"json" → 先读 text 再 JSON.parse,空 body 给 undefined,解析失败抛 ParseError
|
|
377
|
+
"text" → string,空 body 给 undefined
|
|
378
|
+
"blob" → Blob
|
|
379
|
+
"arrayBuffer" → ArrayBuffer
|
|
380
|
+
"bytes" → Uint8Array
|
|
381
|
+
"stream" → ReadableStream | null
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
**返回参数**
|
|
385
|
+
```ts
|
|
386
|
+
data: T; // 实际类型由上面规则决定,泛型由调用时指定
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
对应写法:
|
|
390
|
+
```ts
|
|
391
|
+
await api.get<Data>("/x"); // 自动判断
|
|
392
|
+
await api.get<Data>("/x", { responseType: "json" });
|
|
393
|
+
await api.get<string>("/x", { responseType: "text" });
|
|
394
|
+
await api.get<Blob>("/x", { responseType: "blob" });
|
|
395
|
+
await api.get<Uint8Array>("/x", { responseType: "bytes" });
|
|
396
|
+
await api.get<ArrayBuffer>("/x", { responseType: "arrayBuffer" });
|
|
397
|
+
await api.get<ReadableStream>("/x", { responseType: "stream" });
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
## License
|
|
401
|
+
|
|
402
|
+
MIT © djiji
|
package/README.md
CHANGED
|
@@ -1,3 +1,403 @@
|
|
|
1
|
-
#
|
|
1
|
+
# freq
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Name: `fetch-request -> freq`
|
|
4
|
+
|
|
5
|
+
Zero-dependency TypeScript HTTP client built on native `fetch`, with built-in SSE parsing.
|
|
6
|
+
|
|
7
|
+
[中文文档](https://github.com/xinghenyu/freq/blob/master/README-cn.md)
|
|
8
|
+
|
|
9
|
+
- Throws on non-2xx, no need to check `ok` yourself
|
|
10
|
+
- `baseURL` prefix and `query` joined automatically
|
|
11
|
+
- `get` / `post` / `put` / `del` shortcuts, `path` can also be a full `http(s)://` URL
|
|
12
|
+
- Typed: `api.get<User>()` gives you a `User`
|
|
13
|
+
- Parses the body by `content-type`
|
|
14
|
+
- Retry, timeout, cancellation
|
|
15
|
+
- Four hook stages
|
|
16
|
+
- Built-in SSE parsing and reconnection
|
|
17
|
+
- `raw()` returns the native `Response`
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm i @djiji/freq
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Node >= 20.
|
|
24
|
+
|
|
25
|
+
## Quick Start
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createClient } from "@djiji/freq";
|
|
29
|
+
|
|
30
|
+
// create one client with shared config — this step is required
|
|
31
|
+
const api = createClient({ baseURL: "https://example.com" });
|
|
32
|
+
|
|
33
|
+
// describe the shape you expect
|
|
34
|
+
interface User {
|
|
35
|
+
name: string;
|
|
36
|
+
age: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// GET a list of users
|
|
40
|
+
const res = await api.get<User[]>("/users", {
|
|
41
|
+
query: { page: "2", size: "10" },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
res.code; // 200
|
|
45
|
+
res.data; // [{name: "djiji", age: 18}, {...}]
|
|
46
|
+
res.url; // https://example.com/users?page=2&size=10
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
...
|
|
51
|
+
const api = createClient({}); // an empty config is fine
|
|
52
|
+
...
|
|
53
|
+
const res = await api.get<User[]>("https://example.com/users", {
|
|
54
|
+
query: { page: "2", size: "10" },
|
|
55
|
+
});
|
|
56
|
+
...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Shortcuts
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
api.get("/users", { query: { page: "1" } });
|
|
63
|
+
api.get("https://example.com/users", { query: { page: "1" } }); // absolute URL works
|
|
64
|
+
api.post("/users", { body: { name: "djiji" } });
|
|
65
|
+
api.put("/users/1", { body: { age: 19 } });
|
|
66
|
+
api.del("/users/1");
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
All four are `api.request()` with a `method`:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// equivalent
|
|
73
|
+
api.request("/users", { method: "GET" });
|
|
74
|
+
api.get("/users");
|
|
75
|
+
...
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Request and Response
|
|
79
|
+
|
|
80
|
+
Note: `.get()`, `.post()`, `.put()` and `.del()` take almost the same options.
|
|
81
|
+
|
|
82
|
+
**Request**
|
|
83
|
+
` const api = createClient(options?: HttpConfig) `
|
|
84
|
+
```ts
|
|
85
|
+
baseURL?: string; // URL prefix
|
|
86
|
+
headers?: HeadersInit; // default headers
|
|
87
|
+
timeout?: number; // request timeout
|
|
88
|
+
signal?: AbortSignal; // cancellation signal
|
|
89
|
+
retry?: number; // retry count, default 0
|
|
90
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // retry delay
|
|
91
|
+
retryCodes?: number[]; // status codes to retry
|
|
92
|
+
hooks?: Hooks; // four hooks
|
|
93
|
+
sseReconnect?: SSEReconnect; // SSE reconnection
|
|
94
|
+
responseType?: ResponseType; // json, text...
|
|
95
|
+
```
|
|
96
|
+
` api.request(path: string, options?: RequestOptions) `
|
|
97
|
+
```ts
|
|
98
|
+
method?: string; // HTTP method
|
|
99
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null; // plain objects are stringified, content-type is set
|
|
100
|
+
headers?: HeadersInit; // request headers
|
|
101
|
+
timeout?: number; // overrides the global one
|
|
102
|
+
signal?: AbortSignal; // cancellation signal
|
|
103
|
+
query?: Record<string, string>; // joined and encoded automatically
|
|
104
|
+
responseType?: ResponseType; // overrides the global one
|
|
105
|
+
retry?: number; // retry count, default 0
|
|
106
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // retry delay
|
|
107
|
+
retryCodes?: number[]; // status codes to retry
|
|
108
|
+
hooks?: Hooks; // four hooks
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**Response**
|
|
112
|
+
```ts
|
|
113
|
+
data: T; // parsed body, typed by the generic
|
|
114
|
+
ok: boolean; // always true, failures throw
|
|
115
|
+
code: number; // status code
|
|
116
|
+
url: string; // final URL after redirects
|
|
117
|
+
headers: Headers; // response headers
|
|
118
|
+
redirected: boolean; // whether a redirect happened
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## SSE
|
|
122
|
+
|
|
123
|
+
Low-level: grab the stream yourself and feed it to the built-in parser.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const res = await api.request<ReadableStream>("/events", {
|
|
127
|
+
headers: { accept: "text/event-stream" },
|
|
128
|
+
responseType: "stream",
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
for await (const ev of parseSSE(res.data!)) {
|
|
132
|
+
console.log(ev.event, ev.data, ev.id);
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Shortcut — request and parse in one step:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
for await (const ev of api.sse("/events")) {
|
|
140
|
+
console.log(ev.event, ev.data, ev.id);
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
With `reconnect`, a dropped connection is reopened with `Last-Event-ID` to resume:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
for await (const ev of api.sse("/events", { reconnect: { retry: 3 } })) {
|
|
148
|
+
console.log(ev.data);
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**Request**
|
|
153
|
+
` for await (const ev of api.sse(path: string, options?: SSEOptions)) `
|
|
154
|
+
```ts
|
|
155
|
+
path: string; // relative path or full http(s):// URL
|
|
156
|
+
method?: string; // HTTP method, default GET
|
|
157
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null; // request body
|
|
158
|
+
headers?: HeadersInit; // accept: text/event-stream is added when missing
|
|
159
|
+
timeout?: number; // defaults to 0, the global timeout never cuts a long connection
|
|
160
|
+
signal?: AbortSignal; // throws AbortError on cancel
|
|
161
|
+
query?: Record<string, string>; // joined and encoded automatically
|
|
162
|
+
retry?: number; // retries of a single request, forced to 0 when reconnect is set
|
|
163
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // fallback for reconnect delay
|
|
164
|
+
retryCodes?: number[]; // fallback for reconnect codes
|
|
165
|
+
hooks?: Hooks; // four hooks
|
|
166
|
+
reconnect?: SSEReconnect; // without it a dropped stream throws, falls back to the global sseReconnect
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`reconnect` fields:
|
|
170
|
+
```ts
|
|
171
|
+
retry?: number; // max reconnects, default 0
|
|
172
|
+
delay?: number | ((attempt: number) => number | Promise<number>); // waits Math.max(yours, server retry)
|
|
173
|
+
codes?: number[]; // status codes that trigger a reconnect, defaults to retryCodes
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
**Response**
|
|
177
|
+
```ts
|
|
178
|
+
// AsyncGenerator<SSEMessage>, consumed with for await
|
|
179
|
+
event: string; // "message" when not set
|
|
180
|
+
data: string; // multi-line data joined with \n
|
|
181
|
+
id: string | undefined; // sticky across events
|
|
182
|
+
retry: number | undefined; // server-suggested interval, sticky once sent
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## raw
|
|
186
|
+
|
|
187
|
+
Returns the native `Response`, body untouched.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
const res = await api.raw("/big.zip");
|
|
191
|
+
await res.arrayBuffer();
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
**Request**
|
|
195
|
+
` const res = await api.raw(path: string, options?: RequestOptions) `
|
|
196
|
+
```ts
|
|
197
|
+
path: string; // relative path or full http(s):// URL
|
|
198
|
+
options?: RequestOptions; // same as api.request
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
**Response**
|
|
202
|
+
```ts
|
|
203
|
+
// native Response, body not consumed
|
|
204
|
+
status: number;
|
|
205
|
+
ok: boolean;
|
|
206
|
+
headers: Headers;
|
|
207
|
+
body: ReadableStream<Uint8Array> | null; // read it yourself
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
**Notes**
|
|
211
|
+
|
|
212
|
+
- No status check: 4xx and 5xx come back as-is, check `res.ok` yourself
|
|
213
|
+
- Body is not parsed
|
|
214
|
+
- `Response` and `ResponseError` hooks do not fire
|
|
215
|
+
- No status-code retry: only timeouts (`TimeoutError`) retry, network failures (`TypeError`) do not
|
|
216
|
+
|
|
217
|
+
## Hooks
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const api = createClient({
|
|
221
|
+
baseURL: "https://api.example.com",
|
|
222
|
+
hooks: {
|
|
223
|
+
Request: [({ headers }) => headers.set("authorization", `Bearer ${token}`)],
|
|
224
|
+
Response: [({ result }) => console.log(result.code)],
|
|
225
|
+
RequestError: [({ error }) => console.warn("request failed", error)],
|
|
226
|
+
ResponseError: [({ error, code }) => console.warn(code, error)],
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
**Request**
|
|
232
|
+
` hooks?: Hooks `
|
|
233
|
+
```ts
|
|
234
|
+
Request?: RequestHook[]; // before sending, edit url / method / headers / body
|
|
235
|
+
Response?: ResponseHook[]; // after parsing, edit result
|
|
236
|
+
RequestError?: RequestErrorHook[]; // fetch itself failed
|
|
237
|
+
ResponseError?: ResponseErrorHook[]; // non-2xx or parse failure
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Context each hook receives:
|
|
241
|
+
```ts
|
|
242
|
+
// Request
|
|
243
|
+
url: string; method: string; headers: Headers; body: string | undefined;
|
|
244
|
+
// Response
|
|
245
|
+
result: HttpResult<unknown>;
|
|
246
|
+
// RequestError
|
|
247
|
+
error: unknown; url: string; method: string;
|
|
248
|
+
// ResponseError
|
|
249
|
+
error: unknown; code: number; headers: Headers; url: string;
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Response**
|
|
253
|
+
```ts
|
|
254
|
+
void | Promise<void>; // nothing is read back, mutate the context instead
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
**Notes**
|
|
258
|
+
|
|
259
|
+
- Run in sequence, a throw stops the rest
|
|
260
|
+
- A thrown hook is wrapped into `HookError` and is not retried
|
|
261
|
+
- Throws inside `RequestError` / `ResponseError` are swallowed
|
|
262
|
+
- Global hooks and per-request hooks stack, global first
|
|
263
|
+
|
|
264
|
+
## Error Handling
|
|
265
|
+
|
|
266
|
+
Everything fails by throwing, so `HttpResult.ok` is always `true`:
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
import {
|
|
270
|
+
HttpError,
|
|
271
|
+
TimeoutError,
|
|
272
|
+
AbortError,
|
|
273
|
+
ParseError,
|
|
274
|
+
HookError,
|
|
275
|
+
} from "@djiji/freq";
|
|
276
|
+
|
|
277
|
+
try {
|
|
278
|
+
await api.get("/missing");
|
|
279
|
+
} catch (e) {
|
|
280
|
+
if (e instanceof HttpError) console.error(e.status, e.body); // non-2xx
|
|
281
|
+
else if (e instanceof TimeoutError) console.error(e.timeout); // timeout
|
|
282
|
+
else if (e instanceof AbortError) console.error("aborted"); // cancelled
|
|
283
|
+
else if (e instanceof ParseError) console.error(e.body); // parse failure
|
|
284
|
+
else if (e instanceof HookError) console.error(e.hook); // hook threw
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
**Thrown types**
|
|
289
|
+
```ts
|
|
290
|
+
HttpError: { status: number; path: string; method: string; body: string; headers: Headers }; // non-2xx
|
|
291
|
+
TimeoutError: { timeout: number; path: string; method: string }; // timeout
|
|
292
|
+
AbortError: { path: string; method: string }; // cancelled
|
|
293
|
+
ParseError: { path: string; method: string; body: string; headers: Headers }; // parse failure
|
|
294
|
+
HookError: { hook: string; cause: unknown }; // hook threw
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
`body` keeps only the first 500 characters.
|
|
298
|
+
|
|
299
|
+
## Retry
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
const api = createClient({
|
|
303
|
+
baseURL: "https://api.example.com",
|
|
304
|
+
retry: 3,
|
|
305
|
+
retryDelay: (attempt) => attempt * 500,
|
|
306
|
+
retryCodes: [429, 500, 502, 503, 504, 508],
|
|
307
|
+
});
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
**Request**
|
|
311
|
+
```ts
|
|
312
|
+
retry?: number; // max retries, default 0; total attempts = retry + 1
|
|
313
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // default 1000 * 2 ** (attempt - 1), i.e. 1s, 2s, 4s...
|
|
314
|
+
retryCodes?: number[]; // default [429, 500, 502, 503, 504, 508]
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
**Notes**
|
|
318
|
+
|
|
319
|
+
- Only timeouts and status codes in `retryCodes` are retried
|
|
320
|
+
- Cancellation, parse failures, hook throws and network failures are not retried
|
|
321
|
+
- Per-request fields override the global ones
|
|
322
|
+
- The last error is thrown once retries run out
|
|
323
|
+
|
|
324
|
+
## Timeout and Cancellation
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
const api = createClient({ timeout: 10_000 });
|
|
328
|
+
|
|
329
|
+
const ac = new AbortController();
|
|
330
|
+
const pending = api.get("/slow", { signal: ac.signal });
|
|
331
|
+
ac.abort();
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
**Request**
|
|
335
|
+
```ts
|
|
336
|
+
timeout?: number; // milliseconds, 0 or negative means no limit; per-request wins
|
|
337
|
+
signal?: AbortSignal; // merged with the global one, any abort cancels
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
**Thrown types**
|
|
341
|
+
```ts
|
|
342
|
+
TimeoutError: { timeout: number; path: string; method: string; cause: unknown }; // timeout
|
|
343
|
+
AbortError: { path: string; method: string; cause: unknown }; // cancelled, cause is the original DOMException
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
**Notes**
|
|
347
|
+
|
|
348
|
+
- Cancelling during a retry wait aborts immediately
|
|
349
|
+
- `api.sse` uses `timeout: 0`, a long connection is never cut by the global timeout
|
|
350
|
+
|
|
351
|
+
## Request Body
|
|
352
|
+
|
|
353
|
+
**Rules**
|
|
354
|
+
```ts
|
|
355
|
+
plain objects and arrays → JSON.stringify, content-type: application/json is added
|
|
356
|
+
strings → sent as-is, content-type filled by fetch
|
|
357
|
+
FormData, URLSearchParams, Blob → sent as-is, content-type filled by fetch (boundary included)
|
|
358
|
+
null, undefined → no body
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
## Response Parsing
|
|
362
|
+
|
|
363
|
+
**Specify a type**
|
|
364
|
+
```ts
|
|
365
|
+
responseType?: "json" | "text" | "blob" | "arrayBuffer" | "bytes" | "stream"; // when omitted, content-type decides
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
**Rules**
|
|
369
|
+
```ts
|
|
370
|
+
// without responseType, matched top-down against content-type
|
|
371
|
+
contains event-stream → ReadableStream | null
|
|
372
|
+
contains json → parsed value, undefined for an empty body
|
|
373
|
+
text/*, xml, html, svg, form-urlencoded, missing content-type → string, undefined for an empty body
|
|
374
|
+
anything else (images, pdf, octet-stream...) → Blob
|
|
375
|
+
|
|
376
|
+
// with responseType
|
|
377
|
+
"json" → text then JSON.parse, undefined for an empty body, throws ParseError on failure
|
|
378
|
+
"text" → string, undefined for an empty body
|
|
379
|
+
"blob" → Blob
|
|
380
|
+
"arrayBuffer" → ArrayBuffer
|
|
381
|
+
"bytes" → Uint8Array
|
|
382
|
+
"stream" → ReadableStream | null
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
**Response**
|
|
386
|
+
```ts
|
|
387
|
+
data: T; // actual type follows the rules above, T is given at the call site
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
Usage:
|
|
391
|
+
```ts
|
|
392
|
+
await api.get<Data>("/x"); // auto
|
|
393
|
+
await api.get<Data>("/x", { responseType: "json" });
|
|
394
|
+
await api.get<string>("/x", { responseType: "text" });
|
|
395
|
+
await api.get<Blob>("/x", { responseType: "blob" });
|
|
396
|
+
await api.get<Uint8Array>("/x", { responseType: "bytes" });
|
|
397
|
+
await api.get<ArrayBuffer>("/x", { responseType: "arrayBuffer" });
|
|
398
|
+
await api.get<ReadableStream>("/x", { responseType: "stream" });
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
## License
|
|
402
|
+
|
|
403
|
+
MIT © djiji
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** 默认 HTTP 方法。 */
|
|
2
|
+
export declare const DEFAULT_METHOD = "GET";
|
|
3
|
+
/** 默认重试状态码。 */
|
|
4
|
+
export declare const DEFAULT_RETRY_CODES: number[];
|
|
5
|
+
/** 默认退避:1s、2s、4s…(指数)。 */
|
|
6
|
+
export declare const DEFAULT_RETRY_DELAY: (attempt: number) => number;
|
|
7
|
+
/** 错误体/响应体截断长度,避免把整个大 body 塞进 Error。 */
|
|
8
|
+
export declare const MAX_ERROR_BODY = 500;
|
|
9
|
+
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,kBAAkB;AAClB,eAAO,MAAM,cAAc,QAAQ,CAAC;AAEpC,eAAe;AACf,eAAO,MAAM,mBAAmB,EAAE,MAAM,EAAmC,CAAC;AAE5E,0BAA0B;AAC1B,eAAO,MAAM,mBAAmB,YAAa,MAAM,WACxB,CAAC;AAE5B,wCAAwC;AACxC,eAAO,MAAM,cAAc,MAAM,CAAC"}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { HttpConfig, Hooks, HttpResult, RequestOptions, ResponseType } from "./types";
|
|
2
|
+
export declare function readResponse<T>(res: Response, responseType: ResponseType | undefined, path: string, method: string): Promise<HttpResult<T>>;
|
|
3
|
+
interface SendResult {
|
|
4
|
+
response: Response;
|
|
5
|
+
method: string;
|
|
6
|
+
hooks: Hooks;
|
|
7
|
+
}
|
|
8
|
+
export declare function requestResult(config: HttpConfig, path: string, options: RequestOptions | undefined, attempt: number, maxRetry: number, retryCodes: number[]): Promise<SendResult>;
|
|
9
|
+
export declare function once<T = unknown>(config: HttpConfig, path: string, options: RequestOptions | undefined, attempt: number, maxRetry: number, retryCodes: number[]): Promise<HttpResult<T>>;
|
|
10
|
+
export declare function shouldRetry(e: unknown, codes: number[]): boolean;
|
|
11
|
+
export declare function shouldReconnect(e: unknown, codes: number[]): boolean;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=core.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,UAAU,EACV,KAAK,EACL,UAAU,EAEV,cAAc,EACd,YAAY,EACb,MAAM,SAAS,CAAC;AAgBjB,wBAAsB,YAAY,CAAC,CAAC,EAClC,GAAG,EAAE,QAAQ,EACb,YAAY,EAAE,YAAY,GAAG,SAAS,EACtC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAwFxB;AAED,UAAU,UAAU;IAClB,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,KAAK,CAAC;CACd;AAED,wBAAsB,aAAa,CACjC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAAE,GACnB,OAAO,CAAC,UAAU,CAAC,CA8ErB;AAED,wBAAsB,IAAI,CAAC,CAAC,GAAG,OAAO,EACpC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAAE,GACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CA8CxB;AAED,wBAAgB,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAOhE;AAED,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAMpE"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare class HttpError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
readonly path: string;
|
|
4
|
+
readonly method: string;
|
|
5
|
+
readonly body: string;
|
|
6
|
+
readonly headers: Headers;
|
|
7
|
+
constructor(status: number, path: string, method: string, body: string, headers: Headers);
|
|
8
|
+
}
|
|
9
|
+
export declare class TimeoutError extends Error {
|
|
10
|
+
readonly timeout: number | undefined;
|
|
11
|
+
readonly path: string;
|
|
12
|
+
readonly method: string;
|
|
13
|
+
constructor(timeout: number | undefined, path: string, method: string, cause?: unknown);
|
|
14
|
+
}
|
|
15
|
+
export declare class AbortError extends Error {
|
|
16
|
+
readonly path: string;
|
|
17
|
+
readonly method: string;
|
|
18
|
+
constructor(path: string, method: string, cause?: unknown);
|
|
19
|
+
}
|
|
20
|
+
export declare class ParseError extends Error {
|
|
21
|
+
readonly path: string;
|
|
22
|
+
readonly method: string;
|
|
23
|
+
readonly body: string;
|
|
24
|
+
readonly headers: Headers;
|
|
25
|
+
constructor(path: string, method: string, body: string, headers: Headers);
|
|
26
|
+
}
|
|
27
|
+
export declare class HookError extends Error {
|
|
28
|
+
readonly hook: string;
|
|
29
|
+
constructor(hook: string, cause: unknown);
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=errorType.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errorType.d.ts","sourceRoot":"","sources":["../src/errorType.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAU,SAAQ,KAAK;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B,YACE,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EASjB;CACF;AAED,qBAAa,YAAa,SAAQ,KAAK;IACrC,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YACE,OAAO,EAAE,MAAM,GAAG,SAAS,EAC3B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,KAAK,CAAC,EAAE,OAAO,EAUhB;CACF;AAED,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YAAY,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,EAQxD;CACF;AAED,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B,YAAY,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAOvE;CACF;AAED,qBAAa,SAAU,SAAQ,KAAK;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAOvC;CACF"}
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Hooks, RequestHooksContext, RequestErrorHooksContext, ResponseHooksContext, ResponseErrorHooksContext } from "./types";
|
|
2
|
+
export declare function RequestHooks(brc: RequestHooksContext, hooks: Hooks): Promise<void>;
|
|
3
|
+
export declare function ResponseHooks(brc: ResponseHooksContext, hooks: Hooks): Promise<void>;
|
|
4
|
+
export declare function RequestErrorHooks(brc: RequestErrorHooksContext, hooks: Hooks): Promise<void>;
|
|
5
|
+
export declare function ResponseErrorHooks(brc: ResponseErrorHooksContext, hooks: Hooks): Promise<void>;
|
|
6
|
+
export declare function mergeHooks(base: Hooks | undefined, extra: Hooks | undefined): Hooks;
|
|
7
|
+
//# sourceMappingURL=hooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,KAAK,EACL,mBAAmB,EACnB,wBAAwB,EACxB,oBAAoB,EACpB,yBAAyB,EAC1B,MAAM,SAAS,CAAC;AAEjB,wBAAsB,YAAY,CAAC,GAAG,EAAE,mBAAmB,EAAE,KAAK,EAAE,KAAK,iBAQxE;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,oBAAoB,EAAE,KAAK,EAAE,KAAK,iBAQ1E;AAED,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,wBAAwB,EAC7B,KAAK,EAAE,KAAK,iBAOb;AAED,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,yBAAyB,EAC9B,KAAK,EAAE,KAAK,iBAOb;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,KAAK,GAAG,SAAS,EAAE,KAAK,EAAE,KAAK,GAAG,SAAS,GAAG,KAAK,CAanF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { HttpError, TimeoutError, AbortError, ParseError, HookError, } from "./errorType";
|
|
2
|
+
import { parseSSE, type SSEMessage } from "./parse";
|
|
3
|
+
export { parseSSE, type SSEMessage };
|
|
4
|
+
export { readResponse } from "./core";
|
|
5
|
+
export { buildQuery, buildUrl, isAbsoluteUrl } from "./utils";
|
|
6
|
+
import type { DelOptions, GetOptions, HttpConfig, HttpResult, PostOptions, PutOptions, RequestOptions, SSEOptions } from "./types";
|
|
7
|
+
export type { Hooks, HttpConfig, HttpResult, RequestErrorHook, RequestErrorHooksContext, RequestHook, RequestHooksContext, RequestOptions, ResponseErrorHook, ResponseErrorHooksContext, ResponseHook, ResponseHooksContext, ResponseType, SSEReconnect, SSEOptions, } from "./types";
|
|
8
|
+
export declare function createClient(config: HttpConfig): {
|
|
9
|
+
request: <T = unknown>(path: string, options?: RequestOptions) => Promise<HttpResult<T>>;
|
|
10
|
+
get: <T = unknown>(path: string, options?: GetOptions) => Promise<HttpResult<T>>;
|
|
11
|
+
post: <T = unknown>(path: string, options?: PostOptions) => Promise<HttpResult<T>>;
|
|
12
|
+
put: <T = unknown>(path: string, options?: PutOptions) => Promise<HttpResult<T>>;
|
|
13
|
+
del: <T = unknown>(path: string, options?: DelOptions) => Promise<HttpResult<T>>;
|
|
14
|
+
raw: (path: string, options?: RequestOptions) => Promise<Response>;
|
|
15
|
+
sse: (path: string, options?: SSEOptions) => AsyncGenerator<SSEMessage, void, undefined>;
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,UAAU,EACV,SAAS,GACV,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,QAAQ,EAAE,KAAK,UAAU,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,KAAK,UAAU,EAAE,CAAC;AAGrC,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAQ9D,OAAO,KAAK,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,WAAW,EACX,UAAU,EACV,cAAc,EACd,UAAU,EACX,MAAM,SAAS,CAAC;AAEjB,YAAY,EACV,KAAK,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,wBAAwB,EACxB,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,iBAAiB,EACjB,yBAAyB,EACzB,YAAY,EACZ,oBAAoB,EACpB,YAAY,EACZ,YAAY,EACZ,UAAU,GACX,MAAM,SAAS,CAAC;AAEjB,wBAAgB,YAAY,CAAC,MAAM,EAAE,UAAU;cAyCtB,CAAC,kBAChB,MAAM,YACF,cAAc,KACvB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;UAMN,CAAC,kBACZ,MAAM,YACF,UAAU,KACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;WAIL,CAAC,kBACb,MAAM,YACF,WAAW,KACpB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;UAIN,CAAC,kBACZ,MAAM,YACF,UAAU,KACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;UAIN,CAAC,kBACZ,MAAM,YACF,UAAU,KACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;gBAKjB,MAAM,YACF,cAAc,KACvB,OAAO,CAAC,QAAQ,CAAC;gBAmBZ,MAAM,YACF,UAAU,KACnB,cAAc,CAAC,UAAU,EAAE,IAAI,EAAE,SAAS,CAAC;EAiG/C"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var q=class extends Error{status;path;method;body;headers;constructor(t,n,o,r,a){super(`HTTP ${t} ${o} ${n}`),this.name="HttpError",this.status=t,this.path=n,this.method=o,this.body=r,this.headers=a}},S=class extends Error{timeout;path;method;constructor(t,n,o,r){super(t?`Timeout ${t}ms ${o} ${n}`:`Timeout ${o} ${n}`,r===void 0?void 0:{cause:r}),this.name="TimeoutError",this.timeout=t,this.path=n,this.method=o}},g=class extends Error{path;method;constructor(t,n,o){super(`Aborted ${n} ${t}`,o===void 0?void 0:{cause:o}),this.name="AbortError",this.path=t,this.method=n}},x=class extends Error{path;method;body;headers;constructor(t,n,o,r){super(`Parse error ${n} ${t} ${o}`),this.name="ParseError",this.path=t,this.method=n,this.body=o,this.headers=r}},T=class extends Error{hook;constructor(t,n){super(`hook "${t}" failed: ${n instanceof Error?n.message:String(n)}`,{cause:n}),this.name="HookError",this.hook=t}};function G(e,t){let n=[],o=0,r=0;for(;r<e.length;){let a=e.charCodeAt(r);if(a===10){n.push(e.slice(o,r)),r+=1,o=r;continue}if(a===13){if(r+1<e.length)n.push(e.slice(o,r)),r+=e.charCodeAt(r+1)===10?2:1,o=r;else if(t)n.push(e.slice(o,r)),r+=1,o=r;else break;continue}r+=1}return{lines:n,rest:e.slice(o)}}async function*N(e){let t=e.getReader(),n=new TextDecoder,o="",r,a,c="",f=[];function*k(s){if(s===""){f.length>0&&(yield{event:c||"message",data:f.join(`
|
|
2
|
+
`),id:r,retry:a},f=[]),c="";return}if(s.startsWith(":"))return;let i=s.indexOf(":"),p=i===-1?s:s.slice(0,i),u=i===-1?"":s.slice(i+1);u.startsWith(" ")&&(u=u.slice(1)),p==="data"?f.push(u):p==="event"?c=u:p==="id"?u.includes("\0")||(r=u):p==="retry"&&/^\d+$/.test(u)&&(a=Number(u))}try{for(;;){let{done:s,value:i}=await t.read();if(s){o+=n.decode();let{lines:d}=G(o,!0);for(let m of d)yield*k(m);break}o+=n.decode(i,{stream:!0});let{lines:p,rest:u}=G(o,!1);o=u;for(let d of p)yield*k(d)}}finally{try{await t.cancel()}catch{}t.releaseLock()}}function I(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function W(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function M(e,t){if(W(t))return t;if(!e)throw new Error(`baseURL is required when path is not absolute: ${t}`);if(/^\/\/[^/]/.test(t))throw new Error(`protocol-relative URL is not supported: ${t}`);let n=e.replace(/\/+$/,""),o=t.replace(/^\/+/,"");return`${n}/${o}`}function _(e,t){if(!t||Object.keys(t).length===0)return e;let n=new URLSearchParams(t).toString();return e.includes("?")?e.endsWith("?")?`${e}${n}`:`${e}&${n}`:`${e}?${n}`}function j(e,t){return new Promise((n,o)=>{if(t?.aborted){o(t.reason);return}function r(){clearTimeout(a),o(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);t?.addEventListener("abort",r,{once:!0})})}function P(e){let t=e.filter(n=>n!=null);if(t.length!==0)return t.length===1?t[0]:AbortSignal.any(t)}async function J(e,t){try{for(let n of t.Request??[])await n(e)}catch(n){throw new T("Request",n)}}async function Q(e,t){try{for(let n of t.Response??[])await n(e)}catch(n){throw new T("Response",n)}}async function X(e,t){for(let n of t.RequestError??[])try{await n(e)}catch{}}async function z(e,t){for(let n of t.ResponseError??[])try{await n(e)}catch{}}function K(e,t){return{Request:[...e?.Request??[],...t?.Request??[]],Response:[...e?.Response??[],...t?.Response??[]],RequestError:[...e?.RequestError??[],...t?.RequestError??[]],ResponseError:[...e?.ResponseError??[],...t?.ResponseError??[]]}}var Y=[429,500,502,503,504,508],B=e=>1e3*2**(e-1),L=500;async function V(e,t,n,o){let r={ok:e.ok,code:e.status,url:e.url,headers:e.headers,redirected:e.redirected};switch(t){case"bytes":return{data:await e.bytes(),...r};case"arrayBuffer":return{data:await e.arrayBuffer(),...r};case"blob":return{data:await e.blob(),...r};case"text":return{data:await e.text(),...r};case"json":{let a=await e.text();if(a==="")return{data:void 0,...r};try{return{data:JSON.parse(a),...r}}catch{throw new x(n,o,a.slice(0,L),e.headers)}}case"stream":return{data:e.body??null,...r};case void 0:{let a=(e.headers.get("content-type")??"")?.toLowerCase();if(a.includes("event-stream"))return{data:e.body??null,...r};if(a.includes("json")){let f=await e.text();if(f==="")return{data:void 0,...r};try{return{data:JSON.parse(f),...r}}catch{throw new x(n,o,f.slice(0,L),e.headers)}}if(a?.startsWith("text")||a.includes("xml")||a.includes("html")||a.includes("svg")||a.includes("form-urlencoded")||a===""){let f=await e.text();return{data:f===""?void 0:f,...r}}return{data:await e.blob(),...r}}default:throw new x(n,o,`unsupported responseType: ${String(t)}`,e.headers)}}async function F(e,t,n,o,r,a){let c=new Headers(e.headers);n?.headers&&new Headers(n.headers).forEach((l,h)=>{c.set(h,l)});let{timeout:f,signal:k,query:s,body:i,...p}=n??{},u=e.signal,d=f??e.timeout,m=d&&d>0?AbortSignal.timeout(d):void 0,H=P([u,k,m]),E=M(e.baseURL,t);s&&(E=_(E,s));let w;I(i)||Array.isArray(i)?(w=JSON.stringify(i),c.has("content-type")||c.set("content-type","application/json")):w=i??void 0;let R=p.method??"GET";if(H?.aborted)throw new g(t,R);let y={url:E,method:R,headers:c,body:typeof w=="string"?w:void 0},O=K(e.hooks,n?.hooks);await J(y,O),R=y.method;let D=y.body!==void 0?y.body:w,A={...p,method:R,headers:y.headers,...D!==void 0?{body:D}:{},...H?{signal:H}:{}},$;try{return $=await fetch(y.url,A),{response:$,method:R,hooks:O}}catch(l){let h=l;if(l instanceof DOMException&&l.name==="TimeoutError"){let U=m!==void 0&&l===m.reason;h=new S(U?d:void 0,t,R,l)}throw l instanceof DOMException&&l.name==="AbortError"&&(h=new g(t,R,l)),(o>=r||!v(h,a))&&await X({error:h,url:y.url,method:R},O),h}}async function Z(e,t,n,o,r,a){let c,f="GET",k={};try{let s=await F(e,t,n,o,r,a);if(c=s.response,f=s.method,k=s.hooks,!c.ok){let p=await c.text();throw new q(c.status,t,f,p.slice(0,L),c.headers)}let i=await V(c,n?.responseType??e.responseType,t,f);return await Q({result:i},k),i}catch(s){throw(o>=r||!v(s,a))&&c&&!(s instanceof T)&&await z({error:s,code:c.status,headers:c.headers,url:c.url},k),s}}function v(e,t){return e instanceof T||e instanceof g||e instanceof x?!1:e instanceof S?!0:e instanceof q?t.includes(e.status):!1}function ee(e,t){return e instanceof g||e instanceof T||e instanceof x?!1:e instanceof q?t.includes(e.status):!0}function ge(e){async function t(s,i,p){let u=i?.retry??e.retry??0;if(!Number.isInteger(u)||u<0)throw new Error(`retry must be a non-negative integer, got ${u}`);let d=i?.retryCodes??e.retryCodes??Y,m=i?.retryDelay??e.retryDelay??B,H;for(let E=0;E<=u;E++)try{return await p(E,u,d)}catch(w){if(H=w,E>=u||!v(w,d))throw w;let R=typeof m=="function"?await m(E+1):m;try{await j(R,P([e.signal,i?.signal]))}catch(y){throw y instanceof DOMException&&y.name==="AbortError"?new g(s,i?.method??"GET",y):y}}throw H}async function n(s,i){return t(s,i,(p,u,d)=>Z(e,s,i,p,u,d))}async function o(s,i){return n(s,{...i,method:"GET"})}async function r(s,i){return n(s,{...i,method:"POST"})}async function a(s,i){return n(s,{...i,method:"PUT"})}async function c(s,i){return n(s,{...i,method:"DELETE"})}async function f(s,i){return t(s,i,async(p,u,d)=>{let{response:m}=await F(e,s,i,p,u,d);return m})}async function*k(s,i){let{reconnect:p,headers:u,...d}=i??{},m=p??e.sseReconnect,H=m?.retry??0,E=m?.codes??d.retryCodes??e.retryCodes??Y,w=d.method??"GET",R=P([e.signal,d.signal]),y=0,O,D;for(;;){let A=new Headers(u);A.has("accept")||A.set("accept","text/event-stream"),O!==void 0&&A.set("Last-Event-ID",O);let $=!1;try{let l={...d,headers:A,responseType:"stream",timeout:d.timeout??0};m&&(l.retry=0);let{data:h}=await n(s,l);if(!h)return;for await(let b of N(h))$=!0,b.id!==void 0&&(O=b.id),b.retry!==void 0&&(D=b.retry),yield b;return}catch(l){let h=l;if(l instanceof DOMException&&(l.name==="AbortError"?h=new g(s,w,l):l.name==="TimeoutError"&&(h=new S(d.timeout,s,w,l))),$&&(y=0),!m||y>=H||!ee(h,E))throw h;y++;let b=m.delay??d.retryDelay??e.retryDelay,U=typeof b=="function"?await b(y):b??B(y),te=Math.max(U,D??0);try{await j(te,R)}catch(ne){throw new g(s,w,ne)}}}}return{request:n,get:o,post:r,put:a,del:c,raw:f,sse:k}}export{g as AbortError,T as HookError,q as HttpError,x as ParseError,S as TimeoutError,_ as buildQuery,M as buildUrl,ge as createClient,W as isAbsoluteUrl,N as parseSSE,V as readResponse};
|
package/dist/parse.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../src/parse.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3B;AAiDD,wBAAuB,QAAQ,CAC7B,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GACjC,cAAc,CAAC,UAAU,CAAC,CAmE5B"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export interface HttpConfig {
|
|
2
|
+
baseURL?: string;
|
|
3
|
+
headers?: HeadersInit;
|
|
4
|
+
timeout?: number;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
retry?: number;
|
|
7
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>);
|
|
8
|
+
retryCodes?: number[];
|
|
9
|
+
hooks?: Hooks;
|
|
10
|
+
sseReconnect?: SSEReconnect;
|
|
11
|
+
responseType?: ResponseType;
|
|
12
|
+
}
|
|
13
|
+
export interface RequestHooksContext {
|
|
14
|
+
url: string;
|
|
15
|
+
method: string;
|
|
16
|
+
headers: Headers;
|
|
17
|
+
body: string | undefined;
|
|
18
|
+
}
|
|
19
|
+
export interface ResponseHooksContext {
|
|
20
|
+
result: HttpResult<unknown>;
|
|
21
|
+
}
|
|
22
|
+
export interface RequestErrorHooksContext {
|
|
23
|
+
error: unknown;
|
|
24
|
+
url: string;
|
|
25
|
+
method: string;
|
|
26
|
+
}
|
|
27
|
+
export interface ResponseErrorHooksContext {
|
|
28
|
+
error: unknown;
|
|
29
|
+
code: number;
|
|
30
|
+
headers: Headers;
|
|
31
|
+
url: string;
|
|
32
|
+
}
|
|
33
|
+
export type RequestHook = (ctx: RequestHooksContext) => void | Promise<void>;
|
|
34
|
+
export type ResponseHook = (ctx: ResponseHooksContext) => void | Promise<void>;
|
|
35
|
+
export type RequestErrorHook = (ctx: RequestErrorHooksContext) => void | Promise<void>;
|
|
36
|
+
export type ResponseErrorHook = (ctx: ResponseErrorHooksContext) => void | Promise<void>;
|
|
37
|
+
export interface Hooks {
|
|
38
|
+
Request?: RequestHook[];
|
|
39
|
+
Response?: ResponseHook[];
|
|
40
|
+
RequestError?: RequestErrorHook[];
|
|
41
|
+
ResponseError?: ResponseErrorHook[];
|
|
42
|
+
}
|
|
43
|
+
export interface RequestOptions extends Omit<RequestInit, "body" | "headers" | "method" | "signal"> {
|
|
44
|
+
method?: string;
|
|
45
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null;
|
|
46
|
+
headers?: HeadersInit;
|
|
47
|
+
timeout?: number;
|
|
48
|
+
signal?: AbortSignal;
|
|
49
|
+
query?: Record<string, string>;
|
|
50
|
+
responseType?: ResponseType;
|
|
51
|
+
retry?: number;
|
|
52
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>);
|
|
53
|
+
retryCodes?: number[];
|
|
54
|
+
hooks?: Hooks;
|
|
55
|
+
}
|
|
56
|
+
export interface SSEReconnect {
|
|
57
|
+
retry?: number;
|
|
58
|
+
delay?: number | ((attempt: number) => number | Promise<number>);
|
|
59
|
+
codes?: number[];
|
|
60
|
+
}
|
|
61
|
+
export interface SSEOptions extends Omit<RequestOptions, "responseType"> {
|
|
62
|
+
reconnect?: SSEReconnect;
|
|
63
|
+
}
|
|
64
|
+
type GetOptions = Omit<RequestOptions, "method" | "body">;
|
|
65
|
+
type PostOptions = Omit<RequestOptions, "method">;
|
|
66
|
+
type PutOptions = Omit<RequestOptions, "method">;
|
|
67
|
+
type DelOptions = Omit<RequestOptions, "method">;
|
|
68
|
+
export interface HttpResult<T> {
|
|
69
|
+
data: T;
|
|
70
|
+
ok: boolean;
|
|
71
|
+
code: number;
|
|
72
|
+
url: string;
|
|
73
|
+
headers: Headers;
|
|
74
|
+
redirected: boolean;
|
|
75
|
+
}
|
|
76
|
+
export type ResponseType = "json" | "text" | "blob" | "arrayBuffer" | "bytes" | "stream";
|
|
77
|
+
export type { GetOptions, PostOptions, PutOptions, DelOptions };
|
|
78
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
2
|
+
export declare function isAbsoluteUrl(input: string): boolean;
|
|
3
|
+
export declare function buildUrl(baseURL: string | undefined, path: string): string;
|
|
4
|
+
export declare function buildQuery(url: string, query: Record<string, string>): string;
|
|
5
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
6
|
+
export declare function mergeSignals(list: (AbortSignal | undefined)[]): AbortSignal | undefined;
|
|
7
|
+
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAI9E;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQpD;AAED,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAS1E;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAM7E;AAED,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAmBrE;AAED,wBAAgB,YAAY,CAC1B,IAAI,EAAE,CAAC,WAAW,GAAG,SAAS,CAAC,EAAE,GAChC,WAAW,GAAG,SAAS,CAKzB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@djiji/freq",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@djiji/freq",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Zero-dependency TypeScript HTTP client built on native fetch, with retry, hooks and SSE.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README-cn.md"
|
|
17
|
+
],
|
|
18
|
+
"sideEffects": false,
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=20"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"prepublishOnly": "npm run build",
|
|
24
|
+
"build": "tsup src/index.ts --format esm --minify --clean && tsc -p tsconfig.build.json",
|
|
25
|
+
"check": "tsc --noEmit",
|
|
26
|
+
"test": "tsx --test \"test/**/*.test.ts\""
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"http",
|
|
30
|
+
"fetch",
|
|
31
|
+
"client",
|
|
32
|
+
"sse",
|
|
33
|
+
"typescript"
|
|
34
|
+
],
|
|
35
|
+
"author": "djiji",
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "git+https://github.com/xinghenyu/freq.git"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://github.com/xinghenyu/freq#readme",
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/xinghenyu/freq/issues"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/node": "^26.6.6",
|
|
47
|
+
"tsup": "^9.0.0",
|
|
48
|
+
"tsx": "^4.23.15",
|
|
49
|
+
"typescript": "^7.0.2"
|
|
50
|
+
}
|
|
51
|
+
}
|