@vueboot/http 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +479 -3
- package/dist/index.d.ts +505 -0
- package/dist/index.js +1552 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1552 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
5
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
|
+
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
function createErrorNormalizer() {
|
|
9
|
+
return async (error) => {
|
|
10
|
+
const normalized = await normalize(error);
|
|
11
|
+
return Promise.reject(hideConfig(normalized));
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function hideConfig(error) {
|
|
15
|
+
if (!error.config) return error;
|
|
16
|
+
try {
|
|
17
|
+
Object.defineProperty(error, "config", {
|
|
18
|
+
value: error.config,
|
|
19
|
+
enumerable: false,
|
|
20
|
+
configurable: true,
|
|
21
|
+
writable: true
|
|
22
|
+
});
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
return error;
|
|
26
|
+
}
|
|
27
|
+
function safeAxiosRaw(error) {
|
|
28
|
+
const raw = {
|
|
29
|
+
isAxiosError: true,
|
|
30
|
+
name: error.name,
|
|
31
|
+
message: error.message
|
|
32
|
+
};
|
|
33
|
+
if (error.code !== void 0) raw.code = error.code;
|
|
34
|
+
if (error.status !== void 0) raw.status = error.status;
|
|
35
|
+
if (error.response) {
|
|
36
|
+
raw.response = {
|
|
37
|
+
status: error.response.status,
|
|
38
|
+
statusText: error.response.statusText,
|
|
39
|
+
data: error.response.data
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return raw;
|
|
43
|
+
}
|
|
44
|
+
function sanitizeErrorForPayload(error) {
|
|
45
|
+
if (error && typeof error === "object" && error.isAxiosError === true) {
|
|
46
|
+
return safeAxiosRaw(error);
|
|
47
|
+
}
|
|
48
|
+
return error;
|
|
49
|
+
}
|
|
50
|
+
var KINDS = /* @__PURE__ */ new Set([
|
|
51
|
+
"network",
|
|
52
|
+
"timeout",
|
|
53
|
+
"http",
|
|
54
|
+
"business",
|
|
55
|
+
"canceled",
|
|
56
|
+
"unknown"
|
|
57
|
+
]);
|
|
58
|
+
function isNormalized(error) {
|
|
59
|
+
if (!error || typeof error !== "object") return false;
|
|
60
|
+
const candidate = error;
|
|
61
|
+
return typeof candidate.message === "string" && KINDS.has(candidate.kind);
|
|
62
|
+
}
|
|
63
|
+
function readableMessage(error) {
|
|
64
|
+
if (error instanceof Error && error.message.trim()) return error.message;
|
|
65
|
+
if (typeof error === "string" && error.trim()) return error.trim();
|
|
66
|
+
return "\u672A\u77E5\u9519\u8BEF";
|
|
67
|
+
}
|
|
68
|
+
async function normalize(error) {
|
|
69
|
+
if (isNormalized(error)) return error;
|
|
70
|
+
if (error instanceof Error && "__business__" in error && error.__business__) {
|
|
71
|
+
const business = error;
|
|
72
|
+
return {
|
|
73
|
+
kind: "business",
|
|
74
|
+
code: business.code,
|
|
75
|
+
message: business.message?.trim() ? business.message : "\u4E1A\u52A1\u5904\u7406\u5931\u8D25",
|
|
76
|
+
config: business.config,
|
|
77
|
+
raw: business.raw ?? business
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const axiosError = error;
|
|
81
|
+
if (!axiosError?.isAxiosError) {
|
|
82
|
+
return {
|
|
83
|
+
kind: "unknown",
|
|
84
|
+
message: readableMessage(error),
|
|
85
|
+
config: error?.config,
|
|
86
|
+
raw: error
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (axiosError.code === "ERR_CANCELED") {
|
|
90
|
+
return {
|
|
91
|
+
kind: "canceled",
|
|
92
|
+
message: "\u8BF7\u6C42\u5DF2\u53D6\u6D88",
|
|
93
|
+
config: axiosError.config,
|
|
94
|
+
raw: safeAxiosRaw(axiosError)
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
if (axiosError.code === "ECONNABORTED" || axiosError.code === "ETIMEDOUT" || axiosError.message?.includes("timeout")) {
|
|
98
|
+
return {
|
|
99
|
+
kind: "timeout",
|
|
100
|
+
message: "\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",
|
|
101
|
+
config: axiosError.config,
|
|
102
|
+
raw: safeAxiosRaw(axiosError)
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
if (!axiosError.response) {
|
|
106
|
+
return {
|
|
107
|
+
kind: "network",
|
|
108
|
+
message: "\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5",
|
|
109
|
+
config: axiosError.config,
|
|
110
|
+
raw: safeAxiosRaw(axiosError)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const { status, data } = axiosError.response;
|
|
114
|
+
const body = await readMessageBody(data);
|
|
115
|
+
return {
|
|
116
|
+
kind: "http",
|
|
117
|
+
status,
|
|
118
|
+
message: pickServerMessage(body) ?? `\u8BF7\u6C42\u5931\u8D25\uFF08${status}\uFF09`,
|
|
119
|
+
config: axiosError.config,
|
|
120
|
+
raw: safeAxiosRaw(axiosError)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
async function readMessageBody(data) {
|
|
124
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
125
|
+
const type = data.type ?? "";
|
|
126
|
+
const textual = !type || type.includes("json") || type.startsWith("text/");
|
|
127
|
+
if (!textual) return data;
|
|
128
|
+
try {
|
|
129
|
+
const text = await data.text();
|
|
130
|
+
return parseJsonText(text) ?? text;
|
|
131
|
+
} catch {
|
|
132
|
+
return data;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (typeof ArrayBuffer !== "undefined") {
|
|
136
|
+
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
|
137
|
+
try {
|
|
138
|
+
return parseJsonText(new TextDecoder().decode(data)) ?? data;
|
|
139
|
+
} catch {
|
|
140
|
+
return data;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return data;
|
|
145
|
+
}
|
|
146
|
+
function parseJsonText(text) {
|
|
147
|
+
const trimmed = text.trim();
|
|
148
|
+
if (!trimmed) return void 0;
|
|
149
|
+
try {
|
|
150
|
+
return JSON.parse(trimmed);
|
|
151
|
+
} catch {
|
|
152
|
+
return void 0;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function pickServerMessage(data) {
|
|
156
|
+
if (typeof data === "string") {
|
|
157
|
+
const text = data.trim();
|
|
158
|
+
return text || void 0;
|
|
159
|
+
}
|
|
160
|
+
if (data && typeof data === "object") {
|
|
161
|
+
const body = data;
|
|
162
|
+
for (const value of [body.message, body.msg, body.MSG]) {
|
|
163
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return void 0;
|
|
167
|
+
}
|
|
168
|
+
function toErrorText(error) {
|
|
169
|
+
const normalized = error;
|
|
170
|
+
if (normalized && typeof normalized === "object" && typeof normalized.message === "string" && normalized.message.trim()) {
|
|
171
|
+
return normalized.message;
|
|
172
|
+
}
|
|
173
|
+
if (error instanceof Error && error.message.trim()) return error.message;
|
|
174
|
+
return "\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/session.ts
|
|
178
|
+
var EMPTY = { tokenType: "Bearer", version: 0 };
|
|
179
|
+
var DEFAULT_REFRESH_COOLDOWN_MS = 1e4;
|
|
180
|
+
var DEFAULT_PROACTIVE_COOLDOWN_MS = 3e3;
|
|
181
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
182
|
+
function normalizeExpiresAt(value) {
|
|
183
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
186
|
+
function normalizeToken(value) {
|
|
187
|
+
return typeof value === "string" && value ? value : void 0;
|
|
188
|
+
}
|
|
189
|
+
function createSessionId() {
|
|
190
|
+
const cryptoRef = globalThis.crypto;
|
|
191
|
+
if (typeof cryptoRef?.randomUUID === "function") {
|
|
192
|
+
return cryptoRef.randomUUID();
|
|
193
|
+
}
|
|
194
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
195
|
+
}
|
|
196
|
+
function normalizeVersion(value) {
|
|
197
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
198
|
+
}
|
|
199
|
+
function normalizeSnapshot(raw) {
|
|
200
|
+
if (!raw || typeof raw !== "object") return null;
|
|
201
|
+
const snapshot = raw;
|
|
202
|
+
const accessToken = normalizeToken(snapshot.accessToken);
|
|
203
|
+
const refreshToken = normalizeToken(snapshot.refreshToken);
|
|
204
|
+
if (!accessToken && !refreshToken) return null;
|
|
205
|
+
return {
|
|
206
|
+
accessToken,
|
|
207
|
+
refreshToken,
|
|
208
|
+
tokenType: typeof snapshot.tokenType === "string" && snapshot.tokenType ? snapshot.tokenType : "Bearer",
|
|
209
|
+
expiresAt: normalizeExpiresAt(snapshot.expiresAt),
|
|
210
|
+
refreshExpiresAt: normalizeExpiresAt(snapshot.refreshExpiresAt),
|
|
211
|
+
sessionId: typeof snapshot.sessionId === "string" && snapshot.sessionId ? snapshot.sessionId : void 0,
|
|
212
|
+
version: normalizeVersion(snapshot.version)
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
function refreshError(kind, message) {
|
|
216
|
+
const error = new Error(message);
|
|
217
|
+
Object.assign(error, { kind });
|
|
218
|
+
return error;
|
|
219
|
+
}
|
|
220
|
+
var Session = class {
|
|
221
|
+
constructor(options = {}) {
|
|
222
|
+
__publicField(this, "state", { ...EMPTY });
|
|
223
|
+
__publicField(this, "hydrated", false);
|
|
224
|
+
__publicField(this, "hydratePromise", null);
|
|
225
|
+
__publicField(this, "inflight", null);
|
|
226
|
+
/** 当前 inflight 的所有参与原因:并发调用方可能来自 proactive / unauthorized / bootstrap */
|
|
227
|
+
__publicField(this, "inflightReasons", null);
|
|
228
|
+
__publicField(this, "lastProactiveFailedAt", 0);
|
|
229
|
+
__publicField(this, "lastAuthFailedAt", 0);
|
|
230
|
+
__publicField(this, "expirationTimer", null);
|
|
231
|
+
__publicField(this, "refreshController", null);
|
|
232
|
+
__publicField(this, "refreshTimer", null);
|
|
233
|
+
/** dispose 时主动结算 inflight,避免刷新实现忽略 abort 后请求永久挂起 */
|
|
234
|
+
__publicField(this, "rejectInflightOnDispose", null);
|
|
235
|
+
__publicField(this, "disposed", false);
|
|
236
|
+
__publicField(this, "expiredEmitted", false);
|
|
237
|
+
__publicField(this, "sideEffectsInstalled", false);
|
|
238
|
+
__publicField(this, "unsubscribers", []);
|
|
239
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Map());
|
|
240
|
+
__publicField(this, "storage");
|
|
241
|
+
__publicField(this, "refreshImpl");
|
|
242
|
+
__publicField(this, "refreshTimeoutMs");
|
|
243
|
+
__publicField(this, "refreshCooldownMs");
|
|
244
|
+
__publicField(this, "proactiveCooldownMs");
|
|
245
|
+
__publicField(this, "expiringThresholdMs");
|
|
246
|
+
/** refreshToken 只存在于 httpOnly cookie */
|
|
247
|
+
__publicField(this, "cookieMode");
|
|
248
|
+
this.storage = options.storage ?? null;
|
|
249
|
+
this.refreshImpl = options.refresh;
|
|
250
|
+
this.cookieMode = options.cookieMode ?? false;
|
|
251
|
+
this.refreshTimeoutMs = options.refreshTimeoutMs ?? 1e4;
|
|
252
|
+
this.refreshCooldownMs = options.refreshCooldownMs ?? DEFAULT_REFRESH_COOLDOWN_MS;
|
|
253
|
+
this.proactiveCooldownMs = options.proactiveCooldownMs ?? DEFAULT_PROACTIVE_COOLDOWN_MS;
|
|
254
|
+
this.expiringThresholdMs = options.expiringThresholdMs ?? 6e4;
|
|
255
|
+
}
|
|
256
|
+
// ───────────────────────── 启动恢复 ─────────────────────────
|
|
257
|
+
/**
|
|
258
|
+
* 水合 + 安装副作用 + 按状态静默恢复。可重复调用。
|
|
259
|
+
* 不会抛出:存储 / 刷新失败都折算成 RestoreResult。
|
|
260
|
+
*
|
|
261
|
+
* `status` 只表示身份是否可用;刷新是否尝试/成功看 `refresh`,
|
|
262
|
+
* 判断能否访问受保护页面请用 `authenticated`(或 isAuthenticated())。
|
|
263
|
+
*/
|
|
264
|
+
async restore(options = {}) {
|
|
265
|
+
if (this.disposed) {
|
|
266
|
+
const tokenStatus2 = this.getStatus();
|
|
267
|
+
return {
|
|
268
|
+
status: tokenStatus2 === "anonymous" ? "anonymous" : this.isAuthenticated() ? "authenticated" : "expired",
|
|
269
|
+
tokenStatus: tokenStatus2,
|
|
270
|
+
refresh: "not-needed",
|
|
271
|
+
authenticated: this.isAuthenticated()
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
await this.hydrate();
|
|
276
|
+
} catch {
|
|
277
|
+
}
|
|
278
|
+
this.installSideEffects();
|
|
279
|
+
const tokenStatus = this.getStatus();
|
|
280
|
+
if (tokenStatus === "anonymous") {
|
|
281
|
+
if (!options.cookieProbe || !this.cookieMode) {
|
|
282
|
+
return {
|
|
283
|
+
status: "anonymous",
|
|
284
|
+
tokenStatus,
|
|
285
|
+
refresh: "not-needed",
|
|
286
|
+
authenticated: false
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
return this.restoreWithRefresh();
|
|
290
|
+
}
|
|
291
|
+
if (tokenStatus === "valid") {
|
|
292
|
+
return {
|
|
293
|
+
status: "authenticated",
|
|
294
|
+
tokenStatus,
|
|
295
|
+
refresh: "not-needed",
|
|
296
|
+
authenticated: true
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
return this.restoreWithRefresh();
|
|
300
|
+
}
|
|
301
|
+
/** 执行一次 bootstrap 刷新,并把结果拆成身份 + 刷新结果两个维度 */
|
|
302
|
+
async restoreWithRefresh() {
|
|
303
|
+
const unavailable = !this.refreshImpl ? "no-handler" : !this.cookieMode && !this.hasRefreshToken() ? "no-token" : null;
|
|
304
|
+
try {
|
|
305
|
+
await this.refresh("bootstrap");
|
|
306
|
+
const tokenStatus = this.getStatus();
|
|
307
|
+
const authenticated = this.isAuthenticated();
|
|
308
|
+
return {
|
|
309
|
+
// 刷新成功但后端给了已过期 token 时,身份仍然是不可用
|
|
310
|
+
status: tokenStatus === "anonymous" ? "anonymous" : authenticated ? "refreshed" : "expired",
|
|
311
|
+
tokenStatus,
|
|
312
|
+
refresh: "succeeded",
|
|
313
|
+
authenticated
|
|
314
|
+
};
|
|
315
|
+
} catch (error) {
|
|
316
|
+
const tokenStatus = this.getStatus();
|
|
317
|
+
const authenticated = this.isAuthenticated();
|
|
318
|
+
return {
|
|
319
|
+
// 刷新失败但 token 仍可用(如 expiring / unknown)→ 保持 authenticated
|
|
320
|
+
status: tokenStatus === "anonymous" ? "anonymous" : authenticated ? "authenticated" : "expired",
|
|
321
|
+
tokenStatus,
|
|
322
|
+
refresh: unavailable ?? "failed",
|
|
323
|
+
authenticated,
|
|
324
|
+
// 失败原因同样脱敏,避免业务记录 RestoreResult 时泄露认证头
|
|
325
|
+
error: sanitizeErrorForPayload(error)
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/** cookie 模式下按需探测会话;非 cookie 模式等价于 restore */
|
|
330
|
+
probe() {
|
|
331
|
+
return this.restore({ cookieProbe: true });
|
|
332
|
+
}
|
|
333
|
+
/** 从存储恢复;仅执行一次,失败后可重试 */
|
|
334
|
+
hydrate() {
|
|
335
|
+
if (this.hydrated) {
|
|
336
|
+
return Promise.resolve(
|
|
337
|
+
Boolean(this.state.accessToken || this.state.refreshToken)
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
if (!this.hydratePromise) {
|
|
341
|
+
this.hydratePromise = this.hydrateOnce().finally(() => {
|
|
342
|
+
this.hydratePromise = null;
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
return this.hydratePromise;
|
|
346
|
+
}
|
|
347
|
+
async hydrateOnce() {
|
|
348
|
+
const versionAtStart = this.state.version;
|
|
349
|
+
const raw = await Promise.resolve(this.storage?.read() ?? null);
|
|
350
|
+
if (this.disposed) return false;
|
|
351
|
+
this.hydrated = true;
|
|
352
|
+
const normalized = normalizeSnapshot(raw);
|
|
353
|
+
if (!normalized) return false;
|
|
354
|
+
const previous = this.getSnapshot();
|
|
355
|
+
if (previous.version > versionAtStart && (previous.accessToken || previous.refreshToken) && normalized.version < previous.version) {
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
this.state = {
|
|
359
|
+
...normalized,
|
|
360
|
+
// 旧版本快照可能没有 sessionId:水合时补发,后续请求才能绑定会话
|
|
361
|
+
sessionId: normalized.sessionId ?? createSessionId(),
|
|
362
|
+
version: Math.max(normalized.version, previous.version + 1)
|
|
363
|
+
};
|
|
364
|
+
this.expiredEmitted = false;
|
|
365
|
+
this.scheduleExpiration();
|
|
366
|
+
this.emit("hydrate", previous, "storage-restore");
|
|
367
|
+
return true;
|
|
368
|
+
}
|
|
369
|
+
installSideEffects() {
|
|
370
|
+
if (this.disposed || this.sideEffectsInstalled) return;
|
|
371
|
+
this.sideEffectsInstalled = true;
|
|
372
|
+
const unsubscribe = this.storage?.subscribe?.((snapshot) => {
|
|
373
|
+
this.hydrateFromExternal(snapshot);
|
|
374
|
+
});
|
|
375
|
+
if (unsubscribe) this.unsubscribers.push(unsubscribe);
|
|
376
|
+
this.scheduleExpiration();
|
|
377
|
+
}
|
|
378
|
+
/** 从其他 tab 注入状态;version 守卫防止旧数据回退 */
|
|
379
|
+
hydrateFromExternal(snapshot) {
|
|
380
|
+
if (snapshot === null) {
|
|
381
|
+
if (!this.state.accessToken && !this.state.refreshToken) return;
|
|
382
|
+
const previous2 = this.getSnapshot();
|
|
383
|
+
this.state = {
|
|
384
|
+
tokenType: this.state.tokenType ?? "Bearer",
|
|
385
|
+
version: this.nextVersion()
|
|
386
|
+
};
|
|
387
|
+
this.expiredEmitted = false;
|
|
388
|
+
this.scheduleExpiration();
|
|
389
|
+
this.emit("clear", previous2, "external-sync");
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
const normalized = normalizeSnapshot(snapshot);
|
|
393
|
+
if (!normalized || normalized.version <= this.state.version) return;
|
|
394
|
+
const previous = this.getSnapshot();
|
|
395
|
+
this.state = {
|
|
396
|
+
...normalized,
|
|
397
|
+
// 旧版本写出的快照可能没有 sessionId,本 tab 补发一个
|
|
398
|
+
sessionId: normalized.sessionId ?? createSessionId()
|
|
399
|
+
};
|
|
400
|
+
this.expiredEmitted = false;
|
|
401
|
+
this.resetCooldown();
|
|
402
|
+
this.scheduleExpiration();
|
|
403
|
+
const type = previous.accessToken ? "refresh" : "login";
|
|
404
|
+
this.emit(type, previous, "external-sync");
|
|
405
|
+
}
|
|
406
|
+
// ───────────────────────── 业务入口 ─────────────────────────
|
|
407
|
+
/** 登录成功:业务完成 token 适配后按契约交进来 */
|
|
408
|
+
login(tokens) {
|
|
409
|
+
return this.setTokens(tokens, { event: "login" });
|
|
410
|
+
}
|
|
411
|
+
/** 本地登出;是否调用退出接口由业务决定 */
|
|
412
|
+
logout(reason = "logout") {
|
|
413
|
+
this.clear(reason);
|
|
414
|
+
}
|
|
415
|
+
setTokens(tokens, options = {}) {
|
|
416
|
+
if (this.disposed) throw new Error("[session] disposed");
|
|
417
|
+
if (typeof tokens?.accessToken !== "string" || !tokens.accessToken) {
|
|
418
|
+
throw new Error("[session] accessToken is required");
|
|
419
|
+
}
|
|
420
|
+
const previous = this.getSnapshot();
|
|
421
|
+
const now = Date.now();
|
|
422
|
+
const rawExpiresAt = typeof tokens.expiresAt === "number" && Number.isFinite(tokens.expiresAt) ? tokens.expiresAt : void 0;
|
|
423
|
+
const rawExpiresIn = typeof tokens.expiresIn === "number" && Number.isFinite(tokens.expiresIn) ? tokens.expiresIn : void 0;
|
|
424
|
+
const expiresAt = rawExpiresAt ?? (rawExpiresIn !== void 0 ? Math.floor(now / 1e3) + rawExpiresIn : void 0);
|
|
425
|
+
const rawRefreshExpiresAt = typeof tokens.refreshExpiresAt === "number" && Number.isFinite(tokens.refreshExpiresAt) ? tokens.refreshExpiresAt : void 0;
|
|
426
|
+
const rawRefreshExpiresIn = typeof tokens.refreshExpiresIn === "number" && Number.isFinite(tokens.refreshExpiresIn) ? tokens.refreshExpiresIn : void 0;
|
|
427
|
+
let refreshExpiresAt = this.state.refreshExpiresAt;
|
|
428
|
+
if (rawRefreshExpiresAt !== void 0) {
|
|
429
|
+
refreshExpiresAt = rawRefreshExpiresAt;
|
|
430
|
+
} else if (rawRefreshExpiresIn !== void 0) {
|
|
431
|
+
refreshExpiresAt = Math.floor(now / 1e3) + rawRefreshExpiresIn;
|
|
432
|
+
} else if (tokens.refreshToken !== void 0) {
|
|
433
|
+
refreshExpiresAt = void 0;
|
|
434
|
+
}
|
|
435
|
+
const type = options.event ?? (previous.accessToken ? "refresh" : "login");
|
|
436
|
+
this.state = {
|
|
437
|
+
accessToken: tokens.accessToken,
|
|
438
|
+
// 显式传入空字符串表示「移除 refreshToken」,缺省则沿用旧值
|
|
439
|
+
refreshToken: tokens.refreshToken === void 0 ? this.state.refreshToken : tokens.refreshToken || void 0,
|
|
440
|
+
tokenType: typeof tokens.tokenType === "string" && tokens.tokenType || this.state.tokenType || "Bearer",
|
|
441
|
+
expiresAt,
|
|
442
|
+
refreshExpiresAt,
|
|
443
|
+
// 新的登录换会话标识;刷新沿用,避免把旧请求重放到新会话上
|
|
444
|
+
// cookieMode 可能从不调用 login:任何首次拿到 token 的写入都补发会话标识
|
|
445
|
+
sessionId: type === "login" || !this.state.sessionId ? createSessionId() : this.state.sessionId,
|
|
446
|
+
version: this.nextVersion()
|
|
447
|
+
};
|
|
448
|
+
this.expiredEmitted = false;
|
|
449
|
+
if (type === "login") this.resetCooldown();
|
|
450
|
+
this.persist();
|
|
451
|
+
this.scheduleExpiration();
|
|
452
|
+
this.emit(type, previous, options.reason);
|
|
453
|
+
return this.getSnapshot();
|
|
454
|
+
}
|
|
455
|
+
updateTokens(partial, reason) {
|
|
456
|
+
if (!this.state.accessToken) {
|
|
457
|
+
throw new Error("[session] updateTokens requires existing token");
|
|
458
|
+
}
|
|
459
|
+
const previous = this.state;
|
|
460
|
+
const accessToken = partial.accessToken ?? previous.accessToken;
|
|
461
|
+
if (!accessToken) {
|
|
462
|
+
throw new Error("[session] updateTokens requires existing token");
|
|
463
|
+
}
|
|
464
|
+
const expiresAt = partial.expiresAt ?? (partial.expiresIn === void 0 ? previous.expiresAt : void 0);
|
|
465
|
+
return this.setTokens(
|
|
466
|
+
{
|
|
467
|
+
accessToken,
|
|
468
|
+
// 只在显式传入时覆盖 refreshToken / 过期信息,避免局部更新把它清掉
|
|
469
|
+
refreshToken: partial.refreshToken,
|
|
470
|
+
refreshExpiresIn: partial.refreshExpiresIn,
|
|
471
|
+
refreshExpiresAt: partial.refreshExpiresAt,
|
|
472
|
+
tokenType: partial.tokenType ?? previous.tokenType,
|
|
473
|
+
expiresIn: partial.expiresIn,
|
|
474
|
+
expiresAt
|
|
475
|
+
},
|
|
476
|
+
{ event: "refresh", reason }
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
clear(reason = "logout") {
|
|
480
|
+
const previous = this.getSnapshot();
|
|
481
|
+
this.state = {
|
|
482
|
+
tokenType: this.state.tokenType ?? "Bearer",
|
|
483
|
+
version: this.nextVersion()
|
|
484
|
+
};
|
|
485
|
+
this.expiredEmitted = false;
|
|
486
|
+
this.persist(null);
|
|
487
|
+
this.cancelExpiration();
|
|
488
|
+
this.emit("clear", previous, reason);
|
|
489
|
+
}
|
|
490
|
+
markInvalid(reason = "invalid") {
|
|
491
|
+
this.emit("invalid", this.getSnapshot(), reason);
|
|
492
|
+
}
|
|
493
|
+
markExpired(reason = "expired") {
|
|
494
|
+
if (this.expiredEmitted) return;
|
|
495
|
+
this.expiredEmitted = true;
|
|
496
|
+
this.emit("expire", this.getSnapshot(), reason);
|
|
497
|
+
}
|
|
498
|
+
// ───────────────────────── 刷新 ─────────────────────────
|
|
499
|
+
/**
|
|
500
|
+
* 刷新 token。jwt 插件(proactive / unauthorized)、restore(bootstrap)
|
|
501
|
+
* 与调试面板共用。并发调用共享同一个 inflight。
|
|
502
|
+
*/
|
|
503
|
+
async refresh(reason = "proactive") {
|
|
504
|
+
if (this.disposed) {
|
|
505
|
+
throw refreshError("unknown", "[session] disposed");
|
|
506
|
+
}
|
|
507
|
+
if (this.inflight) {
|
|
508
|
+
this.inflightReasons?.add(reason);
|
|
509
|
+
return this.inflight;
|
|
510
|
+
}
|
|
511
|
+
if (reason !== "bootstrap" && this.isCoolingDown(reason)) {
|
|
512
|
+
throw refreshError("unknown", "\u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
|
|
513
|
+
}
|
|
514
|
+
const refreshImpl = this.refreshImpl;
|
|
515
|
+
if (!refreshImpl) {
|
|
516
|
+
throw refreshError("unknown", "\u672A\u914D\u7F6E\u5237\u65B0\u56DE\u8C03");
|
|
517
|
+
}
|
|
518
|
+
const refreshToken = this.cookieMode ? void 0 : this.state.refreshToken;
|
|
519
|
+
const versionBefore = this.state.version;
|
|
520
|
+
const reasons = /* @__PURE__ */ new Set([reason]);
|
|
521
|
+
this.inflightReasons = reasons;
|
|
522
|
+
const core = (async () => {
|
|
523
|
+
try {
|
|
524
|
+
if (!this.cookieMode && this.isRefreshTokenExpired()) {
|
|
525
|
+
throw refreshError("unknown", "\u767B\u5F55\u51ED\u8BC1\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55");
|
|
526
|
+
}
|
|
527
|
+
if (!refreshToken && !this.cookieMode) {
|
|
528
|
+
throw refreshError("unknown", "\u767B\u5F55\u72B6\u6001\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55");
|
|
529
|
+
}
|
|
530
|
+
const tokens = await this.withTimeout(
|
|
531
|
+
(signal) => refreshImpl(refreshToken, signal, reason)
|
|
532
|
+
);
|
|
533
|
+
if (this.state.version !== versionBefore) {
|
|
534
|
+
return this.getSnapshot();
|
|
535
|
+
}
|
|
536
|
+
const hasExpiry = typeof tokens.expiresAt === "number" && Number.isFinite(tokens.expiresAt) || typeof tokens.expiresIn === "number" && Number.isFinite(tokens.expiresIn);
|
|
537
|
+
const reusableExpiry = this.state.expiresAt !== void 0 && this.state.expiresAt * 1e3 > Date.now();
|
|
538
|
+
const nextTokens = !hasExpiry && reusableExpiry ? { ...tokens, expiresAt: this.state.expiresAt } : tokens;
|
|
539
|
+
const snapshot = this.setTokens(nextTokens, { event: "refresh" });
|
|
540
|
+
this.lastProactiveFailedAt = 0;
|
|
541
|
+
this.lastAuthFailedAt = 0;
|
|
542
|
+
return snapshot;
|
|
543
|
+
} catch (error) {
|
|
544
|
+
this.recordFailure(error, reasons);
|
|
545
|
+
throw error;
|
|
546
|
+
}
|
|
547
|
+
})();
|
|
548
|
+
const disposal = new Promise((_, reject) => {
|
|
549
|
+
this.rejectInflightOnDispose = reject;
|
|
550
|
+
});
|
|
551
|
+
this.inflight = Promise.race([core, disposal]);
|
|
552
|
+
try {
|
|
553
|
+
return await this.inflight;
|
|
554
|
+
} finally {
|
|
555
|
+
this.inflight = null;
|
|
556
|
+
this.inflightReasons = null;
|
|
557
|
+
this.refreshController = null;
|
|
558
|
+
this.refreshTimer = null;
|
|
559
|
+
this.rejectInflightOnDispose = null;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
isCoolingDown(reason = "proactive") {
|
|
563
|
+
const failedAt = reason === "proactive" ? this.lastProactiveFailedAt : this.lastAuthFailedAt;
|
|
564
|
+
const cooldownMs = reason === "proactive" ? this.proactiveCooldownMs : this.refreshCooldownMs;
|
|
565
|
+
return Date.now() - failedAt < cooldownMs;
|
|
566
|
+
}
|
|
567
|
+
resetCooldown() {
|
|
568
|
+
this.lastProactiveFailedAt = 0;
|
|
569
|
+
this.lastAuthFailedAt = 0;
|
|
570
|
+
}
|
|
571
|
+
recordFailure(error, reasons) {
|
|
572
|
+
if (this.disposed) return;
|
|
573
|
+
const now = Date.now();
|
|
574
|
+
if (reasons.has("proactive")) this.lastProactiveFailedAt = now;
|
|
575
|
+
if (reasons.has("unauthorized") || reasons.has("bootstrap")) {
|
|
576
|
+
this.lastAuthFailedAt = now;
|
|
577
|
+
}
|
|
578
|
+
const hasUnauthorized = reasons.has("unauthorized");
|
|
579
|
+
const sessionStillUsable = !hasUnauthorized && this.isAccessTokenValid();
|
|
580
|
+
const nothingToInvalidate = !this.hasAccessToken() && !this.hasRefreshToken();
|
|
581
|
+
const reasonLabel = [...reasons].join("+");
|
|
582
|
+
if (!sessionStillUsable && !nothingToInvalidate) {
|
|
583
|
+
this.markInvalid(`refresh failed: ${reasonLabel}`);
|
|
584
|
+
}
|
|
585
|
+
this.dispatch("refresh-failed", {
|
|
586
|
+
type: "refresh-failed",
|
|
587
|
+
snapshot: this.getSnapshot(),
|
|
588
|
+
previous: null,
|
|
589
|
+
// 并发刷新可能同时服务多个原因,例如 "proactive+unauthorized"
|
|
590
|
+
reason: reasonLabel,
|
|
591
|
+
error: sanitizeErrorForPayload(error)
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
withTimeout(run) {
|
|
595
|
+
const controller = new AbortController();
|
|
596
|
+
this.refreshController = controller;
|
|
597
|
+
const promise = run(controller.signal);
|
|
598
|
+
if (!this.refreshTimeoutMs) return promise;
|
|
599
|
+
return new Promise((resolve, reject) => {
|
|
600
|
+
const timer = setTimeout(() => {
|
|
601
|
+
this.refreshTimer = null;
|
|
602
|
+
controller.abort();
|
|
603
|
+
reject(refreshError("timeout", "\u5237\u65B0\u767B\u5F55\u72B6\u6001\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"));
|
|
604
|
+
}, this.refreshTimeoutMs);
|
|
605
|
+
this.refreshTimer = timer;
|
|
606
|
+
timer.unref?.();
|
|
607
|
+
promise.then(
|
|
608
|
+
(value) => {
|
|
609
|
+
clearTimeout(timer);
|
|
610
|
+
if (this.refreshTimer === timer) this.refreshTimer = null;
|
|
611
|
+
resolve(value);
|
|
612
|
+
},
|
|
613
|
+
(error) => {
|
|
614
|
+
clearTimeout(timer);
|
|
615
|
+
if (this.refreshTimer === timer) this.refreshTimer = null;
|
|
616
|
+
reject(error);
|
|
617
|
+
}
|
|
618
|
+
);
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
// ───────────────────────── 读取 ─────────────────────────
|
|
622
|
+
getAccessToken() {
|
|
623
|
+
return this.state.accessToken;
|
|
624
|
+
}
|
|
625
|
+
getRefreshToken() {
|
|
626
|
+
return this.state.refreshToken;
|
|
627
|
+
}
|
|
628
|
+
getTokenType() {
|
|
629
|
+
return this.state.tokenType;
|
|
630
|
+
}
|
|
631
|
+
getVersion() {
|
|
632
|
+
return this.state.version;
|
|
633
|
+
}
|
|
634
|
+
/** 当前登录会话标识;未登录时为 undefined */
|
|
635
|
+
getSessionId() {
|
|
636
|
+
return this.state.sessionId;
|
|
637
|
+
}
|
|
638
|
+
getSnapshot() {
|
|
639
|
+
return { ...this.state };
|
|
640
|
+
}
|
|
641
|
+
hasAccessToken() {
|
|
642
|
+
return Boolean(this.state.accessToken);
|
|
643
|
+
}
|
|
644
|
+
hasRefreshToken() {
|
|
645
|
+
return Boolean(this.state.refreshToken);
|
|
646
|
+
}
|
|
647
|
+
/** refreshToken 是否已过期;无 refreshToken 或无过期时间时返回 false */
|
|
648
|
+
isRefreshTokenExpired(now = Date.now()) {
|
|
649
|
+
return this.getRefreshTokenStatus(void 0, now) === "expired";
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* refreshToken 自身状态。cookie 模式下本地没有 refreshToken,返回 missing;
|
|
653
|
+
* 后端未下发 refresh 过期时间时返回 unknown。
|
|
654
|
+
*/
|
|
655
|
+
getRefreshTokenStatus(thresholdMs, now = Date.now()) {
|
|
656
|
+
const { refreshToken, refreshExpiresAt } = this.state;
|
|
657
|
+
if (!refreshToken) return "missing";
|
|
658
|
+
if (refreshExpiresAt === void 0) return "unknown";
|
|
659
|
+
const remain = refreshExpiresAt * 1e3 - now;
|
|
660
|
+
if (remain <= 0) return "expired";
|
|
661
|
+
if (remain <= (thresholdMs ?? this.expiringThresholdMs)) return "expiring";
|
|
662
|
+
return "valid";
|
|
663
|
+
}
|
|
664
|
+
isHydrated() {
|
|
665
|
+
return this.hydrated;
|
|
666
|
+
}
|
|
667
|
+
isAccessTokenValid() {
|
|
668
|
+
return this.hasAccessToken() && this.getStatus() !== "expired";
|
|
669
|
+
}
|
|
670
|
+
isExpiringSoon(thresholdMs) {
|
|
671
|
+
if (this.state.expiresAt === void 0 || !this.state.accessToken) {
|
|
672
|
+
return false;
|
|
673
|
+
}
|
|
674
|
+
const remain = this.state.expiresAt * 1e3 - Date.now();
|
|
675
|
+
return remain > 0 && remain <= (thresholdMs ?? this.expiringThresholdMs);
|
|
676
|
+
}
|
|
677
|
+
/** 路由守卫用;unknown 视为已登录(交给 401 兜底) */
|
|
678
|
+
isAuthenticated() {
|
|
679
|
+
const status = this.getStatus();
|
|
680
|
+
return status === "valid" || status === "expiring" || status === "unknown";
|
|
681
|
+
}
|
|
682
|
+
getStatus(thresholdMs) {
|
|
683
|
+
const snapshot = this.state;
|
|
684
|
+
if (!snapshot.accessToken) {
|
|
685
|
+
return snapshot.refreshToken ? "expired" : "anonymous";
|
|
686
|
+
}
|
|
687
|
+
if (snapshot.expiresAt === void 0) return "unknown";
|
|
688
|
+
const remain = snapshot.expiresAt * 1e3 - Date.now();
|
|
689
|
+
if (remain <= 0) return "expired";
|
|
690
|
+
if (remain <= (thresholdMs ?? this.expiringThresholdMs)) return "expiring";
|
|
691
|
+
return "valid";
|
|
692
|
+
}
|
|
693
|
+
// ───────────────────────── 事件 ─────────────────────────
|
|
694
|
+
on(type, listener) {
|
|
695
|
+
let set = this.listeners.get(type);
|
|
696
|
+
if (!set) {
|
|
697
|
+
set = /* @__PURE__ */ new Set();
|
|
698
|
+
this.listeners.set(type, set);
|
|
699
|
+
}
|
|
700
|
+
set.add(listener);
|
|
701
|
+
return () => this.off(type, listener);
|
|
702
|
+
}
|
|
703
|
+
off(type, listener) {
|
|
704
|
+
this.listeners.get(type)?.delete(listener);
|
|
705
|
+
}
|
|
706
|
+
// ───────────────────────── 生命周期 ─────────────────────────
|
|
707
|
+
/** 停止过期调度、注销存储订阅;在途刷新会被中止且不再写回存储 */
|
|
708
|
+
dispose() {
|
|
709
|
+
if (this.disposed) return;
|
|
710
|
+
this.disposed = true;
|
|
711
|
+
const rejectInflight = this.rejectInflightOnDispose;
|
|
712
|
+
this.rejectInflightOnDispose = null;
|
|
713
|
+
this.refreshController?.abort();
|
|
714
|
+
this.refreshController = null;
|
|
715
|
+
if (this.refreshTimer) {
|
|
716
|
+
clearTimeout(this.refreshTimer);
|
|
717
|
+
this.refreshTimer = null;
|
|
718
|
+
}
|
|
719
|
+
rejectInflight?.(refreshError("unknown", "[session] disposed"));
|
|
720
|
+
this.cancelExpiration();
|
|
721
|
+
for (const unsubscribe of this.unsubscribers.splice(0)) {
|
|
722
|
+
try {
|
|
723
|
+
unsubscribe();
|
|
724
|
+
} catch {
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
this.listeners.clear();
|
|
728
|
+
}
|
|
729
|
+
// ───────────────────────── 内部 ─────────────────────────
|
|
730
|
+
nextVersion() {
|
|
731
|
+
return Math.max(this.state.version + 1, Date.now());
|
|
732
|
+
}
|
|
733
|
+
persist(snapshot = this.state) {
|
|
734
|
+
if (this.disposed) return;
|
|
735
|
+
try {
|
|
736
|
+
const result = this.storage?.write(snapshot);
|
|
737
|
+
void Promise.resolve(result).catch(() => {
|
|
738
|
+
});
|
|
739
|
+
} catch {
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
emit(type, previous, reason) {
|
|
743
|
+
const payload = {
|
|
744
|
+
type,
|
|
745
|
+
snapshot: this.getSnapshot(),
|
|
746
|
+
previous,
|
|
747
|
+
reason
|
|
748
|
+
};
|
|
749
|
+
this.dispatch(type, payload);
|
|
750
|
+
if (type !== "change") {
|
|
751
|
+
this.dispatch("change", { ...payload, type: "change" });
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
dispatch(type, payload) {
|
|
755
|
+
const set = this.listeners.get(type);
|
|
756
|
+
if (!set) return;
|
|
757
|
+
for (const listener of set) {
|
|
758
|
+
try {
|
|
759
|
+
listener(payload);
|
|
760
|
+
} catch {
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
/** 按 expiresAt 精确调度一次过期事件;token 变化时重排 */
|
|
765
|
+
scheduleExpiration() {
|
|
766
|
+
if (this.disposed) return;
|
|
767
|
+
this.cancelExpiration();
|
|
768
|
+
const { accessToken, expiresAt } = this.state;
|
|
769
|
+
if (!accessToken || expiresAt === void 0) return;
|
|
770
|
+
const delay = expiresAt * 1e3 - Date.now();
|
|
771
|
+
this.expirationTimer = setTimeout(() => {
|
|
772
|
+
this.expirationTimer = null;
|
|
773
|
+
if (this.expiredEmitted) return;
|
|
774
|
+
if (Date.now() < expiresAt * 1e3) {
|
|
775
|
+
this.scheduleExpiration();
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
this.markExpired("access token expired");
|
|
779
|
+
}, Math.min(Math.max(delay, 0), MAX_TIMEOUT_MS));
|
|
780
|
+
this.expirationTimer.unref?.();
|
|
781
|
+
}
|
|
782
|
+
cancelExpiration() {
|
|
783
|
+
if (this.expirationTimer) {
|
|
784
|
+
clearTimeout(this.expirationTimer);
|
|
785
|
+
this.expirationTimer = null;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
|
|
790
|
+
// src/storage.ts
|
|
791
|
+
var jsonTokenSerializer = {
|
|
792
|
+
serialize: (value) => JSON.stringify(value),
|
|
793
|
+
deserialize: (raw) => JSON.parse(raw)
|
|
794
|
+
};
|
|
795
|
+
var DEFAULT_MAX_AGE_MS = 30 * 24 * 3600 * 1e3;
|
|
796
|
+
var FUTURE_SKEW_MS = 6e4;
|
|
797
|
+
function createSessionStorage(options = {}) {
|
|
798
|
+
const key = options.key ?? "app.auth";
|
|
799
|
+
const refreshKey = options.refreshKey ?? `${key}.rt`;
|
|
800
|
+
const refreshKeyDistinct = refreshKey !== key;
|
|
801
|
+
const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
|
|
802
|
+
const strategy = options.strategy ?? "same";
|
|
803
|
+
const serializer = options.serializer ?? jsonTokenSerializer;
|
|
804
|
+
const getStore = () => {
|
|
805
|
+
if (options.storage) return options.storage;
|
|
806
|
+
try {
|
|
807
|
+
return typeof localStorage !== "undefined" ? localStorage : null;
|
|
808
|
+
} catch {
|
|
809
|
+
return null;
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
const isFresh = (savedAt) => {
|
|
813
|
+
if (maxAgeMs <= 0) return true;
|
|
814
|
+
if (typeof savedAt !== "number" || !Number.isFinite(savedAt)) return false;
|
|
815
|
+
const now = Date.now();
|
|
816
|
+
if (savedAt > now + FUTURE_SKEW_MS) return false;
|
|
817
|
+
return now - savedAt <= maxAgeMs;
|
|
818
|
+
};
|
|
819
|
+
const parse = (raw) => {
|
|
820
|
+
if (!raw) return null;
|
|
821
|
+
try {
|
|
822
|
+
const parsed = serializer.deserialize(raw);
|
|
823
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
if (!isFresh(parsed._savedAt)) return null;
|
|
827
|
+
return parsed;
|
|
828
|
+
} catch {
|
|
829
|
+
return null;
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
const encode = (value) => serializer.serialize(value);
|
|
833
|
+
const toSnapshot = (persisted) => {
|
|
834
|
+
const snapshot = { ...persisted };
|
|
835
|
+
delete snapshot._savedAt;
|
|
836
|
+
return snapshot;
|
|
837
|
+
};
|
|
838
|
+
const withSeparateToken = (main, store) => {
|
|
839
|
+
if (strategy !== "separate") return main;
|
|
840
|
+
const rt = parse(store.getItem(refreshKey));
|
|
841
|
+
if (rt?.refreshToken) {
|
|
842
|
+
main.refreshToken = rt.refreshToken;
|
|
843
|
+
main.refreshExpiresAt = rt.refreshExpiresAt;
|
|
844
|
+
}
|
|
845
|
+
return main;
|
|
846
|
+
};
|
|
847
|
+
const readFrom = (store) => {
|
|
848
|
+
const main = parse(store.getItem(key));
|
|
849
|
+
if (!main) {
|
|
850
|
+
if (strategy !== "separate") return null;
|
|
851
|
+
const orphanRt = parse(store.getItem(refreshKey));
|
|
852
|
+
if (!orphanRt?.refreshToken) return null;
|
|
853
|
+
return {
|
|
854
|
+
refreshToken: orphanRt.refreshToken,
|
|
855
|
+
refreshExpiresAt: orphanRt.refreshExpiresAt,
|
|
856
|
+
tokenType: "Bearer",
|
|
857
|
+
version: 0
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
return toSnapshot(withSeparateToken(main, store));
|
|
861
|
+
};
|
|
862
|
+
return {
|
|
863
|
+
read() {
|
|
864
|
+
const store = getStore();
|
|
865
|
+
if (!store) return null;
|
|
866
|
+
try {
|
|
867
|
+
return readFrom(store);
|
|
868
|
+
} catch {
|
|
869
|
+
return null;
|
|
870
|
+
}
|
|
871
|
+
},
|
|
872
|
+
write(snapshot) {
|
|
873
|
+
const store = getStore();
|
|
874
|
+
if (!store) return;
|
|
875
|
+
try {
|
|
876
|
+
if (!snapshot) {
|
|
877
|
+
store.removeItem(key);
|
|
878
|
+
if (refreshKeyDistinct) store.removeItem(refreshKey);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
const savedAt = Date.now();
|
|
882
|
+
if (strategy !== "separate" || !refreshKeyDistinct) {
|
|
883
|
+
const payload = { ...snapshot };
|
|
884
|
+
if (strategy === "omit") {
|
|
885
|
+
delete payload.refreshToken;
|
|
886
|
+
delete payload.refreshExpiresAt;
|
|
887
|
+
}
|
|
888
|
+
store.setItem(key, encode({ ...payload, _savedAt: savedAt }));
|
|
889
|
+
if (refreshKeyDistinct) store.removeItem(refreshKey);
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
const { refreshToken, refreshExpiresAt, ...rest } = snapshot;
|
|
893
|
+
store.setItem(key, encode({ ...rest, _savedAt: savedAt }));
|
|
894
|
+
if (refreshToken) {
|
|
895
|
+
store.setItem(
|
|
896
|
+
refreshKey,
|
|
897
|
+
encode({ refreshToken, refreshExpiresAt, _savedAt: savedAt })
|
|
898
|
+
);
|
|
899
|
+
} else {
|
|
900
|
+
store.removeItem(refreshKey);
|
|
901
|
+
}
|
|
902
|
+
} catch {
|
|
903
|
+
}
|
|
904
|
+
},
|
|
905
|
+
subscribe(listener) {
|
|
906
|
+
if (typeof window === "undefined") return () => {
|
|
907
|
+
};
|
|
908
|
+
const handler = (event) => {
|
|
909
|
+
if (event.key !== null && event.key !== key && event.key !== refreshKey) {
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
const store = getStore();
|
|
913
|
+
if (event.storageArea && store && event.storageArea !== store) return;
|
|
914
|
+
try {
|
|
915
|
+
if (!store) {
|
|
916
|
+
listener(null);
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
listener(readFrom(store));
|
|
920
|
+
} catch {
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
window.addEventListener("storage", handler);
|
|
924
|
+
return () => window.removeEventListener("storage", handler);
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// src/request-origin.ts
|
|
930
|
+
var ABSOLUTE_URL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
|
|
931
|
+
var NETWORK_PATH = /^[\\/]{2}/;
|
|
932
|
+
var SCHEME = /^[a-z][a-z\d+\-.]*:/i;
|
|
933
|
+
function normalizeUrl(value) {
|
|
934
|
+
if (typeof value !== "string") return void 0;
|
|
935
|
+
return value.replace(/[\u0000-\u001F\u007F]/g, "").trim();
|
|
936
|
+
}
|
|
937
|
+
function parseUrl(url, base) {
|
|
938
|
+
try {
|
|
939
|
+
return base ? new URL(url, base) : new URL(url);
|
|
940
|
+
} catch {
|
|
941
|
+
return null;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
function originOf(url, base) {
|
|
945
|
+
const parsed = parseUrl(url, base);
|
|
946
|
+
return parsed && parsed.origin !== "null" ? parsed.origin : void 0;
|
|
947
|
+
}
|
|
948
|
+
function currentOrigin() {
|
|
949
|
+
try {
|
|
950
|
+
return typeof location !== "undefined" && location.origin ? location.origin : void 0;
|
|
951
|
+
} catch {
|
|
952
|
+
return void 0;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
function referenceOrigin(baseURL) {
|
|
956
|
+
const base = normalizeUrl(baseURL);
|
|
957
|
+
const current = currentOrigin();
|
|
958
|
+
if (!base) return current;
|
|
959
|
+
if (!ABSOLUTE_URL.test(base) && !NETWORK_PATH.test(base)) return current;
|
|
960
|
+
return originOf(base, current);
|
|
961
|
+
}
|
|
962
|
+
function isSameOriginRequest(config) {
|
|
963
|
+
const url = normalizeUrl(config.url);
|
|
964
|
+
if (!url) return true;
|
|
965
|
+
const networkPath = NETWORK_PATH.test(url);
|
|
966
|
+
const hasScheme = SCHEME.test(url);
|
|
967
|
+
if (!networkPath && !hasScheme) return true;
|
|
968
|
+
const axiosAbsolute = ABSOLUTE_URL.test(url);
|
|
969
|
+
const reference = referenceOrigin(config.baseURL);
|
|
970
|
+
if (hasScheme && !axiosAbsolute && !networkPath) {
|
|
971
|
+
const standalone = originOf(url);
|
|
972
|
+
if (standalone === void 0) {
|
|
973
|
+
return true;
|
|
974
|
+
}
|
|
975
|
+
if (!reference) return false;
|
|
976
|
+
if (standalone !== reference) return false;
|
|
977
|
+
return originOf(url, reference) === reference;
|
|
978
|
+
}
|
|
979
|
+
if (!reference) return false;
|
|
980
|
+
const target = originOf(url, reference);
|
|
981
|
+
return target !== void 0 && target === reference;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// src/plugins/api-key.ts
|
|
985
|
+
function createApiKeyInterceptor(options, allowCrossOriginAuth = false) {
|
|
986
|
+
const {
|
|
987
|
+
getApiKey,
|
|
988
|
+
transport = "header",
|
|
989
|
+
headerName = "X-Api-Key",
|
|
990
|
+
authorizationScheme = ""
|
|
991
|
+
} = options;
|
|
992
|
+
return async (config) => {
|
|
993
|
+
if (config.skipApiKey) return config;
|
|
994
|
+
if (!allowCrossOriginAuth && !isSameOriginRequest(config)) return config;
|
|
995
|
+
const key = await getApiKey();
|
|
996
|
+
if (!key) return config;
|
|
997
|
+
if (transport === "authorization") {
|
|
998
|
+
config.headers.set(
|
|
999
|
+
"Authorization",
|
|
1000
|
+
authorizationScheme ? `${authorizationScheme} ${key}` : key
|
|
1001
|
+
);
|
|
1002
|
+
} else {
|
|
1003
|
+
config.headers.set(headerName, key);
|
|
1004
|
+
}
|
|
1005
|
+
return config;
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// src/plugins/unwrap.ts
|
|
1010
|
+
var DEFAULT_KEYS = {
|
|
1011
|
+
code: ["code", "CODE"],
|
|
1012
|
+
message: ["message", "msg", "MSG"],
|
|
1013
|
+
data: ["data", "DATA"]
|
|
1014
|
+
};
|
|
1015
|
+
function toKeys(keys, fallback) {
|
|
1016
|
+
if (keys === void 0) return fallback;
|
|
1017
|
+
return typeof keys === "string" ? [keys] : keys;
|
|
1018
|
+
}
|
|
1019
|
+
function readField(body, keys, options = {}) {
|
|
1020
|
+
for (const key of keys) {
|
|
1021
|
+
if (!Object.prototype.hasOwnProperty.call(body, key)) continue;
|
|
1022
|
+
const value = body[key];
|
|
1023
|
+
if (value === void 0) continue;
|
|
1024
|
+
if (options.skipNull && value === null) continue;
|
|
1025
|
+
return value;
|
|
1026
|
+
}
|
|
1027
|
+
return void 0;
|
|
1028
|
+
}
|
|
1029
|
+
function isResponseCode(value) {
|
|
1030
|
+
return typeof value === "number" || typeof value === "string";
|
|
1031
|
+
}
|
|
1032
|
+
function defaultIsSuccess(code) {
|
|
1033
|
+
return code === 0 || code === "0" || code === 200 || code === "200";
|
|
1034
|
+
}
|
|
1035
|
+
function isNonJsonPayload(data) {
|
|
1036
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) return true;
|
|
1037
|
+
if (typeof ArrayBuffer !== "undefined") {
|
|
1038
|
+
if (data instanceof ArrayBuffer) return true;
|
|
1039
|
+
if (ArrayBuffer.isView(data)) return true;
|
|
1040
|
+
}
|
|
1041
|
+
if (typeof ReadableStream !== "undefined" && data instanceof ReadableStream) {
|
|
1042
|
+
return true;
|
|
1043
|
+
}
|
|
1044
|
+
return false;
|
|
1045
|
+
}
|
|
1046
|
+
function decodeEnvelope(body, fields) {
|
|
1047
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
1048
|
+
return null;
|
|
1049
|
+
}
|
|
1050
|
+
const record = body;
|
|
1051
|
+
const code = readField(record, toKeys(fields.code, DEFAULT_KEYS.code), {
|
|
1052
|
+
skipNull: true
|
|
1053
|
+
});
|
|
1054
|
+
if (!isResponseCode(code)) return null;
|
|
1055
|
+
const message = readField(
|
|
1056
|
+
record,
|
|
1057
|
+
toKeys(fields.message, DEFAULT_KEYS.message),
|
|
1058
|
+
{ skipNull: true }
|
|
1059
|
+
);
|
|
1060
|
+
return {
|
|
1061
|
+
code,
|
|
1062
|
+
message: typeof message === "string" ? message : void 0,
|
|
1063
|
+
data: readField(record, toKeys(fields.data, DEFAULT_KEYS.data))
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
function createUnwrapInterceptor(options = {}) {
|
|
1067
|
+
const isSuccess = options.isSuccess ?? defaultIsSuccess;
|
|
1068
|
+
const fields = options.fields ?? {};
|
|
1069
|
+
const adapter = options.adapter;
|
|
1070
|
+
const unwrapped = /* @__PURE__ */ new WeakSet();
|
|
1071
|
+
return (response) => {
|
|
1072
|
+
const responseType = response.config.responseType;
|
|
1073
|
+
const binaryResponse = responseType === "blob" || responseType === "arraybuffer" || responseType === "stream" || isNonJsonPayload(response.data);
|
|
1074
|
+
if (binaryResponse || response.config.skipUnwrap || unwrapped.has(response)) {
|
|
1075
|
+
return response;
|
|
1076
|
+
}
|
|
1077
|
+
const envelope = adapter ? adapter(response.data) : decodeEnvelope(response.data, fields);
|
|
1078
|
+
if (envelope === null) {
|
|
1079
|
+
unwrapped.add(response);
|
|
1080
|
+
return response;
|
|
1081
|
+
}
|
|
1082
|
+
if (!isResponseCode(envelope.code)) {
|
|
1083
|
+
throw new Error(
|
|
1084
|
+
"[response-unwrap] \u9002\u914D\u51FD\u6570\u8FD4\u56DE\u7684 code \u5FC5\u987B\u662F\u6570\u5B57\u6216\u5B57\u7B26\u4E32"
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
if (!isSuccess(envelope.code)) {
|
|
1088
|
+
const message = typeof envelope.message === "string" && envelope.message.trim() ? envelope.message : "\u4E1A\u52A1\u5904\u7406\u5931\u8D25";
|
|
1089
|
+
const error = new Error(message);
|
|
1090
|
+
Object.assign(error, {
|
|
1091
|
+
__business__: true,
|
|
1092
|
+
code: envelope.code,
|
|
1093
|
+
raw: response.data
|
|
1094
|
+
});
|
|
1095
|
+
Object.defineProperty(error, "config", {
|
|
1096
|
+
value: response.config,
|
|
1097
|
+
enumerable: false
|
|
1098
|
+
});
|
|
1099
|
+
throw error;
|
|
1100
|
+
}
|
|
1101
|
+
response.data = envelope.data;
|
|
1102
|
+
Object.defineProperty(response, "envelope", {
|
|
1103
|
+
value: { code: envelope.code, message: envelope.message },
|
|
1104
|
+
enumerable: false,
|
|
1105
|
+
configurable: true
|
|
1106
|
+
});
|
|
1107
|
+
unwrapped.add(response);
|
|
1108
|
+
return response;
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// src/plugins/jwt.ts
|
|
1113
|
+
var DEFAULT_STATUSES = [401];
|
|
1114
|
+
var DEFAULT_CODES = [401];
|
|
1115
|
+
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
|
|
1116
|
+
"get",
|
|
1117
|
+
"head",
|
|
1118
|
+
"options"
|
|
1119
|
+
]);
|
|
1120
|
+
function isReplayableData(data) {
|
|
1121
|
+
if (data === void 0 || data === null) return true;
|
|
1122
|
+
if (typeof ReadableStream !== "undefined" && data instanceof ReadableStream) {
|
|
1123
|
+
return false;
|
|
1124
|
+
}
|
|
1125
|
+
const nodeStream = data;
|
|
1126
|
+
return !(typeof nodeStream.pipe === "function" && typeof nodeStream.read === "function");
|
|
1127
|
+
}
|
|
1128
|
+
function isBusinessFailure(error) {
|
|
1129
|
+
return error !== null && typeof error === "object" && error.__business__ === true;
|
|
1130
|
+
}
|
|
1131
|
+
function readBusinessCode(error) {
|
|
1132
|
+
if (!isBusinessFailure(error)) return void 0;
|
|
1133
|
+
return isResponseCode(error.code) ? error.code : void 0;
|
|
1134
|
+
}
|
|
1135
|
+
function toFailureContext(error, config) {
|
|
1136
|
+
const business = isBusinessFailure(error);
|
|
1137
|
+
const axiosError = error;
|
|
1138
|
+
return {
|
|
1139
|
+
status: axiosError.response?.status,
|
|
1140
|
+
code: business ? readBusinessCode(error) : void 0,
|
|
1141
|
+
message: error instanceof Error && error.message ? error.message : "\u8BF7\u6C42\u5931\u8D25",
|
|
1142
|
+
data: business ? error.raw : axiosError.response?.data,
|
|
1143
|
+
config
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
function defaultRefreshWhen(failure) {
|
|
1147
|
+
const matches = (value, candidates) => value !== void 0 && candidates.some((candidate) => String(candidate) === String(value));
|
|
1148
|
+
return matches(failure.status, DEFAULT_STATUSES) || matches(failure.code, DEFAULT_CODES);
|
|
1149
|
+
}
|
|
1150
|
+
function createJwtRequestInterceptor(session, refreshBeforeExpirationMs = 6e4, allowCrossOriginAuth = false) {
|
|
1151
|
+
return async (config) => {
|
|
1152
|
+
if (config.skipAuth) return config;
|
|
1153
|
+
if (!allowCrossOriginAuth && !isSameOriginRequest(config)) return config;
|
|
1154
|
+
let token = session.getAccessToken();
|
|
1155
|
+
if (token && session.isExpiringSoon(refreshBeforeExpirationMs) && !session.isCoolingDown("proactive")) {
|
|
1156
|
+
try {
|
|
1157
|
+
token = (await session.refresh("proactive")).accessToken;
|
|
1158
|
+
} catch {
|
|
1159
|
+
token = session.getAccessToken();
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
if (token) {
|
|
1163
|
+
config.headers.set(
|
|
1164
|
+
"Authorization",
|
|
1165
|
+
`${session.getTokenType()} ${token}`
|
|
1166
|
+
);
|
|
1167
|
+
}
|
|
1168
|
+
config._tokenVersion = session.getVersion();
|
|
1169
|
+
config._sessionId = session.getSessionId();
|
|
1170
|
+
config._authedAtSend = Boolean(config.headers.get("Authorization"));
|
|
1171
|
+
return config;
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
function createJwtResponseInterceptor(instance, session, options = {}) {
|
|
1175
|
+
const refreshWhen = options.refreshWhen ?? defaultRefreshWhen;
|
|
1176
|
+
return async (rawError) => {
|
|
1177
|
+
const error = rawError;
|
|
1178
|
+
const config = error.config;
|
|
1179
|
+
if (!config || config.skipAuth || config.skipRefresh || config._retry) {
|
|
1180
|
+
return Promise.reject(rawError);
|
|
1181
|
+
}
|
|
1182
|
+
if (!(options.allowCrossOriginAuth ?? false) && !isSameOriginRequest(config)) {
|
|
1183
|
+
return Promise.reject(rawError);
|
|
1184
|
+
}
|
|
1185
|
+
if (!isBusinessFailure(rawError) && !error.response) {
|
|
1186
|
+
return Promise.reject(rawError);
|
|
1187
|
+
}
|
|
1188
|
+
const context = toFailureContext(rawError, config);
|
|
1189
|
+
let shouldRefresh = false;
|
|
1190
|
+
try {
|
|
1191
|
+
shouldRefresh = await refreshWhen(context);
|
|
1192
|
+
} catch {
|
|
1193
|
+
shouldRefresh = false;
|
|
1194
|
+
}
|
|
1195
|
+
if (!shouldRefresh) return Promise.reject(rawError);
|
|
1196
|
+
config._retry = true;
|
|
1197
|
+
const method = (config.method ?? "get").toLowerCase();
|
|
1198
|
+
const canReplay = IDEMPOTENT_METHODS.has(method) || (config.retryUnauthorized ?? options.retryOnUnauthorized ?? false);
|
|
1199
|
+
const bodyReplayable = isReplayableData(config.data) && !config.signal?.aborted;
|
|
1200
|
+
const sameSession = () => {
|
|
1201
|
+
if (config._sessionId !== void 0) {
|
|
1202
|
+
return session.getSessionId() === config._sessionId;
|
|
1203
|
+
}
|
|
1204
|
+
return !config._authedAtSend;
|
|
1205
|
+
};
|
|
1206
|
+
if (config._tokenVersion !== void 0 && config._tokenVersion !== session.getVersion()) {
|
|
1207
|
+
if (!canReplay) return Promise.reject(rawError);
|
|
1208
|
+
const latest = session.getAccessToken();
|
|
1209
|
+
if (!latest || !sameSession() || !bodyReplayable) {
|
|
1210
|
+
return Promise.reject(rawError);
|
|
1211
|
+
}
|
|
1212
|
+
config.headers.set(
|
|
1213
|
+
"Authorization",
|
|
1214
|
+
`${session.getTokenType()} ${latest}`
|
|
1215
|
+
);
|
|
1216
|
+
return instance(config);
|
|
1217
|
+
}
|
|
1218
|
+
if (!canReplay) {
|
|
1219
|
+
if (!isBusinessFailure(rawError) || options.refreshWhen !== void 0) {
|
|
1220
|
+
try {
|
|
1221
|
+
await session.refresh("unauthorized");
|
|
1222
|
+
} catch {
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
return Promise.reject(rawError);
|
|
1226
|
+
}
|
|
1227
|
+
try {
|
|
1228
|
+
const snapshot = await session.refresh("unauthorized");
|
|
1229
|
+
if (!snapshot.accessToken) return Promise.reject(rawError);
|
|
1230
|
+
if (!sameSession() || !bodyReplayable) return Promise.reject(rawError);
|
|
1231
|
+
config.headers.set(
|
|
1232
|
+
"Authorization",
|
|
1233
|
+
`${snapshot.tokenType} ${snapshot.accessToken}`
|
|
1234
|
+
);
|
|
1235
|
+
return instance(config);
|
|
1236
|
+
} catch {
|
|
1237
|
+
return Promise.reject(rawError);
|
|
1238
|
+
}
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
// src/plugins/logger.ts
|
|
1243
|
+
var KINDS2 = /* @__PURE__ */ new Set([
|
|
1244
|
+
"network",
|
|
1245
|
+
"timeout",
|
|
1246
|
+
"http",
|
|
1247
|
+
"business",
|
|
1248
|
+
"canceled",
|
|
1249
|
+
"unknown"
|
|
1250
|
+
]);
|
|
1251
|
+
function toKind(value) {
|
|
1252
|
+
return typeof value === "string" && KINDS2.has(value) ? value : "unknown";
|
|
1253
|
+
}
|
|
1254
|
+
function toNumberOrNull(value) {
|
|
1255
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
1256
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
1257
|
+
const parsed = Number(value);
|
|
1258
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1259
|
+
}
|
|
1260
|
+
return null;
|
|
1261
|
+
}
|
|
1262
|
+
function requestPath(config) {
|
|
1263
|
+
const url = config?.url ?? "";
|
|
1264
|
+
const index = url.search(/[?#]/);
|
|
1265
|
+
return index === -1 ? url : url.slice(0, index);
|
|
1266
|
+
}
|
|
1267
|
+
function requestMethod(config) {
|
|
1268
|
+
return (config?.method ?? "").toUpperCase();
|
|
1269
|
+
}
|
|
1270
|
+
function requestLabel(config) {
|
|
1271
|
+
return `${requestMethod(config) || "GET"} ${requestPath(config)}`;
|
|
1272
|
+
}
|
|
1273
|
+
function requestContext(config) {
|
|
1274
|
+
return {
|
|
1275
|
+
apiPath: requestPath(config),
|
|
1276
|
+
apiMethod: requestMethod(config),
|
|
1277
|
+
baseURL: config?.baseURL ?? ""
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
function createLoggerInterceptors(console) {
|
|
1281
|
+
const startedAt = /* @__PURE__ */ new WeakMap();
|
|
1282
|
+
const elapsed = (config) => {
|
|
1283
|
+
const start = startedAt.get(config);
|
|
1284
|
+
return start === void 0 ? null : Date.now() - start;
|
|
1285
|
+
};
|
|
1286
|
+
const safeLog = (run) => {
|
|
1287
|
+
try {
|
|
1288
|
+
run();
|
|
1289
|
+
} catch {
|
|
1290
|
+
}
|
|
1291
|
+
};
|
|
1292
|
+
return {
|
|
1293
|
+
request: {
|
|
1294
|
+
onFulfilled: (config) => {
|
|
1295
|
+
startedAt.set(config, Date.now());
|
|
1296
|
+
safeLog(
|
|
1297
|
+
() => console.info(`\u2192 ${requestLabel(config)}`, {
|
|
1298
|
+
...requestContext(config),
|
|
1299
|
+
apiStatus: null,
|
|
1300
|
+
apiCode: null,
|
|
1301
|
+
apiMsg: "",
|
|
1302
|
+
durationMs: null,
|
|
1303
|
+
// 字符串 / URLSearchParams 等非普通对象不拆键,避免把字符下标写进日志
|
|
1304
|
+
paramKeys: config.params && typeof config.params === "object" ? Object.keys(config.params) : [],
|
|
1305
|
+
skipAuth: config.skipAuth === true,
|
|
1306
|
+
timeout: config.timeout ?? null
|
|
1307
|
+
})
|
|
1308
|
+
);
|
|
1309
|
+
return config;
|
|
1310
|
+
}
|
|
1311
|
+
},
|
|
1312
|
+
response: {
|
|
1313
|
+
onFulfilled: (response) => {
|
|
1314
|
+
safeLog(
|
|
1315
|
+
() => console.info(`\u2190 ${response.status} ${requestLabel(response.config)}`, {
|
|
1316
|
+
...requestContext(response.config),
|
|
1317
|
+
apiStatus: toNumberOrNull(response.status),
|
|
1318
|
+
apiCode: null,
|
|
1319
|
+
apiMsg: response.statusText || "",
|
|
1320
|
+
durationMs: elapsed(response.config),
|
|
1321
|
+
hasData: response.data !== void 0 && response.data !== null
|
|
1322
|
+
})
|
|
1323
|
+
);
|
|
1324
|
+
return response;
|
|
1325
|
+
},
|
|
1326
|
+
onRejected: (error) => {
|
|
1327
|
+
const normalized = error;
|
|
1328
|
+
const config = normalized.config ?? normalized.raw?.config;
|
|
1329
|
+
const label = config ? requestLabel(config) : "request";
|
|
1330
|
+
const kind = toKind(normalized.kind);
|
|
1331
|
+
const data = {
|
|
1332
|
+
...requestContext(config),
|
|
1333
|
+
apiStatus: toNumberOrNull(normalized.status),
|
|
1334
|
+
apiCode: toNumberOrNull(normalized.code),
|
|
1335
|
+
apiMsg: normalized.message ?? "",
|
|
1336
|
+
durationMs: config ? elapsed(config) : null,
|
|
1337
|
+
kind
|
|
1338
|
+
};
|
|
1339
|
+
if (kind === "canceled") {
|
|
1340
|
+
safeLog(() => console.debug(`\u2715 ${label} canceled`, data));
|
|
1341
|
+
} else {
|
|
1342
|
+
safeLog(() => console.warn(`\u2715 ${label}`, data));
|
|
1343
|
+
}
|
|
1344
|
+
return Promise.reject(error);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
// src/client.ts
|
|
1351
|
+
function toRequestSpecs(interceptor) {
|
|
1352
|
+
if (!interceptor) return [];
|
|
1353
|
+
const list = Array.isArray(interceptor) ? interceptor : [interceptor];
|
|
1354
|
+
return list.map(
|
|
1355
|
+
(item) => typeof item === "function" ? { onFulfilled: item } : item
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
1358
|
+
function toResponseSpecs(interceptor) {
|
|
1359
|
+
if (!interceptor) return [];
|
|
1360
|
+
const list = Array.isArray(interceptor) ? interceptor : [interceptor];
|
|
1361
|
+
return list.map(
|
|
1362
|
+
(item) => typeof item === "function" ? { onFulfilled: item } : item
|
|
1363
|
+
);
|
|
1364
|
+
}
|
|
1365
|
+
function childLogger(logger, scope) {
|
|
1366
|
+
if (!logger) return void 0;
|
|
1367
|
+
return logger.child ? logger.child(scope) : logger;
|
|
1368
|
+
}
|
|
1369
|
+
function createHttp(options) {
|
|
1370
|
+
const storageOptions = options.storage === false ? null : options.storage ?? {};
|
|
1371
|
+
const strategy = storageOptions?.strategy ?? "same";
|
|
1372
|
+
const cookieMode = options.cookieMode ?? (storageOptions !== null && strategy === "omit");
|
|
1373
|
+
const withCredentials = options.withCredentials ?? cookieMode;
|
|
1374
|
+
if (!options.instance && !options.baseURL) {
|
|
1375
|
+
throw new Error("[createHttp] \u672A\u63D0\u4F9B instance \u65F6\u5FC5\u987B\u4F20 baseURL");
|
|
1376
|
+
}
|
|
1377
|
+
if (options.apiKey?.transport === "authorization" && options.jwt !== false) {
|
|
1378
|
+
throw new Error(
|
|
1379
|
+
'[createHttp] apiKey.transport="authorization" \u4EC5\u5728 jwt: false \u65F6\u53EF\u7528'
|
|
1380
|
+
);
|
|
1381
|
+
}
|
|
1382
|
+
const baseURL = options.baseURL ?? options.instance?.defaults.baseURL;
|
|
1383
|
+
const timeout = options.timeout ?? options.instance?.defaults.timeout ?? 15e3;
|
|
1384
|
+
const adapter = options.adapter ?? options.instance?.defaults.adapter;
|
|
1385
|
+
const storage = storageOptions ? createSessionStorage({ ...storageOptions, strategy }) : null;
|
|
1386
|
+
const refreshHttp = options.refreshInstance ?? axios.create({
|
|
1387
|
+
baseURL,
|
|
1388
|
+
timeout,
|
|
1389
|
+
withCredentials,
|
|
1390
|
+
...adapter ? { adapter } : {}
|
|
1391
|
+
});
|
|
1392
|
+
const refreshRequestIds = [];
|
|
1393
|
+
const refreshResponseIds = [];
|
|
1394
|
+
const unwrapInterceptor = createUnwrapInterceptor(options.unwrap);
|
|
1395
|
+
refreshResponseIds.push(
|
|
1396
|
+
refreshHttp.interceptors.response.use(unwrapInterceptor)
|
|
1397
|
+
);
|
|
1398
|
+
refreshResponseIds.push(
|
|
1399
|
+
refreshHttp.interceptors.response.use(void 0, createErrorNormalizer())
|
|
1400
|
+
);
|
|
1401
|
+
const refreshLogger = childLogger(options.logger, "refresh");
|
|
1402
|
+
if (refreshLogger) {
|
|
1403
|
+
const loggerInterceptors2 = createLoggerInterceptors(refreshLogger);
|
|
1404
|
+
refreshRequestIds.push(
|
|
1405
|
+
refreshHttp.interceptors.request.use(
|
|
1406
|
+
loggerInterceptors2.request.onFulfilled,
|
|
1407
|
+
loggerInterceptors2.request.onRejected
|
|
1408
|
+
)
|
|
1409
|
+
);
|
|
1410
|
+
refreshResponseIds.push(
|
|
1411
|
+
refreshHttp.interceptors.response.use(
|
|
1412
|
+
loggerInterceptors2.response.onFulfilled,
|
|
1413
|
+
loggerInterceptors2.response.onRejected
|
|
1414
|
+
)
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
1417
|
+
const refresh = options.refresh;
|
|
1418
|
+
const session = new Session({
|
|
1419
|
+
storage,
|
|
1420
|
+
cookieMode,
|
|
1421
|
+
refreshTimeoutMs: options.refreshTimeoutMs,
|
|
1422
|
+
refreshCooldownMs: options.refreshCooldownMs,
|
|
1423
|
+
proactiveCooldownMs: options.proactiveCooldownMs,
|
|
1424
|
+
refresh: refresh ? (refreshToken, signal, reason) => refresh({ http: refreshHttp, refreshToken, signal, reason }) : void 0
|
|
1425
|
+
});
|
|
1426
|
+
const http = options.instance ?? axios.create({
|
|
1427
|
+
baseURL,
|
|
1428
|
+
timeout,
|
|
1429
|
+
withCredentials,
|
|
1430
|
+
...options.headers ? { headers: options.headers } : {},
|
|
1431
|
+
...adapter ? { adapter } : {}
|
|
1432
|
+
});
|
|
1433
|
+
if (options.instance) {
|
|
1434
|
+
if (options.adapter) options.instance.defaults.adapter = options.adapter;
|
|
1435
|
+
if (options.headers) {
|
|
1436
|
+
Object.assign(
|
|
1437
|
+
options.instance.defaults.headers.common,
|
|
1438
|
+
options.headers
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
const requestSteps = [];
|
|
1443
|
+
const responseSteps = [];
|
|
1444
|
+
const loggerInterceptors = options.logger ? createLoggerInterceptors(options.logger) : null;
|
|
1445
|
+
if (loggerInterceptors) {
|
|
1446
|
+
requestSteps.push({ name: "logger", spec: loggerInterceptors.request });
|
|
1447
|
+
}
|
|
1448
|
+
for (const spec of toRequestSpecs(
|
|
1449
|
+
options.interceptors?.request?.beforeAuth
|
|
1450
|
+
)) {
|
|
1451
|
+
requestSteps.push({ name: "business:beforeAuth", spec });
|
|
1452
|
+
}
|
|
1453
|
+
if (options.apiKey) {
|
|
1454
|
+
requestSteps.push({
|
|
1455
|
+
name: "api-key",
|
|
1456
|
+
spec: {
|
|
1457
|
+
onFulfilled: createApiKeyInterceptor(
|
|
1458
|
+
options.apiKey,
|
|
1459
|
+
options.allowCrossOriginAuth
|
|
1460
|
+
)
|
|
1461
|
+
}
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
if (options.jwt !== false) {
|
|
1465
|
+
requestSteps.push({
|
|
1466
|
+
name: "jwt",
|
|
1467
|
+
spec: {
|
|
1468
|
+
onFulfilled: createJwtRequestInterceptor(
|
|
1469
|
+
session,
|
|
1470
|
+
options.refreshBeforeExpirationMs,
|
|
1471
|
+
options.allowCrossOriginAuth
|
|
1472
|
+
)
|
|
1473
|
+
}
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
for (const spec of toRequestSpecs(
|
|
1477
|
+
options.interceptors?.request?.afterAuth
|
|
1478
|
+
)) {
|
|
1479
|
+
requestSteps.push({ name: "business:afterAuth", spec });
|
|
1480
|
+
}
|
|
1481
|
+
for (const spec of toResponseSpecs(
|
|
1482
|
+
options.interceptors?.response?.beforeUnwrap
|
|
1483
|
+
)) {
|
|
1484
|
+
responseSteps.push({ name: "business:beforeUnwrap", spec });
|
|
1485
|
+
}
|
|
1486
|
+
responseSteps.push({
|
|
1487
|
+
name: "unwrap",
|
|
1488
|
+
spec: { onFulfilled: unwrapInterceptor }
|
|
1489
|
+
});
|
|
1490
|
+
if (options.jwt !== false && refresh) {
|
|
1491
|
+
responseSteps.push({
|
|
1492
|
+
name: "jwt",
|
|
1493
|
+
spec: {
|
|
1494
|
+
onRejected: createJwtResponseInterceptor(http, session, {
|
|
1495
|
+
refreshWhen: options.refreshWhen,
|
|
1496
|
+
allowCrossOriginAuth: options.allowCrossOriginAuth,
|
|
1497
|
+
retryOnUnauthorized: options.retryOnUnauthorized
|
|
1498
|
+
})
|
|
1499
|
+
}
|
|
1500
|
+
});
|
|
1501
|
+
}
|
|
1502
|
+
responseSteps.push({
|
|
1503
|
+
name: "error-normalizer",
|
|
1504
|
+
spec: { onRejected: createErrorNormalizer() }
|
|
1505
|
+
});
|
|
1506
|
+
if (loggerInterceptors) {
|
|
1507
|
+
responseSteps.push({ name: "logger", spec: loggerInterceptors.response });
|
|
1508
|
+
}
|
|
1509
|
+
for (const spec of toResponseSpecs(
|
|
1510
|
+
options.interceptors?.response?.afterSettled
|
|
1511
|
+
)) {
|
|
1512
|
+
responseSteps.push({ name: "business:afterSettled", spec });
|
|
1513
|
+
}
|
|
1514
|
+
const requestIds = [];
|
|
1515
|
+
for (const step of [...requestSteps].reverse()) {
|
|
1516
|
+
requestIds.push(
|
|
1517
|
+
http.interceptors.request.use(
|
|
1518
|
+
step.spec.onFulfilled,
|
|
1519
|
+
step.spec.onRejected
|
|
1520
|
+
)
|
|
1521
|
+
);
|
|
1522
|
+
}
|
|
1523
|
+
const responseIds = [];
|
|
1524
|
+
for (const step of responseSteps) {
|
|
1525
|
+
responseIds.push(
|
|
1526
|
+
http.interceptors.response.use(
|
|
1527
|
+
step.spec.onFulfilled,
|
|
1528
|
+
step.spec.onRejected
|
|
1529
|
+
)
|
|
1530
|
+
);
|
|
1531
|
+
}
|
|
1532
|
+
return {
|
|
1533
|
+
http,
|
|
1534
|
+
refreshHttp,
|
|
1535
|
+
session,
|
|
1536
|
+
dispose() {
|
|
1537
|
+
for (const id of requestIds) http.interceptors.request.eject(id);
|
|
1538
|
+
for (const id of responseIds) http.interceptors.response.eject(id);
|
|
1539
|
+
for (const id of refreshRequestIds) {
|
|
1540
|
+
refreshHttp.interceptors.request.eject(id);
|
|
1541
|
+
}
|
|
1542
|
+
for (const id of refreshResponseIds) {
|
|
1543
|
+
refreshHttp.interceptors.response.eject(id);
|
|
1544
|
+
}
|
|
1545
|
+
session.dispose();
|
|
1546
|
+
}
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
export { createHttp, jsonTokenSerializer, toErrorText };
|
|
1551
|
+
//# sourceMappingURL=index.js.map
|
|
1552
|
+
//# sourceMappingURL=index.js.map
|