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