@h-ai/api-client 0.1.0-alpha5
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 +202 -0
- package/README.md +340 -0
- package/dist/index.d.ts +348 -0
- package/dist/index.js +748 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [2026] [idealworld.group]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
# @h-ai/api-client
|
|
2
|
+
|
|
3
|
+
统一 HTTP 客户端模块,提供 Bearer Token 管理、契约调用与流式请求能力。
|
|
4
|
+
|
|
5
|
+
## 支持的能力
|
|
6
|
+
|
|
7
|
+
- 单例模式:`api.init()` → `api.get()` / `api.call()` → `api.close()`
|
|
8
|
+
- 通用 HTTP 方法:`get` / `post` / `put` / `patch` / `delete`
|
|
9
|
+
- 契约调用:`api.call(endpoint, input)`(入参/出参 Zod 双向校验,端到端类型安全)
|
|
10
|
+
- 自动附加 Bearer Token,401 自动刷新重试(并发去重)
|
|
11
|
+
- 可插拔 Token 存储(默认 localStorage,可切换 memory / Capacitor / 自定义)
|
|
12
|
+
- 文件上传(支持附加字段)
|
|
13
|
+
- SSE 流式响应(`api.stream()`)
|
|
14
|
+
- 请求/响应拦截器
|
|
15
|
+
- 统一返回 `HaiResult<T>`
|
|
16
|
+
|
|
17
|
+
## 快速开始
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { api } from '@h-ai/api-client'
|
|
21
|
+
import { iamEndpoints } from '@h-ai/iam/api'
|
|
22
|
+
|
|
23
|
+
// 1. 初始化
|
|
24
|
+
await api.init({
|
|
25
|
+
baseUrl: 'https://api.example.com/api/v1',
|
|
26
|
+
auth: { refreshUrl: '/auth/refresh' },
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
// 2. 登录(契约调用)
|
|
30
|
+
const loginResult = await api.call(iamEndpoints.login, {
|
|
31
|
+
identifier: 'alice',
|
|
32
|
+
password: 'xxx',
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// 3. 登录成功后保存 Token(后续请求自动附加 Bearer)
|
|
36
|
+
if (loginResult.success) {
|
|
37
|
+
await api.auth.setTokens(loginResult.data.tokens)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// 4. 后续请求自动携带 Token
|
|
41
|
+
const me = await api.call(iamEndpoints.currentUser, {})
|
|
42
|
+
|
|
43
|
+
// 5. 关闭
|
|
44
|
+
await api.close()
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
> `auth.storage` 未传时默认使用 `createLocalStorageTokenStorage()`;在 SSR/测试环境可显式传入 `createMemoryTokenStorage()`。
|
|
48
|
+
|
|
49
|
+
## 与 @h-ai/iam 集成
|
|
50
|
+
|
|
51
|
+
`@h-ai/api-client` 与 `@h-ai/iam` 通过 **API 契约(`EndpointDef`)** 实现端到端类型安全。客户端和服务端共享同一份契约定义,编译时保证一致性。
|
|
52
|
+
|
|
53
|
+
### 架构总览
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
┌─────────────────────────────────────────────────┐
|
|
57
|
+
│ @h-ai/iam/api │
|
|
58
|
+
│ iam-api-schemas.ts ← Zod Schema(唯一真相源) │
|
|
59
|
+
│ iam-api-contract.ts ← iamEndpoints │
|
|
60
|
+
└────────┬────────────────────────┬────────────────┘
|
|
61
|
+
│ │
|
|
62
|
+
┌──────▼──────┐ ┌───────▼────────┐
|
|
63
|
+
│ 客户端 │ │ 服务端 │
|
|
64
|
+
│ api.call() │ HTTP │ kit.fromContract│
|
|
65
|
+
│ @h-ai/ │ ◄────► │ @h-ai/kit │
|
|
66
|
+
│ api-client │ │ │
|
|
67
|
+
└─────────────┘ └─────────────────┘
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### 完整登录 → 使用 → 登出流程
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { api } from '@h-ai/api-client'
|
|
74
|
+
import { iamEndpoints } from '@h-ai/iam/api'
|
|
75
|
+
|
|
76
|
+
// ── 初始化 ──
|
|
77
|
+
await api.init({
|
|
78
|
+
baseUrl: 'https://api.example.com/api/v1',
|
|
79
|
+
auth: {
|
|
80
|
+
refreshUrl: '/auth/refresh',
|
|
81
|
+
// Token 刷新成功后的回调(可选,适合更新全局状态)
|
|
82
|
+
onTokenRefreshed: (tokens) => {
|
|
83
|
+
// tokens 包含新的 accessToken / refreshToken / expiresIn
|
|
84
|
+
},
|
|
85
|
+
// Token 刷新失败后的回调(可选,常用于跳转登录页)
|
|
86
|
+
onRefreshFailed: () => {
|
|
87
|
+
window.location.href = '/login'
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
// ── 登录 ──
|
|
93
|
+
const loginResult = await api.call(iamEndpoints.login, {
|
|
94
|
+
identifier: 'alice',
|
|
95
|
+
password: 'StrongPassword123',
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
if (!loginResult.success) {
|
|
99
|
+
// loginResult.error.code 可能是:
|
|
100
|
+
// 1203 (UNAUTHORIZED) — 凭证错误
|
|
101
|
+
// 1206 (VALIDATION_FAILED) — 入参不合法
|
|
102
|
+
// 1202 (SERVER_ERROR) — 服务端异常
|
|
103
|
+
console.error('Login failed:', loginResult.error.message)
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
// loginResult.data 类型自动推导为 { user, tokens, agreements? }
|
|
107
|
+
const { user, tokens } = loginResult.data
|
|
108
|
+
|
|
109
|
+
// 保存 Token — 后续所有请求自动附加 Authorization: Bearer <accessToken>
|
|
110
|
+
await api.auth.setTokens(tokens)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ── 获取当前用户 ──(自动携带 Bearer Token)
|
|
114
|
+
const meResult = await api.call(iamEndpoints.currentUser, {})
|
|
115
|
+
if (meResult.success) {
|
|
116
|
+
// meResult.data 类型推导为 { user, roles, permissions }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ── 修改密码 ──
|
|
120
|
+
await api.call(iamEndpoints.changePassword, {
|
|
121
|
+
oldPassword: 'OldPass123',
|
|
122
|
+
newPassword: 'NewPass456',
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
// ── 登出 ──
|
|
126
|
+
const accessToken = '...' // 从 Token 存储获取
|
|
127
|
+
await api.call(iamEndpoints.logout, { accessToken })
|
|
128
|
+
await api.auth.clear() // 清空本地 Token 存储
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### 401 自动刷新机制
|
|
132
|
+
|
|
133
|
+
当请求收到 401 响应时,`api-client` 自动执行以下流程:
|
|
134
|
+
|
|
135
|
+
1. 使用存储的 `refreshToken` 调用 `auth.refreshUrl`(POST)
|
|
136
|
+
2. 刷新成功 → 更新存储 → 用新 Token 重试原请求(仅重试一次)
|
|
137
|
+
3. 刷新失败 → 清空 Token → 触发 `onRefreshFailed` 回调
|
|
138
|
+
4. 多个并发 401 请求 → **自动去重**,只发一次刷新请求
|
|
139
|
+
|
|
140
|
+
> 流式请求(`api.stream()`)同样支持 401 自动刷新 + 重试。
|
|
141
|
+
|
|
142
|
+
### 可用的 IAM 端点
|
|
143
|
+
|
|
144
|
+
| 分类 | 端点 | 方法 | 路径 | 认证 |
|
|
145
|
+
| ------------ | --------------------------------- | ------ | ----------------------------- | ---- |
|
|
146
|
+
| **认证** | `iamEndpoints.login` | POST | /auth/login | 否 |
|
|
147
|
+
| | `iamEndpoints.loginWithOtp` | POST | /auth/login/otp | 否 |
|
|
148
|
+
| | `iamEndpoints.logout` | POST | /auth/logout | 是 |
|
|
149
|
+
| | `iamEndpoints.currentUser` | GET | /auth/me | 是 |
|
|
150
|
+
| | `iamEndpoints.refreshToken` | POST | /auth/refresh | 否 |
|
|
151
|
+
| | `iamEndpoints.sendOtp` | POST | /auth/otp/send | 否 |
|
|
152
|
+
| | `iamEndpoints.register` | POST | /auth/register | 否 |
|
|
153
|
+
| | `iamEndpoints.changePassword` | POST | /auth/change-password | 是 |
|
|
154
|
+
| | `iamEndpoints.updateCurrentUser` | PUT | /auth/me | 是 |
|
|
155
|
+
| **用户管理** | `iamEndpoints.listUsers` | GET | /iam/users | 是 |
|
|
156
|
+
| | `iamEndpoints.getUser` | GET | /iam/users/:id | 是 |
|
|
157
|
+
| | `iamEndpoints.createUser` | POST | /iam/users | 是 |
|
|
158
|
+
| | `iamEndpoints.updateUser` | PUT | /iam/users/:id | 是 |
|
|
159
|
+
| | `iamEndpoints.deleteUser` | DELETE | /iam/users/:id | 是 |
|
|
160
|
+
| | `iamEndpoints.adminResetPassword` | POST | /iam/users/:id/reset-password | 是 |
|
|
161
|
+
| **角色管理** | `iamEndpoints.listRoles` | GET | /iam/roles | 是 |
|
|
162
|
+
| | `iamEndpoints.getRole` | GET | /iam/roles/:id | 是 |
|
|
163
|
+
| | `iamEndpoints.createRole` | POST | /iam/roles | 是 |
|
|
164
|
+
| | `iamEndpoints.updateRole` | PUT | /iam/roles/:id | 是 |
|
|
165
|
+
| | `iamEndpoints.deleteRole` | DELETE | /iam/roles/:id | 是 |
|
|
166
|
+
| **权限管理** | `iamEndpoints.listPermissions` | GET | /iam/permissions | 是 |
|
|
167
|
+
| | `iamEndpoints.getPermission` | GET | /iam/permissions/:id | 是 |
|
|
168
|
+
| | `iamEndpoints.createPermission` | POST | /iam/permissions | 是 |
|
|
169
|
+
| | `iamEndpoints.deletePermission` | DELETE | /iam/permissions/:id | 是 |
|
|
170
|
+
|
|
171
|
+
## 常见配置场景
|
|
172
|
+
|
|
173
|
+
### 浏览器端(默认 localStorage)
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import { api } from '@h-ai/api-client'
|
|
177
|
+
|
|
178
|
+
await api.init({
|
|
179
|
+
baseUrl: 'https://api.example.com/api/v1',
|
|
180
|
+
auth: { refreshUrl: '/auth/refresh' },
|
|
181
|
+
timeout: 15000,
|
|
182
|
+
})
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Android / iOS App(Capacitor 安全存储)
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { api } from '@h-ai/api-client'
|
|
189
|
+
import { createCapacitorTokenStorage } from '@h-ai/capacitor'
|
|
190
|
+
|
|
191
|
+
await api.init({
|
|
192
|
+
baseUrl: `${PUBLIC_API_BASE}/api/v1`,
|
|
193
|
+
auth: {
|
|
194
|
+
storage: createCapacitorTokenStorage(),
|
|
195
|
+
refreshUrl: '/auth/refresh',
|
|
196
|
+
},
|
|
197
|
+
})
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### SSR / 测试环境(内存存储)
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { api, createMemoryTokenStorage } from '@h-ai/api-client'
|
|
204
|
+
|
|
205
|
+
await api.init({
|
|
206
|
+
baseUrl: 'https://api.example.com/api/v1',
|
|
207
|
+
auth: {
|
|
208
|
+
storage: createMemoryTokenStorage(),
|
|
209
|
+
refreshUrl: '/auth/refresh',
|
|
210
|
+
},
|
|
211
|
+
})
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## 错误处理
|
|
215
|
+
|
|
216
|
+
所有通用 HTTP / 契约调用均返回 `HaiResult<T>`:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
const result = await api.call(iamEndpoints.currentUser, {})
|
|
220
|
+
|
|
221
|
+
if (!result.success) {
|
|
222
|
+
switch (result.error.code) {
|
|
223
|
+
case 1203: // UNAUTHORIZED — Token 失效且刷新也失败
|
|
224
|
+
redirectToLogin()
|
|
225
|
+
break
|
|
226
|
+
case 1201: // TIMEOUT — 请求超时
|
|
227
|
+
showRetryDialog()
|
|
228
|
+
break
|
|
229
|
+
case 1206: // VALIDATION_FAILED — 入参或出参校验失败
|
|
230
|
+
showValidationError(result.error.details)
|
|
231
|
+
break
|
|
232
|
+
default:
|
|
233
|
+
showGenericError(result.error.message)
|
|
234
|
+
}
|
|
235
|
+
return
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// result.data 类型安全
|
|
239
|
+
renderUserProfile(result.data.user)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### 错误码速查
|
|
243
|
+
|
|
244
|
+
| 错误码 | code | 说明 |
|
|
245
|
+
| ---------------------------------------- | -------------------- | ---------------- |
|
|
246
|
+
| `HaiApiClientError.NETWORK_ERROR` | `hai:api-client:001` | 网络不可达 |
|
|
247
|
+
| `HaiApiClientError.TIMEOUT` | `hai:api-client:002` | 请求超时 |
|
|
248
|
+
| `HaiApiClientError.SERVER_ERROR` | `hai:api-client:003` | 5xx 服务端错误 |
|
|
249
|
+
| `HaiApiClientError.UNAUTHORIZED` | `hai:api-client:004` | 401 未认证 |
|
|
250
|
+
| `HaiApiClientError.FORBIDDEN` | `hai:api-client:005` | 403 无权限 |
|
|
251
|
+
| `HaiApiClientError.NOT_FOUND` | `hai:api-client:006` | 404 资源不存在 |
|
|
252
|
+
| `HaiApiClientError.VALIDATION_FAILED` | `hai:api-client:007` | 请求参数校验失败 |
|
|
253
|
+
| `HaiApiClientError.TOKEN_REFRESH_FAILED` | `hai:api-client:008` | Token 刷新失败 |
|
|
254
|
+
| `HaiApiClientError.NOT_INITIALIZED` | `hai:api-client:010` | 未初始化 |
|
|
255
|
+
| `HaiApiClientError.CONFIG_ERROR` | `hai:api-client:011` | 配置错误 |
|
|
256
|
+
| `HaiApiClientError.UNKNOWN` | `hai:api-client:099` | 未知错误 |
|
|
257
|
+
|
|
258
|
+
## Token 管理
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
// 设置 Token(通常在登录成功后)
|
|
262
|
+
await api.auth.setTokens({
|
|
263
|
+
accessToken: 'xxx',
|
|
264
|
+
refreshToken: 'yyy',
|
|
265
|
+
expiresIn: 3600,
|
|
266
|
+
tokenType: 'Bearer',
|
|
267
|
+
})
|
|
268
|
+
|
|
269
|
+
// 清空 Token(登出时)
|
|
270
|
+
await api.auth.clear()
|
|
271
|
+
|
|
272
|
+
// 监听自动刷新事件
|
|
273
|
+
const unsubscribe = api.auth.onTokenRefreshed((tokens) => {
|
|
274
|
+
// Token 自动刷新成功时触发
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
// 取消监听
|
|
278
|
+
unsubscribe()
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
## 流式响应(SSE)
|
|
282
|
+
|
|
283
|
+
```ts
|
|
284
|
+
const controller = new AbortController()
|
|
285
|
+
|
|
286
|
+
for await (const chunk of api.stream('/ai/chat/stream', { message: 'hello' }, { signal: controller.signal })) {
|
|
287
|
+
// chunk 对应 SSE 的 data: 内容
|
|
288
|
+
process.stdout.write(chunk)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// 主动停止流式响应
|
|
292
|
+
controller.abort()
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
说明:
|
|
296
|
+
|
|
297
|
+
- `stream()` 内置超时控制(连接阶段与流式读取阶段均生效)
|
|
298
|
+
- 401 会尝试自动刷新 Token 后重试一次
|
|
299
|
+
- 解析器支持跨 chunk 的 SSE 行缓冲
|
|
300
|
+
- 支持外部传入 `AbortSignal` 主动取消
|
|
301
|
+
|
|
302
|
+
## 拦截器(高级用法)
|
|
303
|
+
|
|
304
|
+
```ts
|
|
305
|
+
await api.init({
|
|
306
|
+
baseUrl: 'https://api.example.com/api/v1',
|
|
307
|
+
auth: { refreshUrl: '/auth/refresh' },
|
|
308
|
+
interceptors: {
|
|
309
|
+
request: [
|
|
310
|
+
async config => ({
|
|
311
|
+
...config,
|
|
312
|
+
headers: {
|
|
313
|
+
...config.headers,
|
|
314
|
+
'X-App-Version': '1.0.0',
|
|
315
|
+
},
|
|
316
|
+
}),
|
|
317
|
+
],
|
|
318
|
+
response: [
|
|
319
|
+
async (response) => {
|
|
320
|
+
// 可统一记录埋点、限流处理等
|
|
321
|
+
return response
|
|
322
|
+
},
|
|
323
|
+
],
|
|
324
|
+
},
|
|
325
|
+
})
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
## 测试
|
|
329
|
+
|
|
330
|
+
```bash
|
|
331
|
+
pnpm --filter @h-ai/api-client test
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
## License
|
|
335
|
+
|
|
336
|
+
Apache-2.0
|
|
337
|
+
|
|
338
|
+
## License
|
|
339
|
+
|
|
340
|
+
Apache-2.0
|