@be-link/request 1.45.1-beta.2 → 1.45.1-beta.4

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.cjs.js CHANGED
@@ -7,7 +7,7 @@ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentS
7
7
  /**
8
8
  * HTTP 状态码常量
9
9
  */
10
- var HTTP_STATUS = {
10
+ const HTTP_STATUS = {
11
11
  OK: 200,
12
12
  CREATED: 201,
13
13
  NO_CONTENT: 204,
@@ -43,24 +43,29 @@ exports.ContentType = void 0;
43
43
  /**
44
44
  * 默认超时时间
45
45
  */
46
- var DEFAULT_TIMEOUT = 8000;
46
+ const DEFAULT_TIMEOUT = 8000;
47
47
  /**
48
48
  * Token Header 名称
49
49
  */
50
- var TOKEN_HEADER = 'x-belink-authorization';
50
+ const TOKEN_HEADER = 'x-belink-authorization';
51
+ /**
52
+ * UserID Header 名称
53
+ */
54
+ const USERID_HEADER = 'x-belink-userid';
51
55
  /**
52
56
  * 时间同步 Header
53
57
  */
54
- var TIME_SYNC_HEADERS = {
58
+ const TIME_SYNC_HEADERS = {
55
59
  SERVER_TIME: 'x-belink-serverTime',
56
60
  TIME_DIFF: 'x-belink-timeDiff',
57
61
  };
58
62
  /**
59
63
  * LocalStorage 键
60
64
  */
61
- var STORAGE_KEYS = {
65
+ const STORAGE_KEYS = {
62
66
  TOKEN: 'token',
63
67
  SERVER_TIME: 'x-belink-serverTime',
68
+ CLIENT_TIME: 'x-belink-clientTime',
64
69
  TIME_DIFF: 'x-belink-timeDiff',
65
70
  };
66
71
 
@@ -70,9 +75,9 @@ var STORAGE_KEYS = {
70
75
  */
71
76
  function request(config) {
72
77
  // 创建独立实例,避免拦截器泄漏
73
- var instance = axios.create();
78
+ const instance = axios.create();
74
79
  // 解析 HTTP 方法
75
- var method = config.method || (config.data ? 'post' : 'get');
80
+ const method = config.method || (config.data ? 'post' : 'get');
76
81
  // 应用临时拦截器
77
82
  if (config.requestInterceptors && typeof config.requestInterceptors === 'function') {
78
83
  instance.interceptors.request.use(config.requestInterceptors);
@@ -80,18 +85,18 @@ function request(config) {
80
85
  if (config.responseInterceptors && typeof config.responseInterceptors === 'function') {
81
86
  instance.interceptors.response.use(config.responseInterceptors);
82
87
  }
83
- var timeout = config.timeout || DEFAULT_TIMEOUT;
84
- return new Promise(function (resolve, reject) {
88
+ const timeout = config.timeout || DEFAULT_TIMEOUT;
89
+ return new Promise((resolve, reject) => {
85
90
  instance
86
91
  .request({
87
- method: method,
92
+ method,
88
93
  url: config.url,
89
94
  headers: config.headers || {},
90
95
  data: config.data,
91
96
  params: config.params,
92
- timeout: timeout,
97
+ timeout,
93
98
  })
94
- .then(function (result) {
99
+ .then((result) => {
95
100
  if (result.status === 200) {
96
101
  resolve(result.data);
97
102
  }
@@ -99,140 +104,15 @@ function request(config) {
99
104
  reject(result.data);
100
105
  }
101
106
  })
102
- .catch(function (reason) {
103
- var _a, _b;
107
+ .catch((reason) => {
104
108
  if (config.catchCallback && typeof config.catchCallback === 'function') {
105
109
  config.catchCallback(reason);
106
110
  }
107
- reject((_b = (_a = reason === null || reason === void 0 ? void 0 : reason.response) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : reason);
111
+ reject(reason?.response?.data ?? reason);
108
112
  });
109
113
  });
110
114
  }
111
115
 
112
- /******************************************************************************
113
- Copyright (c) Microsoft Corporation.
114
-
115
- Permission to use, copy, modify, and/or distribute this software for any
116
- purpose with or without fee is hereby granted.
117
-
118
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
119
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
120
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
121
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
122
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
123
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
124
- PERFORMANCE OF THIS SOFTWARE.
125
- ***************************************************************************** */
126
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
127
-
128
- var extendStatics = function(d, b) {
129
- extendStatics = Object.setPrototypeOf ||
130
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
131
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
132
- return extendStatics(d, b);
133
- };
134
-
135
- function __extends$1(d, b) {
136
- if (typeof b !== "function" && b !== null)
137
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
138
- extendStatics(d, b);
139
- function __() { this.constructor = d; }
140
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
141
- }
142
-
143
- var __assign$4 = function() {
144
- __assign$4 = Object.assign || function __assign(t) {
145
- for (var s, i = 1, n = arguments.length; i < n; i++) {
146
- s = arguments[i];
147
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
148
- }
149
- return t;
150
- };
151
- return __assign$4.apply(this, arguments);
152
- };
153
-
154
- function __awaiter$3(thisArg, _arguments, P, generator) {
155
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
156
- return new (P || (P = Promise))(function (resolve, reject) {
157
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
158
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
159
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
160
- step((generator = generator.apply(thisArg, _arguments || [])).next());
161
- });
162
- }
163
-
164
- function __generator$3(thisArg, body) {
165
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
166
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
167
- function verb(n) { return function (v) { return step([n, v]); }; }
168
- function step(op) {
169
- if (f) throw new TypeError("Generator is already executing.");
170
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
171
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
172
- if (y = 0, t) op = [op[0] & 2, t.value];
173
- switch (op[0]) {
174
- case 0: case 1: t = op; break;
175
- case 4: _.label++; return { value: op[1], done: false };
176
- case 5: _.label++; y = op[1]; op = [0]; continue;
177
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
178
- default:
179
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
180
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
181
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
182
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
183
- if (t[2]) _.ops.pop();
184
- _.trys.pop(); continue;
185
- }
186
- op = body.call(thisArg, _);
187
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
188
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
189
- }
190
- }
191
-
192
- function __values(o) {
193
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
194
- if (m) return m.call(o);
195
- if (o && typeof o.length === "number") return {
196
- next: function () {
197
- if (o && i >= o.length) o = void 0;
198
- return { value: o && o[i++], done: !o };
199
- }
200
- };
201
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
202
- }
203
-
204
- function __read(o, n) {
205
- var m = typeof Symbol === "function" && o[Symbol.iterator];
206
- if (!m) return o;
207
- var i = m.call(o), r, ar = [], e;
208
- try {
209
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
210
- }
211
- catch (error) { e = { error: error }; }
212
- finally {
213
- try {
214
- if (r && !r.done && (m = i["return"])) m.call(i);
215
- }
216
- finally { if (e) throw e.error; }
217
- }
218
- return ar;
219
- }
220
-
221
- function __spreadArray$1(to, from, pack) {
222
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
223
- if (ar || !(i in from)) {
224
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
225
- ar[i] = from[i];
226
- }
227
- }
228
- return to.concat(ar || Array.prototype.slice.call(from));
229
- }
230
-
231
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
232
- var e = new Error(message);
233
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
234
- };
235
-
236
116
  /**
237
117
  * HTTP 方法枚举
238
118
  */
@@ -248,660 +128,376 @@ exports.HttpMethod = void 0;
248
128
  /**
249
129
  * 基础错误类
250
130
  */
251
- var BaseError = /** @class */ (function (_super) {
252
- __extends$1(BaseError, _super);
253
- function BaseError(message, code, originalError) {
254
- var _this = _super.call(this, message) || this;
255
- Object.defineProperty(_this, "code", {
256
- enumerable: true,
257
- configurable: true,
258
- writable: true,
259
- value: void 0
260
- });
261
- Object.defineProperty(_this, "originalError", {
262
- enumerable: true,
263
- configurable: true,
264
- writable: true,
265
- value: void 0
266
- });
267
- _this.name = _this.constructor.name;
268
- _this.code = code;
269
- _this.originalError = originalError;
270
- Error.captureStackTrace(_this, _this.constructor);
271
- return _this;
131
+ class BaseError extends Error {
132
+ constructor(message, code, originalError) {
133
+ super(message);
134
+ this.name = this.constructor.name;
135
+ this.code = code;
136
+ this.originalError = originalError;
137
+ Error.captureStackTrace(this, this.constructor);
272
138
  }
273
- return BaseError;
274
- }(Error));
139
+ }
275
140
  /**
276
141
  * HTTP 错误
277
142
  */
278
- var HttpError = /** @class */ (function (_super) {
279
- __extends$1(HttpError, _super);
280
- function HttpError(message, status, data, originalError) {
281
- var _this = _super.call(this, message, 'HTTP_ERROR', originalError) || this;
282
- Object.defineProperty(_this, "status", {
283
- enumerable: true,
284
- configurable: true,
285
- writable: true,
286
- value: void 0
287
- });
288
- Object.defineProperty(_this, "data", {
289
- enumerable: true,
290
- configurable: true,
291
- writable: true,
292
- value: void 0
293
- });
294
- _this.status = status;
295
- _this.data = data;
296
- return _this;
143
+ class HttpError extends BaseError {
144
+ constructor(message, status, data, originalError) {
145
+ super(message, 'HTTP_ERROR', originalError);
146
+ this.status = status;
147
+ this.data = data;
297
148
  }
298
- return HttpError;
299
- }(BaseError));
149
+ }
300
150
  /**
301
151
  * 认证错误
302
152
  */
303
- var AuthError = /** @class */ (function (_super) {
304
- __extends$1(AuthError, _super);
305
- function AuthError(message, originalError) {
306
- if (message === void 0) { message = 'Unauthorized'; }
307
- return _super.call(this, message, 'AUTH_ERROR', originalError) || this;
308
- }
309
- return AuthError;
310
- }(BaseError));
153
+ class AuthError extends BaseError {
154
+ constructor(message = 'Unauthorized', originalError) {
155
+ super(message, 'AUTH_ERROR', originalError);
156
+ }
157
+ }
311
158
  /**
312
159
  * 超时错误
313
160
  */
314
- var TimeoutError = /** @class */ (function (_super) {
315
- __extends$1(TimeoutError, _super);
316
- function TimeoutError(message, timeout, originalError) {
317
- var _this = _super.call(this, message, 'TIMEOUT_ERROR', originalError) || this;
318
- Object.defineProperty(_this, "timeout", {
319
- enumerable: true,
320
- configurable: true,
321
- writable: true,
322
- value: void 0
323
- });
324
- _this.timeout = timeout;
325
- return _this;
161
+ class TimeoutError extends BaseError {
162
+ constructor(message, timeout, originalError) {
163
+ super(message, 'TIMEOUT_ERROR', originalError);
164
+ this.timeout = timeout;
326
165
  }
327
- return TimeoutError;
328
- }(BaseError));
166
+ }
329
167
  /**
330
168
  * 配置错误
331
169
  */
332
- var ConfigError = /** @class */ (function (_super) {
333
- __extends$1(ConfigError, _super);
334
- function ConfigError(message, originalError) {
335
- return _super.call(this, message, 'CONFIG_ERROR', originalError) || this;
170
+ class ConfigError extends BaseError {
171
+ constructor(message, originalError) {
172
+ super(message, 'CONFIG_ERROR', originalError);
336
173
  }
337
- return ConfigError;
338
- }(BaseError));
174
+ }
339
175
  /**
340
176
  * 网络错误
341
177
  */
342
- var NetworkError = /** @class */ (function (_super) {
343
- __extends$1(NetworkError, _super);
344
- function NetworkError(message, originalError) {
345
- if (message === void 0) { message = 'Network error'; }
346
- return _super.call(this, message, 'NETWORK_ERROR', originalError) || this;
178
+ class NetworkError extends BaseError {
179
+ constructor(message = 'Network error', originalError) {
180
+ super(message, 'NETWORK_ERROR', originalError);
347
181
  }
348
- return NetworkError;
349
- }(BaseError));
182
+ }
350
183
 
351
184
  /**
352
185
  * Axios 适配器
353
186
  * 封装 Axios 实例,提供统一的请求接口
354
187
  */
355
- var AxiosAdapter = /** @class */ (function () {
356
- function AxiosAdapter(baseURL, timeout) {
357
- Object.defineProperty(this, "instance", {
358
- enumerable: true,
359
- configurable: true,
360
- writable: true,
361
- value: void 0
362
- });
363
- Object.defineProperty(this, "interceptorIds", {
364
- enumerable: true,
365
- configurable: true,
366
- writable: true,
367
- value: {
368
- request: [],
369
- response: [],
370
- }
371
- });
188
+ class AxiosAdapter {
189
+ constructor(baseURL, timeout) {
190
+ this.interceptorIds = {
191
+ request: [],
192
+ response: [],
193
+ };
372
194
  this.instance = axios.create({
373
- baseURL: baseURL,
195
+ baseURL,
374
196
  timeout: timeout || DEFAULT_TIMEOUT,
375
197
  });
376
198
  }
377
199
  /**
378
200
  * 发起请求
379
201
  */
380
- Object.defineProperty(AxiosAdapter.prototype, "request", {
381
- enumerable: false,
382
- configurable: true,
383
- writable: true,
384
- value: function (config) {
385
- return __awaiter$3(this, void 0, void 0, function () {
386
- var headers, axiosConfig, response, error_1;
387
- return __generator$3(this, function (_a) {
388
- switch (_a.label) {
389
- case 0:
390
- headers = __assign$4({}, config.headers);
391
- // 当有请求体时,默认设置 Content-Type 为 application/json
392
- if (config.data && !headers['Content-Type'] && !headers['content-type']) {
393
- headers['Content-Type'] = exports.ContentType.JSON;
394
- }
395
- axiosConfig = __assign$4({ method: config.method || (config.data ? exports.HttpMethod.POST : exports.HttpMethod.GET), url: config.url, headers: headers, data: config.data, params: config.params, timeout: config.timeout || DEFAULT_TIMEOUT }, config.axiosConfig);
396
- _a.label = 1;
397
- case 1:
398
- _a.trys.push([1, 3, , 4]);
399
- return [4 /*yield*/, this.instance.request(axiosConfig)];
400
- case 2:
401
- response = _a.sent();
402
- if (response.status === 200) {
403
- return [2 /*return*/, response.data];
404
- }
405
- throw new HttpError("Request failed with status ".concat(response.status), response.status, response.data);
406
- case 3:
407
- error_1 = _a.sent();
408
- throw this.handleError(error_1);
409
- case 4: return [2 /*return*/];
410
- }
411
- });
412
- });
202
+ async request(config) {
203
+ const headers = { ...config.headers };
204
+ // 当有请求体时,默认设置 Content-Type 为 application/json
205
+ if (config.data && !headers['Content-Type'] && !headers['content-type']) {
206
+ headers['Content-Type'] = exports.ContentType.JSON;
413
207
  }
414
- });
208
+ const axiosConfig = {
209
+ method: config.method || (config.data ? exports.HttpMethod.POST : exports.HttpMethod.GET),
210
+ url: config.url,
211
+ headers,
212
+ data: config.data,
213
+ params: config.params,
214
+ timeout: config.timeout || DEFAULT_TIMEOUT,
215
+ ...config.axiosConfig,
216
+ };
217
+ try {
218
+ const response = await this.instance.request(axiosConfig);
219
+ if (response.status === 200) {
220
+ return response.data;
221
+ }
222
+ throw new HttpError(`Request failed with status ${response.status}`, response.status, response.data);
223
+ }
224
+ catch (error) {
225
+ throw this.handleError(error);
226
+ }
227
+ }
415
228
  /**
416
229
  * 添加请求拦截器
417
230
  * @returns 拦截器 ID
418
231
  */
419
- Object.defineProperty(AxiosAdapter.prototype, "addRequestInterceptor", {
420
- enumerable: false,
421
- configurable: true,
422
- writable: true,
423
- value: function (onFulfilled, onRejected) {
424
- var id = this.instance.interceptors.request.use(onFulfilled, onRejected);
425
- this.interceptorIds.request.push(id);
426
- return id;
427
- }
428
- });
232
+ addRequestInterceptor(onFulfilled, onRejected) {
233
+ const id = this.instance.interceptors.request.use(onFulfilled, onRejected);
234
+ this.interceptorIds.request.push(id);
235
+ return id;
236
+ }
429
237
  /**
430
238
  * 添加响应拦截器
431
239
  * @returns 拦截器 ID
432
240
  */
433
- Object.defineProperty(AxiosAdapter.prototype, "addResponseInterceptor", {
434
- enumerable: false,
435
- configurable: true,
436
- writable: true,
437
- value: function (onFulfilled, onRejected) {
438
- var id = this.instance.interceptors.response.use(onFulfilled, onRejected);
439
- this.interceptorIds.response.push(id);
440
- return id;
441
- }
442
- });
241
+ addResponseInterceptor(onFulfilled, onRejected) {
242
+ const id = this.instance.interceptors.response.use(onFulfilled, onRejected);
243
+ this.interceptorIds.response.push(id);
244
+ return id;
245
+ }
443
246
  /**
444
247
  * 移除请求拦截器
445
248
  */
446
- Object.defineProperty(AxiosAdapter.prototype, "removeRequestInterceptor", {
447
- enumerable: false,
448
- configurable: true,
449
- writable: true,
450
- value: function (id) {
451
- this.instance.interceptors.request.eject(id);
452
- var index = this.interceptorIds.request.indexOf(id);
453
- if (index > -1) {
454
- this.interceptorIds.request.splice(index, 1);
455
- }
249
+ removeRequestInterceptor(id) {
250
+ this.instance.interceptors.request.eject(id);
251
+ const index = this.interceptorIds.request.indexOf(id);
252
+ if (index > -1) {
253
+ this.interceptorIds.request.splice(index, 1);
456
254
  }
457
- });
255
+ }
458
256
  /**
459
257
  * 移除响应拦截器
460
258
  */
461
- Object.defineProperty(AxiosAdapter.prototype, "removeResponseInterceptor", {
462
- enumerable: false,
463
- configurable: true,
464
- writable: true,
465
- value: function (id) {
466
- this.instance.interceptors.response.eject(id);
467
- var index = this.interceptorIds.response.indexOf(id);
468
- if (index > -1) {
469
- this.interceptorIds.response.splice(index, 1);
470
- }
259
+ removeResponseInterceptor(id) {
260
+ this.instance.interceptors.response.eject(id);
261
+ const index = this.interceptorIds.response.indexOf(id);
262
+ if (index > -1) {
263
+ this.interceptorIds.response.splice(index, 1);
471
264
  }
472
- });
265
+ }
473
266
  /**
474
267
  * 清理所有拦截器
475
268
  */
476
- Object.defineProperty(AxiosAdapter.prototype, "clearAllInterceptors", {
477
- enumerable: false,
478
- configurable: true,
479
- writable: true,
480
- value: function () {
481
- var _this = this;
482
- this.interceptorIds.request.forEach(function (id) {
483
- _this.instance.interceptors.request.eject(id);
484
- });
485
- this.interceptorIds.response.forEach(function (id) {
486
- _this.instance.interceptors.response.eject(id);
487
- });
488
- this.interceptorIds = { request: [], response: [] };
489
- }
490
- });
269
+ clearAllInterceptors() {
270
+ this.interceptorIds.request.forEach((id) => {
271
+ this.instance.interceptors.request.eject(id);
272
+ });
273
+ this.interceptorIds.response.forEach((id) => {
274
+ this.instance.interceptors.response.eject(id);
275
+ });
276
+ this.interceptorIds = { request: [], response: [] };
277
+ }
491
278
  /**
492
279
  * 获取 Axios 实例
493
280
  */
494
- Object.defineProperty(AxiosAdapter.prototype, "getInstance", {
495
- enumerable: false,
496
- configurable: true,
497
- writable: true,
498
- value: function () {
499
- return this.instance;
500
- }
501
- });
281
+ getInstance() {
282
+ return this.instance;
283
+ }
502
284
  /**
503
285
  * 设置 BaseURL
504
286
  */
505
- Object.defineProperty(AxiosAdapter.prototype, "setBaseUrl", {
506
- enumerable: false,
507
- configurable: true,
508
- writable: true,
509
- value: function (baseUrl) {
510
- this.instance.defaults.baseURL = baseUrl;
511
- }
512
- });
287
+ setBaseUrl(baseUrl) {
288
+ this.instance.defaults.baseURL = baseUrl;
289
+ }
513
290
  /**
514
291
  * 处理错误
515
292
  */
516
- Object.defineProperty(AxiosAdapter.prototype, "handleError", {
517
- enumerable: false,
518
- configurable: true,
519
- writable: true,
520
- value: function (error) {
521
- var _a, _b;
522
- if (axios.isAxiosError(error)) {
523
- var axiosError = error;
524
- if (axiosError.code === 'ECONNABORTED') {
525
- return new TimeoutError("Request timeout after ".concat((_a = axiosError.config) === null || _a === void 0 ? void 0 : _a.timeout, "ms"), ((_b = axiosError.config) === null || _b === void 0 ? void 0 : _b.timeout) || DEFAULT_TIMEOUT, axiosError);
526
- }
527
- if (!axiosError.response) {
528
- return new NetworkError('Network error: Unable to reach server', axiosError);
529
- }
530
- return new HttpError(axiosError.message, axiosError.response.status, axiosError.response.data, axiosError);
293
+ handleError(error) {
294
+ if (axios.isAxiosError(error)) {
295
+ const axiosError = error;
296
+ if (axiosError.code === 'ECONNABORTED') {
297
+ return new TimeoutError(`Request timeout after ${axiosError.config?.timeout}ms`, axiosError.config?.timeout || DEFAULT_TIMEOUT, axiosError);
531
298
  }
532
- if (error instanceof Error) {
533
- return error;
299
+ if (!axiosError.response) {
300
+ return new NetworkError('Network error: Unable to reach server', axiosError);
534
301
  }
535
- return new Error(String(error));
302
+ return new HttpError(axiosError.message, axiosError.response.status, axiosError.response.data, axiosError);
536
303
  }
537
- });
538
- return AxiosAdapter;
539
- }());
304
+ if (error instanceof Error) {
305
+ return error;
306
+ }
307
+ return new Error(String(error));
308
+ }
309
+ }
540
310
 
541
311
  /**
542
312
  * 生成请求 ID
543
313
  */
544
314
  function generateRequestId() {
545
- return "req_".concat(Date.now(), "_").concat(Math.random().toString(36).substring(2, 11));
315
+ return `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
546
316
  }
547
317
  /**
548
318
  * HTTP 客户端实现
549
319
  * 提供基础的 HTTP 请求功能
550
320
  */
551
- var HttpClient = /** @class */ (function () {
552
- function HttpClient(adapter) {
553
- Object.defineProperty(this, "adapter", {
554
- enumerable: true,
555
- configurable: true,
556
- writable: true,
557
- value: void 0
558
- });
559
- Object.defineProperty(this, "requestInterceptors", {
560
- enumerable: true,
561
- configurable: true,
562
- writable: true,
563
- value: []
564
- });
565
- Object.defineProperty(this, "responseInterceptors", {
566
- enumerable: true,
567
- configurable: true,
568
- writable: true,
569
- value: []
570
- });
321
+ class HttpClient {
322
+ constructor(adapter) {
323
+ this.requestInterceptors = [];
324
+ this.responseInterceptors = [];
571
325
  this.adapter = adapter || new AxiosAdapter();
572
326
  }
573
327
  /**
574
328
  * GET 请求
575
329
  */
576
- Object.defineProperty(HttpClient.prototype, "get", {
577
- enumerable: false,
578
- configurable: true,
579
- writable: true,
580
- value: function (url, config) {
581
- return __awaiter$3(this, void 0, void 0, function () {
582
- return __generator$3(this, function (_a) {
583
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, method: exports.HttpMethod.GET }))];
584
- });
585
- });
586
- }
587
- });
330
+ async get(url, config) {
331
+ return this.request({ ...config, url, method: exports.HttpMethod.GET });
332
+ }
588
333
  /**
589
334
  * POST 请求
590
335
  */
591
- Object.defineProperty(HttpClient.prototype, "post", {
592
- enumerable: false,
593
- configurable: true,
594
- writable: true,
595
- value: function (url, data, config) {
596
- return __awaiter$3(this, void 0, void 0, function () {
597
- return __generator$3(this, function (_a) {
598
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, data: data, method: exports.HttpMethod.POST }))];
599
- });
600
- });
601
- }
602
- });
336
+ async post(url, data, config) {
337
+ return this.request({ ...config, url, data, method: exports.HttpMethod.POST });
338
+ }
603
339
  /**
604
340
  * PUT 请求
605
341
  */
606
- Object.defineProperty(HttpClient.prototype, "put", {
607
- enumerable: false,
608
- configurable: true,
609
- writable: true,
610
- value: function (url, data, config) {
611
- return __awaiter$3(this, void 0, void 0, function () {
612
- return __generator$3(this, function (_a) {
613
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, data: data, method: exports.HttpMethod.PUT }))];
614
- });
615
- });
616
- }
617
- });
342
+ async put(url, data, config) {
343
+ return this.request({ ...config, url, data, method: exports.HttpMethod.PUT });
344
+ }
618
345
  /**
619
346
  * DELETE 请求
620
347
  */
621
- Object.defineProperty(HttpClient.prototype, "delete", {
622
- enumerable: false,
623
- configurable: true,
624
- writable: true,
625
- value: function (url, config) {
626
- return __awaiter$3(this, void 0, void 0, function () {
627
- return __generator$3(this, function (_a) {
628
- return [2 /*return*/, this.request(__assign$4(__assign$4({}, config), { url: url, method: exports.HttpMethod.DELETE }))];
629
- });
630
- });
631
- }
632
- });
348
+ async delete(url, config) {
349
+ return this.request({ ...config, url, method: exports.HttpMethod.DELETE });
350
+ }
633
351
  /**
634
352
  * 通用请求方法
635
353
  */
636
- Object.defineProperty(HttpClient.prototype, "request", {
637
- enumerable: false,
638
- configurable: true,
639
- writable: true,
640
- value: function (config) {
641
- return __awaiter$3(this, void 0, void 0, function () {
642
- var context, processedContext, _a, _b, interceptor, e_1_1, response, responseContext, _c, _d, interceptor, e_2_1, error_1, processedError, _e, _f, interceptor, interceptorError_1, e_3_1;
643
- var e_1, _g, e_2, _h, e_3, _j;
644
- return __generator$3(this, function (_k) {
645
- switch (_k.label) {
646
- case 0:
647
- context = {
648
- config: this.normalizeConfig(config),
649
- startTime: Date.now(),
650
- requestId: generateRequestId(),
651
- metadata: new Map(),
652
- };
653
- _k.label = 1;
654
- case 1:
655
- _k.trys.push([1, 19, , 30]);
656
- processedContext = context;
657
- _k.label = 2;
658
- case 2:
659
- _k.trys.push([2, 7, 8, 9]);
660
- _a = __values(this.requestInterceptors), _b = _a.next();
661
- _k.label = 3;
662
- case 3:
663
- if (!!_b.done) return [3 /*break*/, 6];
664
- interceptor = _b.value;
665
- return [4 /*yield*/, interceptor.onRequest(processedContext)];
666
- case 4:
667
- processedContext = (_k.sent());
668
- _k.label = 5;
669
- case 5:
670
- _b = _a.next();
671
- return [3 /*break*/, 3];
672
- case 6: return [3 /*break*/, 9];
673
- case 7:
674
- e_1_1 = _k.sent();
675
- e_1 = { error: e_1_1 };
676
- return [3 /*break*/, 9];
677
- case 8:
678
- try {
679
- if (_b && !_b.done && (_g = _a.return)) _g.call(_a);
680
- }
681
- finally { if (e_1) throw e_1.error; }
682
- return [7 /*endfinally*/];
683
- case 9: return [4 /*yield*/, this.adapter.request(processedContext.config)];
684
- case 10:
685
- response = _k.sent();
686
- responseContext = {
687
- response: response,
688
- status: 200,
689
- headers: {},
690
- duration: Date.now() - context.startTime,
691
- requestId: context.requestId,
692
- };
693
- _k.label = 11;
694
- case 11:
695
- _k.trys.push([11, 16, 17, 18]);
696
- _c = __values(this.responseInterceptors), _d = _c.next();
697
- _k.label = 12;
698
- case 12:
699
- if (!!_d.done) return [3 /*break*/, 15];
700
- interceptor = _d.value;
701
- return [4 /*yield*/, interceptor.onResponse(responseContext)];
702
- case 13:
703
- responseContext = _k.sent();
704
- _k.label = 14;
705
- case 14:
706
- _d = _c.next();
707
- return [3 /*break*/, 12];
708
- case 15: return [3 /*break*/, 18];
709
- case 16:
710
- e_2_1 = _k.sent();
711
- e_2 = { error: e_2_1 };
712
- return [3 /*break*/, 18];
713
- case 17:
714
- try {
715
- if (_d && !_d.done && (_h = _c.return)) _h.call(_c);
716
- }
717
- finally { if (e_2) throw e_2.error; }
718
- return [7 /*endfinally*/];
719
- case 18: return [2 /*return*/, responseContext.response];
720
- case 19:
721
- error_1 = _k.sent();
722
- processedError = error_1;
723
- _k.label = 20;
724
- case 20:
725
- _k.trys.push([20, 27, 28, 29]);
726
- _e = __values(this.responseInterceptors), _f = _e.next();
727
- _k.label = 21;
728
- case 21:
729
- if (!!_f.done) return [3 /*break*/, 26];
730
- interceptor = _f.value;
731
- if (!interceptor.onResponseError) return [3 /*break*/, 25];
732
- _k.label = 22;
733
- case 22:
734
- _k.trys.push([22, 24, , 25]);
735
- return [4 /*yield*/, interceptor.onResponseError(processedError)];
736
- case 23:
737
- processedError = _k.sent();
738
- return [3 /*break*/, 25];
739
- case 24:
740
- interceptorError_1 = _k.sent();
741
- processedError = interceptorError_1;
742
- return [3 /*break*/, 25];
743
- case 25:
744
- _f = _e.next();
745
- return [3 /*break*/, 21];
746
- case 26: return [3 /*break*/, 29];
747
- case 27:
748
- e_3_1 = _k.sent();
749
- e_3 = { error: e_3_1 };
750
- return [3 /*break*/, 29];
751
- case 28:
752
- try {
753
- if (_f && !_f.done && (_j = _e.return)) _j.call(_e);
754
- }
755
- finally { if (e_3) throw e_3.error; }
756
- return [7 /*endfinally*/];
757
- case 29: throw processedError;
758
- case 30: return [2 /*return*/];
354
+ async request(config) {
355
+ // 创建请求上下文
356
+ const context = {
357
+ config: this.normalizeConfig(config),
358
+ startTime: Date.now(),
359
+ requestId: generateRequestId(),
360
+ metadata: new Map(),
361
+ };
362
+ try {
363
+ // 执行请求拦截器
364
+ let processedContext = context;
365
+ for (const interceptor of this.requestInterceptors) {
366
+ processedContext = (await interceptor.onRequest(processedContext));
367
+ }
368
+ // 发起请求
369
+ const response = await this.adapter.request(processedContext.config);
370
+ // 创建响应上下文
371
+ let responseContext = {
372
+ response,
373
+ status: 200,
374
+ headers: {},
375
+ duration: Date.now() - context.startTime,
376
+ requestId: context.requestId,
377
+ };
378
+ // 执行响应拦截器
379
+ for (const interceptor of this.responseInterceptors) {
380
+ responseContext = await interceptor.onResponse(responseContext);
381
+ }
382
+ return responseContext.response;
383
+ }
384
+ catch (error) {
385
+ // 执行错误拦截器
386
+ let processedError = error;
387
+ for (const interceptor of this.responseInterceptors) {
388
+ if (interceptor.onResponseError) {
389
+ try {
390
+ processedError = await interceptor.onResponseError(processedError);
759
391
  }
760
- });
761
- });
392
+ catch (interceptorError) {
393
+ processedError = interceptorError;
394
+ }
395
+ }
396
+ }
397
+ throw processedError;
762
398
  }
763
- });
399
+ }
764
400
  /**
765
401
  * 添加请求拦截器
766
402
  */
767
- Object.defineProperty(HttpClient.prototype, "addRequestInterceptor", {
768
- enumerable: false,
769
- configurable: true,
770
- writable: true,
771
- value: function (interceptor) {
772
- var _this = this;
773
- this.requestInterceptors.push(interceptor);
774
- this.requestInterceptors.sort(function (a, b) { return (a.priority || 0) - (b.priority || 0); });
775
- return function () {
776
- var index = _this.requestInterceptors.indexOf(interceptor);
777
- if (index > -1) {
778
- _this.requestInterceptors.splice(index, 1);
779
- }
780
- };
781
- }
782
- });
403
+ addRequestInterceptor(interceptor) {
404
+ this.requestInterceptors.push(interceptor);
405
+ this.requestInterceptors.sort((a, b) => (a.priority || 0) - (b.priority || 0));
406
+ return () => {
407
+ const index = this.requestInterceptors.indexOf(interceptor);
408
+ if (index > -1) {
409
+ this.requestInterceptors.splice(index, 1);
410
+ }
411
+ };
412
+ }
783
413
  /**
784
414
  * 添加响应拦截器
785
415
  */
786
- Object.defineProperty(HttpClient.prototype, "addResponseInterceptor", {
787
- enumerable: false,
788
- configurable: true,
789
- writable: true,
790
- value: function (interceptor) {
791
- var _this = this;
792
- this.responseInterceptors.push(interceptor);
793
- this.responseInterceptors.sort(function (a, b) { return (a.priority || 0) - (b.priority || 0); });
794
- return function () {
795
- var index = _this.responseInterceptors.indexOf(interceptor);
796
- if (index > -1) {
797
- _this.responseInterceptors.splice(index, 1);
798
- }
799
- };
800
- }
801
- });
416
+ addResponseInterceptor(interceptor) {
417
+ this.responseInterceptors.push(interceptor);
418
+ this.responseInterceptors.sort((a, b) => (a.priority || 0) - (b.priority || 0));
419
+ return () => {
420
+ const index = this.responseInterceptors.indexOf(interceptor);
421
+ if (index > -1) {
422
+ this.responseInterceptors.splice(index, 1);
423
+ }
424
+ };
425
+ }
802
426
  /**
803
427
  * 克隆客户端
804
428
  * 注意:克隆会创建新的拦截器数组,但共享同一个适配器实例
805
429
  * 如需独立的适配器,请使用 new HttpClient() 创建新实例
806
430
  */
807
- Object.defineProperty(HttpClient.prototype, "clone", {
808
- enumerable: false,
809
- configurable: true,
810
- writable: true,
811
- value: function () {
812
- var cloned = new HttpClient(this.adapter);
813
- cloned.requestInterceptors = __spreadArray$1([], __read(this.requestInterceptors), false);
814
- cloned.responseInterceptors = __spreadArray$1([], __read(this.responseInterceptors), false);
815
- return cloned;
816
- }
817
- });
431
+ clone() {
432
+ const cloned = new HttpClient(this.adapter);
433
+ cloned.requestInterceptors = [...this.requestInterceptors];
434
+ cloned.responseInterceptors = [...this.responseInterceptors];
435
+ return cloned;
436
+ }
818
437
  /**
819
438
  * 规范化配置
820
439
  */
821
- Object.defineProperty(HttpClient.prototype, "normalizeConfig", {
822
- enumerable: false,
823
- configurable: true,
824
- writable: true,
825
- value: function (config) {
826
- return __assign$4({ method: config.method || (config.data ? exports.HttpMethod.POST : exports.HttpMethod.GET), timeout: config.timeout || DEFAULT_TIMEOUT, headers: config.headers || {} }, config);
827
- }
828
- });
440
+ normalizeConfig(config) {
441
+ return {
442
+ method: config.method || (config.data ? exports.HttpMethod.POST : exports.HttpMethod.GET),
443
+ timeout: config.timeout || DEFAULT_TIMEOUT,
444
+ headers: config.headers || {},
445
+ ...config,
446
+ };
447
+ }
829
448
  /**
830
449
  * 获取适配器
831
450
  */
832
- Object.defineProperty(HttpClient.prototype, "getAdapter", {
833
- enumerable: false,
834
- configurable: true,
835
- writable: true,
836
- value: function () {
837
- return this.adapter;
838
- }
839
- });
451
+ getAdapter() {
452
+ return this.adapter;
453
+ }
840
454
  /**
841
455
  * 处理旧版拦截器的请求(向后兼容)
842
456
  * 此方法被 BeLinkClient 和 LiveClient 共享
843
457
  * @protected 允许子类调用
844
458
  */
845
- Object.defineProperty(HttpClient.prototype, "requestWithLegacyInterceptors", {
846
- enumerable: false,
847
- configurable: true,
848
- writable: true,
849
- value: function (config) {
850
- return __awaiter$3(this, void 0, void 0, function () {
851
- var removeRequestInterceptor, removeResponseInterceptor, response, error_2, err;
852
- var _a;
853
- return __generator$3(this, function (_b) {
854
- switch (_b.label) {
855
- case 0:
856
- removeRequestInterceptor = config.requestInterceptors
857
- ? this.addRequestInterceptor({
858
- name: 'LegacyRequest',
859
- priority: 100,
860
- onRequest: function (ctx) {
861
- var newConfig = config.requestInterceptors(ctx.config);
862
- return __assign$4(__assign$4({}, ctx), { config: newConfig });
863
- },
864
- })
865
- : null;
866
- removeResponseInterceptor = config.responseInterceptors
867
- ? this.addResponseInterceptor({
868
- name: 'LegacyResponse',
869
- priority: 100,
870
- onResponse: function (ctx) { return ctx; },
871
- })
872
- : null;
873
- _b.label = 1;
874
- case 1:
875
- _b.trys.push([1, 3, 4, 5]);
876
- return [4 /*yield*/, this.request(config)];
877
- case 2:
878
- response = _b.sent();
879
- return [2 /*return*/, response];
880
- case 3:
881
- error_2 = _b.sent();
882
- if (config.catchCallback) {
883
- config.catchCallback(error_2);
884
- }
885
- err = error_2;
886
- throw ((_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.data) || error_2;
887
- case 4:
888
- // 清理临时拦截器
889
- removeRequestInterceptor === null || removeRequestInterceptor === void 0 ? void 0 : removeRequestInterceptor();
890
- removeResponseInterceptor === null || removeResponseInterceptor === void 0 ? void 0 : removeResponseInterceptor();
891
- return [7 /*endfinally*/];
892
- case 5: return [2 /*return*/];
893
- }
894
- });
895
- });
459
+ async requestWithLegacyInterceptors(config) {
460
+ // 注册临时拦截器
461
+ const removeRequestInterceptor = config.requestInterceptors
462
+ ? this.addRequestInterceptor({
463
+ name: 'LegacyRequest',
464
+ priority: 100,
465
+ onRequest: (ctx) => {
466
+ const newConfig = config.requestInterceptors(ctx.config);
467
+ return { ...ctx, config: newConfig };
468
+ },
469
+ })
470
+ : null;
471
+ const removeResponseInterceptor = config.responseInterceptors
472
+ ? this.addResponseInterceptor({
473
+ name: 'LegacyResponse',
474
+ priority: 100,
475
+ onResponse: (ctx) => ctx,
476
+ })
477
+ : null;
478
+ try {
479
+ const response = await this.request(config);
480
+ return response;
896
481
  }
897
- });
898
- return HttpClient;
899
- }());
482
+ catch (error) {
483
+ if (config.catchCallback) {
484
+ config.catchCallback(error);
485
+ }
486
+ const err = error;
487
+ throw err?.response?.data || error;
488
+ }
489
+ finally {
490
+ // 清理临时拦截器
491
+ removeRequestInterceptor?.();
492
+ removeResponseInterceptor?.();
493
+ }
494
+ }
495
+ }
900
496
 
901
497
  /**
902
498
  * 默认配置值
903
499
  */
904
- var DEFAULT_CONFIG = {
500
+ const DEFAULT_CONFIG = {
905
501
  mode: 'development',
906
502
  timeout: 8000,
907
503
  encryption: {
@@ -926,151 +522,100 @@ var DEFAULT_CONFIG = {
926
522
  * 配置管理器实现
927
523
  * 单例模式,集中管理所有配置
928
524
  */
929
- var ConfigManager = /** @class */ (function () {
930
- function ConfigManager() {
931
- Object.defineProperty(this, "config", {
932
- enumerable: true,
933
- configurable: true,
934
- writable: true,
935
- value: void 0
936
- });
937
- this.config = __assign$4({}, DEFAULT_CONFIG);
525
+ class ConfigManager {
526
+ constructor() {
527
+ this.config = { ...DEFAULT_CONFIG };
938
528
  this.loadFromEnvironment();
939
529
  }
940
530
  /**
941
531
  * 获取单例实例
942
532
  */
943
- Object.defineProperty(ConfigManager, "getInstance", {
944
- enumerable: false,
945
- configurable: true,
946
- writable: true,
947
- value: function () {
948
- if (!ConfigManager.instance) {
949
- ConfigManager.instance = new ConfigManager();
950
- }
951
- return ConfigManager.instance;
533
+ static getInstance() {
534
+ if (!ConfigManager.instance) {
535
+ ConfigManager.instance = new ConfigManager();
952
536
  }
953
- });
537
+ return ConfigManager.instance;
538
+ }
954
539
  /**
955
540
  * 初始化配置
956
541
  */
957
- Object.defineProperty(ConfigManager.prototype, "init", {
958
- enumerable: false,
959
- configurable: true,
960
- writable: true,
961
- value: function (config) {
962
- this.config = this.mergeConfig(this.config, config);
963
- if (!this.validate()) {
964
- console.warn('[ConfigManager] Configuration validation failed');
965
- }
542
+ init(config) {
543
+ this.config = this.mergeConfig(this.config, config);
544
+ if (!this.validate()) {
545
+ console.warn('[ConfigManager] Configuration validation failed');
966
546
  }
967
- });
547
+ }
968
548
  /**
969
549
  * 获取配置项
970
550
  */
971
- Object.defineProperty(ConfigManager.prototype, "get", {
972
- enumerable: false,
973
- configurable: true,
974
- writable: true,
975
- value: function (key) {
976
- return this.config[key];
977
- }
978
- });
551
+ get(key) {
552
+ return this.config[key];
553
+ }
979
554
  /**
980
555
  * 设置配置项
981
556
  */
982
- Object.defineProperty(ConfigManager.prototype, "set", {
983
- enumerable: false,
984
- configurable: true,
985
- writable: true,
986
- value: function (key, value) {
987
- this.config[key] = value;
988
- }
989
- });
557
+ set(key, value) {
558
+ this.config[key] = value;
559
+ }
990
560
  /**
991
561
  * 获取完整配置
992
562
  */
993
- Object.defineProperty(ConfigManager.prototype, "getAll", {
994
- enumerable: false,
995
- configurable: true,
996
- writable: true,
997
- value: function () {
998
- return Object.freeze(__assign$4({}, this.config));
999
- }
1000
- });
563
+ getAll() {
564
+ return Object.freeze({ ...this.config });
565
+ }
1001
566
  /**
1002
567
  * 验证配置
1003
568
  */
1004
- Object.defineProperty(ConfigManager.prototype, "validate", {
1005
- enumerable: false,
1006
- configurable: true,
1007
- writable: true,
1008
- value: function () {
1009
- if (!this.config.mode) {
1010
- console.error('[ConfigManager] Mode is required');
1011
- return false;
1012
- }
1013
- return true;
569
+ validate() {
570
+ if (!this.config.mode) {
571
+ console.error('[ConfigManager] Mode is required');
572
+ return false;
1014
573
  }
1015
- });
574
+ return true;
575
+ }
1016
576
  /**
1017
577
  * 重置配置
1018
578
  */
1019
- Object.defineProperty(ConfigManager.prototype, "reset", {
1020
- enumerable: false,
1021
- configurable: true,
1022
- writable: true,
1023
- value: function () {
1024
- this.config = __assign$4({}, DEFAULT_CONFIG);
1025
- }
1026
- });
579
+ reset() {
580
+ this.config = { ...DEFAULT_CONFIG };
581
+ }
1027
582
  /**
1028
583
  * 从环境变量加载配置
1029
584
  */
1030
- Object.defineProperty(ConfigManager.prototype, "loadFromEnvironment", {
1031
- enumerable: false,
1032
- configurable: true,
1033
- writable: true,
1034
- value: function () {
1035
- var key = this.getEnvVar('BELINK_ENCRYPTION_KEY');
1036
- var iv = this.getEnvVar('BELINK_ENCRYPTION_IV');
1037
- if (key && iv) {
1038
- this.config.encryption = { key: key, iv: iv };
1039
- }
585
+ loadFromEnvironment() {
586
+ const key = this.getEnvVar('BELINK_ENCRYPTION_KEY');
587
+ const iv = this.getEnvVar('BELINK_ENCRYPTION_IV');
588
+ if (key && iv) {
589
+ this.config.encryption = { key, iv };
1040
590
  }
1041
- });
591
+ }
1042
592
  /**
1043
593
  * 深度合并配置
1044
594
  */
1045
- Object.defineProperty(ConfigManager.prototype, "mergeConfig", {
1046
- enumerable: false,
1047
- configurable: true,
1048
- writable: true,
1049
- value: function (target, source) {
1050
- return __assign$4(__assign$4(__assign$4({}, target), source), { encryption: source.encryption ? __assign$4(__assign$4({}, target.encryption), source.encryption) : target.encryption, timeSync: source.timeSync ? __assign$4(__assign$4({}, target.timeSync), source.timeSync) : target.timeSync, cloudbase: source.cloudbase ? __assign$4(__assign$4({}, target.cloudbase), source.cloudbase) : target.cloudbase });
1051
- }
1052
- });
595
+ mergeConfig(target, source) {
596
+ return {
597
+ ...target,
598
+ ...source,
599
+ encryption: source.encryption ? { ...target.encryption, ...source.encryption } : target.encryption,
600
+ timeSync: source.timeSync ? { ...target.timeSync, ...source.timeSync } : target.timeSync,
601
+ cloudbase: source.cloudbase ? { ...target.cloudbase, ...source.cloudbase } : target.cloudbase,
602
+ };
603
+ }
1053
604
  /**
1054
605
  * 获取环境变量
1055
606
  */
1056
- Object.defineProperty(ConfigManager.prototype, "getEnvVar", {
1057
- enumerable: false,
1058
- configurable: true,
1059
- writable: true,
1060
- value: function (key) {
1061
- // Vite 环境
1062
- if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) }) !== 'undefined' && undefined) {
1063
- return undefined[key];
1064
- }
1065
- // Webpack/Node 环境
1066
- if (typeof process !== 'undefined' && process.env) {
1067
- return process.env[key];
1068
- }
1069
- return undefined;
607
+ getEnvVar(key) {
608
+ // Vite 环境
609
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) }) !== 'undefined' && undefined) {
610
+ return undefined[key];
1070
611
  }
1071
- });
1072
- return ConfigManager;
1073
- }());
612
+ // Webpack/Node 环境
613
+ if (typeof process !== 'undefined' && process.env) {
614
+ return process.env[key];
615
+ }
616
+ return undefined;
617
+ }
618
+ }
1074
619
 
1075
620
  /**
1076
621
  * 检测当前环境
@@ -1078,12 +623,12 @@ var ConfigManager = /** @class */ (function () {
1078
623
  function detectEnvironment() {
1079
624
  // Vite 环境
1080
625
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) }) !== 'undefined' && undefined) {
1081
- var env = undefined.VITE_API_ENV || undefined.MODE;
626
+ const env = undefined.VITE_API_ENV || undefined.MODE;
1082
627
  return normalizeEnv(env);
1083
628
  }
1084
629
  // Webpack/Node 环境
1085
630
  if (typeof process !== 'undefined' && process.env) {
1086
- var env = process.env.API_ENV || process.env.NODE_ENV;
631
+ const env = process.env.API_ENV || process.env.NODE_ENV;
1087
632
  return normalizeEnv(env);
1088
633
  }
1089
634
  console.warn('[EnvUtils] Cannot detect environment, defaulting to "development"');
@@ -1095,7 +640,7 @@ function detectEnvironment() {
1095
640
  function normalizeEnv(env) {
1096
641
  if (!env)
1097
642
  return 'development';
1098
- var normalized = env.toLowerCase();
643
+ const normalized = env.toLowerCase();
1099
644
  if (normalized === 'production' || normalized === 'prod') {
1100
645
  return 'production';
1101
646
  }
@@ -1121,950 +666,604 @@ function isNode() {
1121
666
  * 加密服务实现
1122
667
  * 提供 Token 加密/解密功能
1123
668
  */
1124
- var EncryptionService = /** @class */ (function () {
1125
- function EncryptionService(config, timeSyncService) {
1126
- Object.defineProperty(this, "config", {
1127
- enumerable: true,
1128
- configurable: true,
1129
- writable: true,
1130
- value: void 0
1131
- });
1132
- Object.defineProperty(this, "timeSyncService", {
1133
- enumerable: true,
1134
- configurable: true,
1135
- writable: true,
1136
- value: void 0
1137
- });
1138
- this.config = __assign$4({}, config);
669
+ class EncryptionService {
670
+ constructor(config, timeSyncService) {
671
+ this.config = { ...config };
1139
672
  this.timeSyncService = timeSyncService;
1140
673
  }
1141
674
  /**
1142
675
  * 加密 Token
1143
676
  * 格式: AES(token + "|+|" + timestamp)
1144
677
  */
1145
- Object.defineProperty(EncryptionService.prototype, "encryptToken", {
1146
- enumerable: false,
1147
- configurable: true,
1148
- writable: true,
1149
- value: function (token, timestamp) {
1150
- if (!token) {
1151
- return '';
1152
- }
1153
- var time = timestamp !== null && timestamp !== void 0 ? timestamp : this.getAdjustedTime();
1154
- var data = "".concat(token, "|+|").concat(time);
1155
- var encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(this.config.key), {
1156
- iv: CryptoJS.enc.Utf8.parse(this.config.iv),
1157
- mode: CryptoJS.mode.CBC,
1158
- }).toString();
1159
- return encrypted;
678
+ encryptToken(token, timestamp) {
679
+ if (!token) {
680
+ return '';
1160
681
  }
1161
- });
682
+ const time = timestamp ?? this.getAdjustedTime();
683
+ const data = `${token}|+|${time}`;
684
+ return CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(this.config.key), {
685
+ iv: CryptoJS.enc.Utf8.parse(this.config.iv),
686
+ mode: CryptoJS.mode.CBC,
687
+ }).toString();
688
+ }
1162
689
  /**
1163
690
  * 解密 Token
1164
691
  */
1165
- Object.defineProperty(EncryptionService.prototype, "decryptToken", {
1166
- enumerable: false,
1167
- configurable: true,
1168
- writable: true,
1169
- value: function (encryptedToken) {
1170
- var decrypted = CryptoJS.AES.decrypt(encryptedToken, CryptoJS.enc.Utf8.parse(this.config.key), {
1171
- iv: CryptoJS.enc.Utf8.parse(this.config.iv),
1172
- mode: CryptoJS.mode.CBC,
1173
- }).toString(CryptoJS.enc.Utf8);
1174
- var parts = decrypted.split('|+|');
1175
- return {
1176
- token: parts[0],
1177
- timestamp: parseInt(parts[1], 10),
1178
- };
1179
- }
1180
- });
692
+ decryptToken(encryptedToken) {
693
+ const decrypted = CryptoJS.AES.decrypt(encryptedToken, CryptoJS.enc.Utf8.parse(this.config.key), {
694
+ iv: CryptoJS.enc.Utf8.parse(this.config.iv),
695
+ mode: CryptoJS.mode.CBC,
696
+ }).toString(CryptoJS.enc.Utf8);
697
+ const parts = decrypted.split('|+|');
698
+ return {
699
+ token: parts[0],
700
+ timestamp: parseInt(parts[1], 10),
701
+ };
702
+ }
1181
703
  /**
1182
704
  * 更新加密配置
1183
705
  */
1184
- Object.defineProperty(EncryptionService.prototype, "updateConfig", {
1185
- enumerable: false,
1186
- configurable: true,
1187
- writable: true,
1188
- value: function (config) {
1189
- this.config = __assign$4(__assign$4({}, this.config), config);
1190
- }
1191
- });
706
+ updateConfig(config) {
707
+ this.config = { ...this.config, ...config };
708
+ }
1192
709
  /**
1193
710
  * 获取调整后的时间戳(考虑服务器时间差)
1194
711
  * 优先使用注入的 TimeSyncService
1195
712
  */
1196
- Object.defineProperty(EncryptionService.prototype, "getAdjustedTime", {
1197
- enumerable: false,
1198
- configurable: true,
1199
- writable: true,
1200
- value: function () {
1201
- var currentTime = Date.now();
1202
- // 优先使用注入的 TimeSyncService
1203
- if (this.timeSyncService) {
1204
- var timeDiff = this.timeSyncService.getTimeDiff();
1205
- return timeDiff !== null ? currentTime + timeDiff : currentTime;
1206
- }
1207
- // 降级方案:直接读取 localStorage(向后兼容)
1208
- // 需要环境检查,防止 Node.js 环境崩溃
1209
- if (isBrowser()) {
1210
- var timeDiff = localStorage.getItem(STORAGE_KEYS.TIME_DIFF);
1211
- return timeDiff ? currentTime + Number(timeDiff) : currentTime;
1212
- }
1213
- return currentTime;
713
+ getAdjustedTime() {
714
+ const currentTime = Date.now();
715
+ // 优先使用注入的 TimeSyncService
716
+ if (this.timeSyncService) {
717
+ const timeDiff = this.timeSyncService.getTimeDiff();
718
+ return timeDiff !== null ? currentTime + timeDiff : currentTime;
1214
719
  }
1215
- });
1216
- return EncryptionService;
1217
- }());
720
+ // 降级方案:直接读取 localStorage(向后兼容)
721
+ // 需要环境检查,防止 Node.js 环境崩溃
722
+ if (isBrowser()) {
723
+ const timeDiff = localStorage.getItem(STORAGE_KEYS.TIME_DIFF);
724
+ return timeDiff ? currentTime + Number(timeDiff) : currentTime;
725
+ }
726
+ return currentTime;
727
+ }
728
+ }
1218
729
 
1219
730
  /**
1220
731
  * 时间同步服务
1221
732
  * 负责同步客户端和服务器时间
1222
733
  */
1223
- var TimeSyncService = /** @class */ (function () {
1224
- function TimeSyncService(config, mode) {
1225
- if (mode === void 0) { mode = 'development'; }
1226
- Object.defineProperty(this, "config", {
1227
- enumerable: true,
1228
- configurable: true,
1229
- writable: true,
1230
- value: void 0
1231
- });
1232
- Object.defineProperty(this, "mode", {
1233
- enumerable: true,
1234
- configurable: true,
1235
- writable: true,
1236
- value: void 0
1237
- });
1238
- Object.defineProperty(this, "synced", {
1239
- enumerable: true,
1240
- configurable: true,
1241
- writable: true,
1242
- value: false
1243
- });
734
+ class TimeSyncService {
735
+ constructor(config, mode = 'development') {
1244
736
  this.config = config;
1245
737
  this.mode = mode;
1246
738
  }
1247
739
  /**
1248
740
  * 确保时间已同步
1249
741
  */
1250
- Object.defineProperty(TimeSyncService.prototype, "ensureSync", {
1251
- enumerable: false,
1252
- configurable: true,
1253
- writable: true,
1254
- value: function () {
1255
- return __awaiter$3(this, void 0, void 0, function () {
1256
- var serverTime;
1257
- return __generator$3(this, function (_a) {
1258
- switch (_a.label) {
1259
- case 0:
1260
- if (!this.config.enabled) {
1261
- return [2 /*return*/];
1262
- }
1263
- if (this.synced) {
1264
- return [2 /*return*/];
1265
- }
1266
- if (!isBrowser()) {
1267
- return [2 /*return*/];
1268
- }
1269
- serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
1270
- if (serverTime && serverTime !== 'undefined') {
1271
- this.synced = true;
1272
- return [2 /*return*/];
1273
- }
1274
- return [4 /*yield*/, this.sync()];
1275
- case 1:
1276
- _a.sent();
1277
- return [2 /*return*/];
1278
- }
1279
- });
1280
- });
742
+ async ensureSync() {
743
+ if (!this.config.enabled) {
744
+ return;
1281
745
  }
1282
- });
746
+ if (!isBrowser()) {
747
+ return;
748
+ }
749
+ const serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
750
+ const clientTime = localStorage.getItem(STORAGE_KEYS.CLIENT_TIME);
751
+ const currentTime = Date.now();
752
+ if (serverTime && serverTime !== 'undefined' && clientTime && clientTime !== 'undefined') {
753
+ const diff = Math.abs(Number(clientTime) - currentTime);
754
+ if (diff <= (this.config.syncGapTime || 50 * 1000)) {
755
+ console.log('服务器时间无需同步,差值:', diff);
756
+ return;
757
+ }
758
+ }
759
+ await this.sync();
760
+ }
1283
761
  /**
1284
762
  * 执行时间同步
1285
763
  */
1286
- Object.defineProperty(TimeSyncService.prototype, "sync", {
1287
- enumerable: false,
1288
- configurable: true,
1289
- writable: true,
1290
- value: function () {
1291
- return __awaiter$3(this, void 0, void 0, function () {
1292
- var url, response, res, serverTime, currentTime, timeDiff, error_1;
1293
- return __generator$3(this, function (_a) {
1294
- switch (_a.label) {
1295
- case 0:
1296
- if (!isBrowser()) {
1297
- return [2 /*return*/];
1298
- }
1299
- _a.label = 1;
1300
- case 1:
1301
- _a.trys.push([1, 4, , 5]);
1302
- url = this.getSyncUrl();
1303
- if (!url) {
1304
- console.warn('[TimeSyncService] Sync URL not configured');
1305
- return [2 /*return*/];
1306
- }
1307
- return [4 /*yield*/, fetch(url, { method: 'POST' })];
1308
- case 2:
1309
- response = _a.sent();
1310
- // 检查响应状态
1311
- if (!response.ok) {
1312
- console.error('[TimeSyncService] Sync failed with status:', response.status);
1313
- this.clear();
1314
- return [2 /*return*/];
1315
- }
1316
- return [4 /*yield*/, response.json()];
1317
- case 3:
1318
- res = _a.sent();
1319
- serverTime = res.data;
1320
- if (!serverTime) {
1321
- this.clear();
1322
- return [2 /*return*/];
1323
- }
1324
- currentTime = Date.now();
1325
- timeDiff = serverTime - currentTime;
1326
- localStorage.setItem(STORAGE_KEYS.SERVER_TIME, String(serverTime));
1327
- localStorage.setItem(STORAGE_KEYS.TIME_DIFF, String(timeDiff));
1328
- this.synced = true;
1329
- return [3 /*break*/, 5];
1330
- case 4:
1331
- error_1 = _a.sent();
1332
- console.error('[TimeSyncService] Failed to sync time:', error_1);
1333
- this.clear();
1334
- return [3 /*break*/, 5];
1335
- case 5: return [2 /*return*/];
1336
- }
1337
- });
1338
- });
764
+ async sync() {
765
+ if (!isBrowser()) {
766
+ return;
1339
767
  }
1340
- });
768
+ try {
769
+ console.log('服务器时间无需同步');
770
+ const url = this.getSyncUrl();
771
+ if (!url) {
772
+ console.warn('[TimeSyncService] Sync URL not configured');
773
+ return;
774
+ }
775
+ const response = await fetch(url, { method: 'POST' });
776
+ // 检查响应状态
777
+ if (!response.ok) {
778
+ console.error('[TimeSyncService] Sync failed with status:', response.status);
779
+ this.clear();
780
+ return;
781
+ }
782
+ const res = await response.json();
783
+ const serverTime = res.data;
784
+ if (!serverTime) {
785
+ this.clear();
786
+ return;
787
+ }
788
+ console.log(111111113331312);
789
+ localStorage.setItem(STORAGE_KEYS.SERVER_TIME, String(serverTime));
790
+ localStorage.setItem(STORAGE_KEYS.CLIENT_TIME, String(Date.now()));
791
+ }
792
+ catch (error) {
793
+ console.error('[TimeSyncService] Failed to sync time:', error);
794
+ this.clear();
795
+ }
796
+ }
1341
797
  /**
1342
798
  * 获取服务器时间
1343
799
  */
1344
- Object.defineProperty(TimeSyncService.prototype, "getServerTime", {
1345
- enumerable: false,
1346
- configurable: true,
1347
- writable: true,
1348
- value: function () {
1349
- if (!isBrowser()) {
1350
- return null;
1351
- }
1352
- var serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
1353
- return serverTime ? Number(serverTime) : null;
800
+ getServerTime() {
801
+ if (!isBrowser()) {
802
+ return null;
1354
803
  }
1355
- });
804
+ const serverTime = localStorage.getItem(STORAGE_KEYS.SERVER_TIME);
805
+ return serverTime ? Number(serverTime) : null;
806
+ }
1356
807
  /**
1357
808
  * 获取时间差
1358
809
  */
1359
- Object.defineProperty(TimeSyncService.prototype, "getTimeDiff", {
1360
- enumerable: false,
1361
- configurable: true,
1362
- writable: true,
1363
- value: function () {
1364
- if (!isBrowser()) {
1365
- return null;
1366
- }
1367
- var timeDiff = localStorage.getItem(STORAGE_KEYS.TIME_DIFF);
1368
- return timeDiff ? Number(timeDiff) : null;
810
+ getTimeDiff() {
811
+ if (!isBrowser()) {
812
+ return null;
1369
813
  }
1370
- });
814
+ const serverTime = this.getServerTime();
815
+ return serverTime ? serverTime - Date.now() : null;
816
+ }
1371
817
  /**
1372
818
  * 获取时间同步请求头
1373
819
  */
1374
- Object.defineProperty(TimeSyncService.prototype, "getTimeSyncHeaders", {
1375
- enumerable: false,
1376
- configurable: true,
1377
- writable: true,
1378
- value: function () {
1379
- var headers = {};
1380
- var serverTime = this.getServerTime();
1381
- var timeDiff = this.getTimeDiff();
1382
- if (serverTime) {
1383
- headers['x-belink-serverTime'] = String(serverTime);
1384
- }
1385
- if (timeDiff !== null) {
1386
- headers['x-belink-timeDiff'] = String(timeDiff);
1387
- }
1388
- return headers;
820
+ getTimeSyncHeaders() {
821
+ const headers = {};
822
+ const serverTime = this.getServerTime();
823
+ const timeDiff = this.getTimeDiff();
824
+ if (serverTime) {
825
+ headers['x-belink-serverTime'] = String(serverTime);
1389
826
  }
1390
- });
827
+ if (timeDiff !== null) {
828
+ headers['x-belink-timeDiff'] = String(timeDiff);
829
+ }
830
+ return headers;
831
+ }
1391
832
  /**
1392
833
  * 清理时间同步数据
1393
834
  */
1394
- Object.defineProperty(TimeSyncService.prototype, "clear", {
1395
- enumerable: false,
1396
- configurable: true,
1397
- writable: true,
1398
- value: function () {
1399
- if (isBrowser()) {
1400
- localStorage.removeItem(STORAGE_KEYS.SERVER_TIME);
1401
- localStorage.removeItem(STORAGE_KEYS.TIME_DIFF);
1402
- }
1403
- this.synced = false;
835
+ clear() {
836
+ if (isBrowser()) {
837
+ localStorage.removeItem(STORAGE_KEYS.SERVER_TIME);
838
+ localStorage.removeItem(STORAGE_KEYS.CLIENT_TIME);
839
+ localStorage.removeItem(STORAGE_KEYS.TIME_DIFF);
1404
840
  }
1405
- });
841
+ }
1406
842
  /**
1407
843
  * 更新模式
1408
844
  */
1409
- Object.defineProperty(TimeSyncService.prototype, "setMode", {
1410
- enumerable: false,
1411
- configurable: true,
1412
- writable: true,
1413
- value: function (mode) {
1414
- this.mode = mode;
1415
- }
1416
- });
845
+ setMode(mode) {
846
+ this.mode = mode;
847
+ }
1417
848
  /**
1418
849
  * 获取同步 URL
1419
850
  */
1420
- Object.defineProperty(TimeSyncService.prototype, "getSyncUrl", {
1421
- enumerable: false,
1422
- configurable: true,
1423
- writable: true,
1424
- value: function () {
1425
- if (this.mode === 'production') {
1426
- return this.config.productionUrl || '';
1427
- }
1428
- return this.config.developmentUrl || '';
851
+ getSyncUrl() {
852
+ if (this.mode === 'production') {
853
+ return this.config.productionUrl || '';
1429
854
  }
1430
- });
1431
- return TimeSyncService;
1432
- }());
855
+ return this.config.developmentUrl || '';
856
+ }
857
+ }
1433
858
 
1434
859
  /**
1435
- * Token 拦截器
1436
- * 负责将 Token 加密后注入请求头
1437
- */
1438
- var TokenInterceptor = /** @class */ (function () {
1439
- function TokenInterceptor(tokenProvider, encryptionService, options) {
1440
- Object.defineProperty(this, "name", {
1441
- enumerable: true,
1442
- configurable: true,
1443
- writable: true,
1444
- value: 'TokenInterceptor'
1445
- });
1446
- Object.defineProperty(this, "priority", {
1447
- enumerable: true,
1448
- configurable: true,
1449
- writable: true,
1450
- value: void 0
1451
- });
1452
- Object.defineProperty(this, "tokenProvider", {
1453
- enumerable: true,
1454
- configurable: true,
1455
- writable: true,
1456
- value: void 0
1457
- });
1458
- Object.defineProperty(this, "encryptionService", {
1459
- enumerable: true,
1460
- configurable: true,
1461
- writable: true,
1462
- value: void 0
1463
- });
1464
- Object.defineProperty(this, "headerName", {
1465
- enumerable: true,
1466
- configurable: true,
1467
- writable: true,
1468
- value: void 0
1469
- });
1470
- this.tokenProvider = tokenProvider;
1471
- this.encryptionService = encryptionService;
1472
- this.priority = (options === null || options === void 0 ? void 0 : options.priority) || 0;
1473
- this.headerName = (options === null || options === void 0 ? void 0 : options.headerName) || TOKEN_HEADER;
1474
- }
1475
- Object.defineProperty(TokenInterceptor.prototype, "onRequest", {
1476
- enumerable: false,
1477
- configurable: true,
1478
- writable: true,
1479
- value: function (context) {
1480
- return __awaiter$3(this, void 0, void 0, function () {
1481
- var token, encryptedToken;
1482
- return __generator$3(this, function (_a) {
1483
- token = this.tokenProvider();
1484
- if (token) {
1485
- encryptedToken = this.encryptionService.encryptToken(token);
1486
- if (!context.config.headers) {
1487
- context.config.headers = {};
1488
- }
1489
- context.config.headers[this.headerName] = encryptedToken;
1490
- }
1491
- return [2 /*return*/, context];
1492
- });
1493
- });
1494
- }
1495
- });
1496
- Object.defineProperty(TokenInterceptor.prototype, "onRequestError", {
1497
- enumerable: false,
1498
- configurable: true,
1499
- writable: true,
1500
- value: function (error) {
1501
- return __awaiter$3(this, void 0, void 0, function () {
1502
- return __generator$3(this, function (_a) {
1503
- throw error;
1504
- });
1505
- });
860
+ * Token 拦截器
861
+ * 负责将 Token 加密后注入请求头
862
+ */
863
+ class TokenInterceptor {
864
+ constructor(tokenProvider, encryptionService, options) {
865
+ this.name = 'TokenInterceptor';
866
+ this.tokenProvider = tokenProvider;
867
+ this.encryptionService = encryptionService;
868
+ this.priority = options?.priority || 0;
869
+ this.headerName = options?.headerName || TOKEN_HEADER;
870
+ this.userId = options?.userId || '';
871
+ }
872
+ async onRequest(context) {
873
+ const token = this.tokenProvider();
874
+ if (token) {
875
+ const encryptedToken = this.encryptionService.encryptToken(token);
876
+ if (!context.config.headers) {
877
+ context.config.headers = {};
878
+ }
879
+ context.config.headers[this.headerName] = encryptedToken;
880
+ context.config.headers[USERID_HEADER] = this.userId || '';
1506
881
  }
1507
- });
1508
- return TokenInterceptor;
1509
- }());
882
+ return context;
883
+ }
884
+ async onRequestError(error) {
885
+ throw error;
886
+ }
887
+ }
1510
888
 
1511
889
  /**
1512
890
  * 时间同步拦截器
1513
891
  * 负责同步服务器时间并注入请求头
1514
892
  */
1515
- var TimeInterceptor = /** @class */ (function () {
1516
- function TimeInterceptor(timeSyncService, options) {
1517
- Object.defineProperty(this, "name", {
1518
- enumerable: true,
1519
- configurable: true,
1520
- writable: true,
1521
- value: 'TimeInterceptor'
1522
- });
1523
- Object.defineProperty(this, "priority", {
1524
- enumerable: true,
1525
- configurable: true,
1526
- writable: true,
1527
- value: void 0
1528
- });
1529
- Object.defineProperty(this, "timeSyncService", {
1530
- enumerable: true,
1531
- configurable: true,
1532
- writable: true,
1533
- value: void 0
1534
- });
893
+ class TimeInterceptor {
894
+ constructor(timeSyncService, options) {
895
+ this.name = 'TimeInterceptor';
1535
896
  this.timeSyncService = timeSyncService;
1536
- this.priority = (options === null || options === void 0 ? void 0 : options.priority) || 0;
897
+ this.priority = options?.priority || 0;
1537
898
  }
1538
- Object.defineProperty(TimeInterceptor.prototype, "onRequest", {
1539
- enumerable: false,
1540
- configurable: true,
1541
- writable: true,
1542
- value: function (context) {
1543
- return __awaiter$3(this, void 0, void 0, function () {
1544
- var timeSyncHeaders;
1545
- return __generator$3(this, function (_a) {
1546
- switch (_a.label) {
1547
- case 0:
1548
- // 确保时间已同步
1549
- return [4 /*yield*/, this.timeSyncService.ensureSync()];
1550
- case 1:
1551
- // 确保时间已同步
1552
- _a.sent();
1553
- timeSyncHeaders = this.timeSyncService.getTimeSyncHeaders();
1554
- if (!context.config.headers) {
1555
- context.config.headers = {};
1556
- }
1557
- Object.assign(context.config.headers, timeSyncHeaders);
1558
- return [2 /*return*/, context];
1559
- }
1560
- });
1561
- });
1562
- }
1563
- });
1564
- Object.defineProperty(TimeInterceptor.prototype, "onRequestError", {
1565
- enumerable: false,
1566
- configurable: true,
1567
- writable: true,
1568
- value: function (error) {
1569
- return __awaiter$3(this, void 0, void 0, function () {
1570
- return __generator$3(this, function (_a) {
1571
- throw error;
1572
- });
1573
- });
899
+ async onRequest(context) {
900
+ // 确保时间已同步
901
+ await this.timeSyncService.ensureSync();
902
+ // 获取时间同步头
903
+ const timeSyncHeaders = this.timeSyncService.getTimeSyncHeaders();
904
+ if (!context.config.headers) {
905
+ context.config.headers = {};
1574
906
  }
1575
- });
1576
- return TimeInterceptor;
1577
- }());
907
+ Object.assign(context.config.headers, timeSyncHeaders);
908
+ return context;
909
+ }
910
+ async onRequestError(error) {
911
+ throw error;
912
+ }
913
+ }
1578
914
 
1579
915
  /**
1580
916
  * 认证拦截器
1581
917
  * 负责处理 401 未授权响应
1582
918
  */
1583
- var AuthInterceptor = /** @class */ (function () {
1584
- function AuthInterceptor(configManager, timeSyncService, options) {
1585
- Object.defineProperty(this, "name", {
1586
- enumerable: true,
1587
- configurable: true,
1588
- writable: true,
1589
- value: 'AuthInterceptor'
1590
- });
1591
- Object.defineProperty(this, "priority", {
1592
- enumerable: true,
1593
- configurable: true,
1594
- writable: true,
1595
- value: void 0
1596
- });
1597
- Object.defineProperty(this, "configManager", {
1598
- enumerable: true,
1599
- configurable: true,
1600
- writable: true,
1601
- value: void 0
1602
- });
1603
- Object.defineProperty(this, "timeSyncService", {
1604
- enumerable: true,
1605
- configurable: true,
1606
- writable: true,
1607
- value: void 0
1608
- });
919
+ class AuthInterceptor {
920
+ constructor(configManager, timeSyncService, options) {
921
+ this.name = 'AuthInterceptor';
1609
922
  this.configManager = configManager;
1610
923
  this.timeSyncService = timeSyncService;
1611
- this.priority = (options === null || options === void 0 ? void 0 : options.priority) || 0;
924
+ this.priority = options?.priority || 0;
1612
925
  }
1613
- Object.defineProperty(AuthInterceptor.prototype, "onResponse", {
1614
- enumerable: false,
1615
- configurable: true,
1616
- writable: true,
1617
- value: function (context) {
1618
- return __awaiter$3(this, void 0, void 0, function () {
1619
- return __generator$3(this, function (_a) {
1620
- return [2 /*return*/, context];
1621
- });
1622
- });
1623
- }
1624
- });
1625
- Object.defineProperty(AuthInterceptor.prototype, "onResponseError", {
1626
- enumerable: false,
1627
- configurable: true,
1628
- writable: true,
1629
- value: function (error) {
1630
- return __awaiter$3(this, void 0, void 0, function () {
1631
- var status, loginPath;
1632
- return __generator$3(this, function (_a) {
1633
- status = error.status;
1634
- if (status === 401) {
1635
- // 清理时间同步数据
1636
- this.timeSyncService.clear();
1637
- loginPath = this.configManager.get('loginPath');
1638
- if (typeof loginPath === 'string') {
1639
- if (typeof window !== 'undefined') {
1640
- window.location.replace(loginPath);
1641
- }
1642
- }
1643
- else if (typeof loginPath === 'function') {
1644
- loginPath();
1645
- }
1646
- throw new AuthError('Unauthorized', error instanceof Error ? error : undefined);
1647
- }
1648
- throw error;
1649
- });
1650
- });
926
+ async onResponse(context) {
927
+ return context;
928
+ }
929
+ async onResponseError(error) {
930
+ const status = error.status;
931
+ if (status === 401) {
932
+ // 清理时间同步数据
933
+ this.timeSyncService.clear();
934
+ const loginPath = this.configManager.get('loginPath');
935
+ if (typeof loginPath === 'string') {
936
+ if (typeof window !== 'undefined') {
937
+ window.location.replace(loginPath);
938
+ }
939
+ }
940
+ else if (typeof loginPath === 'function') {
941
+ loginPath();
942
+ }
943
+ throw new AuthError('Unauthorized', error instanceof Error ? error : undefined);
1651
944
  }
1652
- });
1653
- return AuthInterceptor;
1654
- }());
945
+ throw error;
946
+ }
947
+ }
1655
948
 
1656
949
  /**
1657
950
  * BeLink 业务请求客户端
1658
951
  * 提供完整的认证、加密、时间同步等企业级功能
1659
952
  */
1660
- var BeLinkClient = /** @class */ (function (_super) {
1661
- __extends$1(BeLinkClient, _super);
1662
- function BeLinkClient() {
1663
- var _this = _super.call(this) || this;
1664
- Object.defineProperty(_this, "configManager", {
1665
- enumerable: true,
1666
- configurable: true,
1667
- writable: true,
1668
- value: void 0
1669
- });
1670
- Object.defineProperty(_this, "encryptionService", {
1671
- enumerable: true,
1672
- configurable: true,
1673
- writable: true,
1674
- value: void 0
1675
- });
1676
- Object.defineProperty(_this, "timeSyncService", {
1677
- enumerable: true,
1678
- configurable: true,
1679
- writable: true,
1680
- value: void 0
1681
- });
1682
- Object.defineProperty(_this, "token", {
1683
- enumerable: true,
1684
- configurable: true,
1685
- writable: true,
1686
- value: null
1687
- });
1688
- Object.defineProperty(_this, "initialized", {
1689
- enumerable: true,
1690
- configurable: true,
1691
- writable: true,
1692
- value: false
1693
- });
1694
- Object.defineProperty(_this, "tokenListenerCleanup", {
1695
- enumerable: true,
1696
- configurable: true,
1697
- writable: true,
1698
- value: null
1699
- });
1700
- Object.defineProperty(_this, "tokenHeaderName", {
1701
- enumerable: true,
1702
- configurable: true,
1703
- writable: true,
1704
- value: TOKEN_HEADER
1705
- });
1706
- Object.defineProperty(_this, "tokenStorageKey", {
1707
- enumerable: true,
1708
- configurable: true,
1709
- writable: true,
1710
- value: STORAGE_KEYS.TOKEN
1711
- });
1712
- _this.configManager = ConfigManager.getInstance();
953
+ class BeLinkClient extends HttpClient {
954
+ constructor() {
955
+ super();
956
+ this.token = null;
957
+ this.initialized = false;
958
+ this.tokenListenerCleanup = null;
959
+ this.tokenHeaderName = TOKEN_HEADER;
960
+ this.tokenStorageKey = STORAGE_KEYS.TOKEN;
961
+ this.configManager = ConfigManager.getInstance();
1713
962
  // 先初始化 timeSyncService
1714
- _this.timeSyncService = new TimeSyncService(_this.configManager.get('timeSync') || { enabled: true }, _this.configManager.get('mode'));
963
+ this.timeSyncService = new TimeSyncService(this.configManager.get('timeSync') || { enabled: true }, this.configManager.get('mode'));
1715
964
  // 再初始化 encryptionService,注入 timeSyncService
1716
- _this.encryptionService = new EncryptionService(_this.configManager.get('encryption') || { key: '214c!dsf1214c!ds', iv: 'icalqai23cfhgj!s' }, _this.timeSyncService);
1717
- return _this;
965
+ this.encryptionService = new EncryptionService(this.configManager.get('encryption') || { key: '214c!dsf1214c!ds', iv: 'icalqai23cfhgj!s' }, this.timeSyncService);
1718
966
  }
1719
967
  /**
1720
968
  * 初始化客户端
1721
969
  */
1722
- Object.defineProperty(BeLinkClient.prototype, "init", {
1723
- enumerable: false,
1724
- configurable: true,
1725
- writable: true,
1726
- value: function (config) {
1727
- this.configManager.init({
1728
- mode: config.mode,
1729
- loginPath: config.loginPath,
1730
- baseUrl: config.baseUrl,
1731
- tokenHeaderName: config.tokenHeaderName,
1732
- tokenStorageKey: config.tokenStorageKey,
1733
- });
1734
- // 更新时间同步服务的模式
1735
- this.timeSyncService.setMode(config.mode);
1736
- // 设置 baseUrl
1737
- if (config.baseUrl) {
1738
- this.adapter.setBaseUrl(config.baseUrl);
1739
- }
1740
- // 设置 tokenHeaderName(请求头名称)
1741
- if (config.tokenHeaderName) {
1742
- this.tokenHeaderName = config.tokenHeaderName;
1743
- }
1744
- // 设置 tokenStorageKey(localStorage 存储键名)
1745
- if (config.tokenStorageKey) {
1746
- this.tokenStorageKey = config.tokenStorageKey;
1747
- }
1748
- // 设置默认拦截器
1749
- if (!this.initialized) {
1750
- this.setupDefaultInterceptors();
1751
- this.initialized = true;
1752
- }
970
+ init(config) {
971
+ this.configManager.init({
972
+ mode: config.mode,
973
+ loginPath: config.loginPath,
974
+ baseUrl: config.baseUrl,
975
+ tokenHeaderName: config.tokenHeaderName,
976
+ tokenStorageKey: config.tokenStorageKey,
977
+ });
978
+ // 更新时间同步服务的模式
979
+ this.timeSyncService.setMode(config.mode);
980
+ // 设置 baseUrl
981
+ if (config.baseUrl) {
982
+ this.adapter.setBaseUrl(config.baseUrl);
1753
983
  }
1754
- });
984
+ // 设置 tokenHeaderName(请求头名称)
985
+ if (config.tokenHeaderName) {
986
+ this.tokenHeaderName = config.tokenHeaderName;
987
+ }
988
+ // 设置 tokenStorageKey(localStorage 存储键名)
989
+ if (config.tokenStorageKey) {
990
+ this.tokenStorageKey = config.tokenStorageKey;
991
+ }
992
+ // 设置默认拦截器
993
+ if (!this.initialized) {
994
+ this.setupDefaultInterceptors();
995
+ this.initialized = true;
996
+ }
997
+ }
1755
998
  /**
1756
999
  * 设置 Token
1757
1000
  */
1758
- Object.defineProperty(BeLinkClient.prototype, "setToken", {
1759
- enumerable: false,
1760
- configurable: true,
1761
- writable: true,
1762
- value: function (token) {
1763
- this.token = token;
1764
- }
1765
- });
1001
+ setToken(token) {
1002
+ this.token = token;
1003
+ }
1766
1004
  /**
1767
1005
  * 获取当前 Token
1768
1006
  */
1769
- Object.defineProperty(BeLinkClient.prototype, "getToken", {
1770
- enumerable: false,
1771
- configurable: true,
1772
- writable: true,
1773
- value: function () {
1774
- return this.token;
1775
- }
1776
- });
1007
+ getToken() {
1008
+ return this.token;
1009
+ }
1777
1010
  /**
1778
1011
  * 设置 Token 监听器
1779
1012
  * @returns 清理函数,用于移除监听器
1780
1013
  */
1781
- Object.defineProperty(BeLinkClient.prototype, "setupTokenListener", {
1782
- enumerable: false,
1783
- configurable: true,
1784
- writable: true,
1785
- value: function (tokenKey) {
1786
- var _this = this;
1787
- // 清理之前的监听器
1788
- if (this.tokenListenerCleanup) {
1789
- this.tokenListenerCleanup();
1790
- this.tokenListenerCleanup = null;
1014
+ setupTokenListener(tokenKey) {
1015
+ // 清理之前的监听器
1016
+ if (this.tokenListenerCleanup) {
1017
+ this.tokenListenerCleanup();
1018
+ this.tokenListenerCleanup = null;
1019
+ }
1020
+ // 非浏览器环境返回空操作
1021
+ if (!isBrowser()) {
1022
+ return () => { };
1023
+ }
1024
+ const getToken = () => {
1025
+ if (typeof tokenKey === 'string') {
1026
+ return window.localStorage.getItem(tokenKey);
1791
1027
  }
1792
- // 非浏览器环境返回空操作
1793
- if (!isBrowser()) {
1794
- return function () { };
1028
+ else if (typeof tokenKey === 'function') {
1029
+ return tokenKey();
1795
1030
  }
1796
- var getToken = function () {
1797
- if (typeof tokenKey === 'string') {
1798
- return window.localStorage.getItem(tokenKey);
1799
- }
1800
- else if (typeof tokenKey === 'function') {
1801
- return tokenKey();
1802
- }
1803
- return null;
1804
- };
1805
- var storageHandler = function (event) {
1806
- if (typeof tokenKey === 'string' && event.key === tokenKey) {
1807
- if (event.newValue) {
1808
- _this.setToken(event.newValue);
1809
- }
1031
+ return null;
1032
+ };
1033
+ const storageHandler = (event) => {
1034
+ if (typeof tokenKey === 'string' && event.key === tokenKey) {
1035
+ if (event.newValue) {
1036
+ this.setToken(event.newValue);
1810
1037
  }
1811
- if (typeof tokenKey === 'function') {
1812
- var token_1 = tokenKey();
1813
- if (token_1) {
1814
- _this.setToken(token_1);
1815
- }
1038
+ }
1039
+ if (typeof tokenKey === 'function') {
1040
+ const token = tokenKey();
1041
+ if (token) {
1042
+ this.setToken(token);
1816
1043
  }
1817
- };
1818
- window.addEventListener('storage', storageHandler);
1819
- // 初始化时获取 token
1820
- var token = getToken();
1821
- if (token) {
1822
- this.setToken(token);
1823
1044
  }
1824
- // 创建并存储清理函数
1825
- var cleanup = function () {
1826
- window.removeEventListener('storage', storageHandler);
1827
- };
1828
- this.tokenListenerCleanup = cleanup;
1829
- return cleanup;
1045
+ };
1046
+ window.addEventListener('storage', storageHandler);
1047
+ // 初始化时获取 token
1048
+ const token = getToken();
1049
+ if (token) {
1050
+ this.setToken(token);
1830
1051
  }
1831
- });
1052
+ // 创建并存储清理函数
1053
+ const cleanup = () => {
1054
+ window.removeEventListener('storage', storageHandler);
1055
+ };
1056
+ this.tokenListenerCleanup = cleanup;
1057
+ return cleanup;
1058
+ }
1832
1059
  /**
1833
1060
  * 设置全局拦截器(向后兼容)
1834
1061
  */
1835
- Object.defineProperty(BeLinkClient.prototype, "setupInterceptors", {
1836
- enumerable: false,
1837
- configurable: true,
1838
- writable: true,
1839
- value: function () {
1840
- // 已在 init 中自动设置
1841
- }
1842
- });
1062
+ setupInterceptors() {
1063
+ // 已在 init 中自动设置
1064
+ }
1843
1065
  /**
1844
1066
  * 设置认证回调(向后兼容)
1845
1067
  */
1846
- Object.defineProperty(BeLinkClient.prototype, "setupAuthorizationCallback", {
1847
- enumerable: false,
1848
- configurable: true,
1849
- writable: true,
1850
- value: function (path) {
1851
- this.configManager.set('loginPath', path);
1852
- }
1853
- });
1068
+ setupAuthorizationCallback(path) {
1069
+ this.configManager.set('loginPath', path);
1070
+ }
1854
1071
  /**
1855
1072
  * 清除请求时间
1856
1073
  */
1857
- Object.defineProperty(BeLinkClient.prototype, "removeRequestTime", {
1858
- enumerable: false,
1859
- configurable: true,
1860
- writable: true,
1861
- value: function () {
1862
- return __awaiter$3(this, void 0, void 0, function () {
1863
- return __generator$3(this, function (_a) {
1864
- this.timeSyncService.clear();
1865
- return [2 /*return*/];
1866
- });
1867
- });
1868
- }
1869
- });
1074
+ async removeRequestTime() {
1075
+ this.timeSyncService.clear();
1076
+ }
1870
1077
  /**
1871
1078
  * @deprecated 请使用 removeRequestTime(修正拼写后的版本)
1872
1079
  * 清除请求时间(向后兼容)
1873
1080
  */
1874
- Object.defineProperty(BeLinkClient.prototype, "removeReqeustTime", {
1875
- enumerable: false,
1876
- configurable: true,
1877
- writable: true,
1878
- value: function () {
1879
- return __awaiter$3(this, void 0, void 0, function () {
1880
- return __generator$3(this, function (_a) {
1881
- return [2 /*return*/, this.removeRequestTime()];
1882
- });
1883
- });
1884
- }
1885
- });
1081
+ async removeReqeustTime() {
1082
+ return this.removeRequestTime();
1083
+ }
1886
1084
  /**
1887
1085
  * 设置请求时间
1888
1086
  */
1889
- Object.defineProperty(BeLinkClient.prototype, "setupRequestTime", {
1890
- enumerable: false,
1891
- configurable: true,
1892
- writable: true,
1893
- value: function (config) {
1894
- return __awaiter$3(this, void 0, void 0, function () {
1895
- var headers;
1896
- return __generator$3(this, function (_a) {
1897
- switch (_a.label) {
1898
- case 0: return [4 /*yield*/, this.timeSyncService.ensureSync()];
1899
- case 1:
1900
- _a.sent();
1901
- headers = this.timeSyncService.getTimeSyncHeaders();
1902
- if (!config.headers) {
1903
- config.headers = {};
1904
- }
1905
- Object.assign(config.headers, headers);
1906
- return [2 /*return*/];
1907
- }
1908
- });
1909
- });
1087
+ async setupRequestTime(config) {
1088
+ await this.timeSyncService.ensureSync();
1089
+ const headers = this.timeSyncService.getTimeSyncHeaders();
1090
+ if (!config.headers) {
1091
+ config.headers = {};
1910
1092
  }
1911
- });
1093
+ Object.assign(config.headers, headers);
1094
+ }
1912
1095
  /**
1913
1096
  * @deprecated 请使用 setupRequestTime(修正拼写后的版本)
1914
1097
  * 设置请求时间(向后兼容)
1915
1098
  */
1916
- Object.defineProperty(BeLinkClient.prototype, "setupReqeustTime", {
1917
- enumerable: false,
1918
- configurable: true,
1919
- writable: true,
1920
- value: function (config) {
1921
- return __awaiter$3(this, void 0, void 0, function () {
1922
- return __generator$3(this, function (_a) {
1923
- return [2 /*return*/, this.setupRequestTime(config)];
1924
- });
1925
- });
1926
- }
1927
- });
1099
+ async setupReqeustTime(config) {
1100
+ return this.setupRequestTime(config);
1101
+ }
1928
1102
  /**
1929
1103
  * 设置 Token(向后兼容)
1930
1104
  */
1931
- Object.defineProperty(BeLinkClient.prototype, "setupToken", {
1932
- enumerable: false,
1933
- configurable: true,
1934
- writable: true,
1935
- value: function (config) {
1936
- if (!isBrowser()) {
1937
- return;
1938
- }
1939
- var token = localStorage.getItem(this.tokenStorageKey);
1940
- if (token) {
1941
- if (!config.headers) {
1942
- config.headers = {};
1943
- }
1944
- config.headers[this.tokenHeaderName] = this.encryptionService.encryptToken(token);
1105
+ setupToken(config) {
1106
+ if (!isBrowser()) {
1107
+ return;
1108
+ }
1109
+ const token = localStorage.getItem(this.tokenStorageKey);
1110
+ if (token) {
1111
+ if (!config.headers) {
1112
+ config.headers = {};
1945
1113
  }
1114
+ config.headers[this.tokenHeaderName] = this.encryptionService.encryptToken(token);
1946
1115
  }
1947
- });
1116
+ }
1948
1117
  /**
1949
1118
  * 重写请求方法(向后兼容旧版 API)
1950
1119
  */
1951
- Object.defineProperty(BeLinkClient.prototype, "request", {
1952
- enumerable: false,
1953
- configurable: true,
1954
- writable: true,
1955
- value: function (config) {
1956
- return __awaiter$3(this, void 0, void 0, function () {
1957
- return __generator$3(this, function (_a) {
1958
- // 处理 customToken
1959
- if (config.customToken) {
1960
- this.setToken(config.customToken);
1961
- }
1962
- // 处理旧版拦截器配置(使用基类的共享方法)
1963
- if (config.requestInterceptors || config.responseInterceptors) {
1964
- return [2 /*return*/, this.requestWithLegacyInterceptors(config)];
1965
- }
1966
- return [2 /*return*/, _super.prototype.request.call(this, config)];
1967
- });
1968
- });
1120
+ async request(config) {
1121
+ // 处理 customToken
1122
+ if (config.customToken) {
1123
+ this.setToken(config.customToken);
1969
1124
  }
1970
- });
1125
+ // 处理旧版拦截器配置(使用基类的共享方法)
1126
+ if (config.requestInterceptors || config.responseInterceptors) {
1127
+ return this.requestWithLegacyInterceptors(config);
1128
+ }
1129
+ return super.request(config);
1130
+ }
1971
1131
  /**
1972
1132
  * 设置默认拦截器
1973
1133
  */
1974
- Object.defineProperty(BeLinkClient.prototype, "setupDefaultInterceptors", {
1975
- enumerable: false,
1976
- configurable: true,
1977
- writable: true,
1978
- value: function () {
1979
- var _this = this;
1980
- // 时间同步拦截器
1981
- this.addRequestInterceptor(new TimeInterceptor(this.timeSyncService, {
1982
- priority: 1,
1983
- }));
1984
- // Token 拦截器
1985
- this.addRequestInterceptor(new TokenInterceptor(function () { return _this.token || localStorage.getItem(_this.tokenStorageKey); }, this.encryptionService, {
1986
- priority: 2,
1987
- headerName: this.tokenHeaderName,
1988
- }));
1989
- // 认证拦截器(处理 401)
1990
- this.addResponseInterceptor(new AuthInterceptor(this.configManager, this.timeSyncService, {
1991
- priority: 1,
1992
- }));
1993
- }
1994
- });
1995
- return BeLinkClient;
1996
- }(HttpClient));
1134
+ setupDefaultInterceptors() {
1135
+ // 时间同步拦截器
1136
+ this.addRequestInterceptor(new TimeInterceptor(this.timeSyncService, {
1137
+ priority: 1,
1138
+ }));
1139
+ // Token 拦截器
1140
+ this.addRequestInterceptor(new TokenInterceptor(() => this.token || localStorage.getItem(this.tokenStorageKey), this.encryptionService, {
1141
+ priority: 2,
1142
+ headerName: this.tokenHeaderName,
1143
+ }));
1144
+ // 认证拦截器(处理 401)
1145
+ this.addResponseInterceptor(new AuthInterceptor(this.configManager, this.timeSyncService, {
1146
+ priority: 1,
1147
+ }));
1148
+ }
1149
+ }
1997
1150
 
1998
1151
  // 创建并导出单例实例
1999
- var beLinkRequest = new BeLinkClient();
1152
+ const beLinkRequest = new BeLinkClient();
2000
1153
 
2001
1154
  /**
2002
- * BeLink 直播请求客户端
2003
- * 简化版客户端,无认证逻辑
1155
+ * LiveClient 业务请求客户端
1156
+ * 提供完整的认证、加密、时间同步等企业级功能
2004
1157
  */
2005
- var LiveClient = /** @class */ (function (_super) {
2006
- __extends$1(LiveClient, _super);
2007
- function LiveClient() {
2008
- var _this = _super.call(this) || this;
2009
- Object.defineProperty(_this, "tokenHeaderName", {
2010
- enumerable: true,
2011
- configurable: true,
2012
- writable: true,
2013
- value: TOKEN_HEADER
2014
- });
2015
- return _this;
1158
+ class LiveClient extends HttpClient {
1159
+ constructor() {
1160
+ super();
1161
+ this.token = '';
1162
+ this.userId = '';
1163
+ this.initialized = false;
1164
+ this.tokenHeaderName = TOKEN_HEADER;
1165
+ this.tokenStorageKey = STORAGE_KEYS.TOKEN;
1166
+ this.configManager = ConfigManager.getInstance();
1167
+ // 先初始化 timeSyncService
1168
+ this.timeSyncService = new TimeSyncService(this.configManager.get('timeSync') || { enabled: true }, this.configManager.get('mode'));
1169
+ // 再初始化 encryptionService,注入 timeSyncService
1170
+ this.encryptionService = new EncryptionService(this.configManager.get('encryption') || { key: '214c!dsf1214c!ds', iv: 'icalqai23cfhgj!s' }, this.timeSyncService);
2016
1171
  }
2017
1172
  /**
2018
1173
  * 初始化客户端
2019
1174
  */
2020
- Object.defineProperty(LiveClient.prototype, "init", {
2021
- enumerable: false,
2022
- configurable: true,
2023
- writable: true,
2024
- value: function (config) {
2025
- if (config.baseUrl) {
2026
- this.adapter.setBaseUrl(config.baseUrl);
2027
- }
2028
- if (config.tokenHeaderName) {
2029
- this.tokenHeaderName = config.tokenHeaderName;
2030
- }
1175
+ init(config) {
1176
+ this.configManager.init({
1177
+ mode: config.mode,
1178
+ baseUrl: config.baseUrl,
1179
+ timeSync: config.timeSyncConfig,
1180
+ encryption: config.encryption,
1181
+ tokenHeaderName: config.tokenHeaderName,
1182
+ tokenStorageKey: config.tokenStorageKey,
1183
+ });
1184
+ // 更新时间同步服务的模式
1185
+ this.timeSyncService.setMode(config.mode);
1186
+ // 设置 baseUrl
1187
+ if (config.baseUrl) {
1188
+ this.adapter.setBaseUrl(config.baseUrl);
2031
1189
  }
2032
- });
1190
+ // 设置 tokenHeaderName(请求头名称)
1191
+ if (config.tokenHeaderName) {
1192
+ this.tokenHeaderName = config.tokenHeaderName;
1193
+ }
1194
+ // 设置 tokenStorageKey(localStorage 存储键名)
1195
+ if (config.tokenStorageKey) {
1196
+ this.tokenStorageKey = config.tokenStorageKey;
1197
+ }
1198
+ if (config.token) {
1199
+ this.token = config.token;
1200
+ }
1201
+ if (config.userId) {
1202
+ this.userId = config.userId;
1203
+ }
1204
+ // 设置默认拦截器
1205
+ if (!this.initialized) {
1206
+ this.setupDefaultInterceptors();
1207
+ this.initialized = true;
1208
+ }
1209
+ }
1210
+ setUserId(userId) {
1211
+ this.userId = userId;
1212
+ }
2033
1213
  /**
2034
- * 获取 Token 请求头名称
1214
+ * 获取当前 Token
2035
1215
  */
2036
- Object.defineProperty(LiveClient.prototype, "getTokenHeaderName", {
2037
- enumerable: false,
2038
- configurable: true,
2039
- writable: true,
2040
- value: function () {
2041
- return this.tokenHeaderName;
1216
+ getToken() {
1217
+ return this.token;
1218
+ }
1219
+ /**
1220
+ * 清除请求时间
1221
+ */
1222
+ async removeRequestTime() {
1223
+ this.timeSyncService.clear();
1224
+ }
1225
+ /**
1226
+ * 设置请求时间
1227
+ */
1228
+ async setupRequestTime(config) {
1229
+ await this.timeSyncService.ensureSync();
1230
+ const headers = this.timeSyncService.getTimeSyncHeaders();
1231
+ if (!config.headers) {
1232
+ config.headers = {};
2042
1233
  }
2043
- });
1234
+ Object.assign(config.headers, headers);
1235
+ }
1236
+ /**
1237
+ * 设置默认拦截器
1238
+ */
1239
+ setupDefaultInterceptors() {
1240
+ // 时间同步拦截器
1241
+ this.addRequestInterceptor(new TimeInterceptor(this.timeSyncService, { priority: 1 }));
1242
+ // Token 拦截器
1243
+ if (this.encryptionService) {
1244
+ this.addRequestInterceptor(new TokenInterceptor(() => this.token || localStorage.getItem(this.tokenStorageKey), this.encryptionService, {
1245
+ priority: 2,
1246
+ headerName: this.tokenHeaderName,
1247
+ userId: this.userId,
1248
+ }));
1249
+ }
1250
+ // 认证拦截器(处理 401)
1251
+ this.addResponseInterceptor(new AuthInterceptor(this.configManager, this.timeSyncService, { priority: 1 }));
1252
+ }
2044
1253
  /**
2045
1254
  * 重写请求方法(向后兼容旧版 API)
2046
1255
  */
2047
- Object.defineProperty(LiveClient.prototype, "request", {
2048
- enumerable: false,
2049
- configurable: true,
2050
- writable: true,
2051
- value: function (config) {
2052
- return __awaiter$3(this, void 0, void 0, function () {
2053
- return __generator$3(this, function (_a) {
2054
- // 处理旧版拦截器配置(使用基类的共享方法)
2055
- if (config.requestInterceptors || config.responseInterceptors) {
2056
- return [2 /*return*/, this.requestWithLegacyInterceptors(config)];
2057
- }
2058
- return [2 /*return*/, _super.prototype.request.call(this, config)];
2059
- });
2060
- });
1256
+ async request(config) {
1257
+ // 处理旧版拦截器配置(使用基类的共享方法)
1258
+ if (config.requestInterceptors || config.responseInterceptors) {
1259
+ return this.requestWithLegacyInterceptors(config);
2061
1260
  }
2062
- });
2063
- return LiveClient;
2064
- }(HttpClient));
1261
+ return super.request(config);
1262
+ }
1263
+ }
2065
1264
 
2066
1265
  // 创建并导出单例实例
2067
- var beLinkLiveRequest = new LiveClient();
1266
+ const beLinkLiveRequest = new LiveClient();
2068
1267
 
2069
1268
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2070
1269
 
@@ -6144,167 +5343,111 @@ catch (e) { }
6144
5343
  * 用户信息服务
6145
5344
  * 单例模式,用于存储和获取当前用户信息
6146
5345
  */
6147
- var UserInfoService = /** @class */ (function () {
6148
- function UserInfoService() {
6149
- Object.defineProperty(this, "userInfo", {
6150
- enumerable: true,
6151
- configurable: true,
6152
- writable: true,
6153
- value: {
6154
- name: '',
6155
- }
6156
- });
5346
+ class UserInfoService {
5347
+ constructor() {
5348
+ this.userInfo = {
5349
+ name: '',
5350
+ };
6157
5351
  }
6158
5352
  /**
6159
5353
  * 初始化用户信息
6160
5354
  */
6161
- Object.defineProperty(UserInfoService.prototype, "init", {
6162
- enumerable: false,
6163
- configurable: true,
6164
- writable: true,
6165
- value: function (userInfo) {
6166
- this.userInfo = userInfo || { name: '' };
6167
- }
6168
- });
5355
+ init(userInfo) {
5356
+ this.userInfo = userInfo || { name: '' };
5357
+ }
6169
5358
  /**
6170
5359
  * 获取用户信息
6171
5360
  */
6172
- Object.defineProperty(UserInfoService.prototype, "getParams", {
6173
- enumerable: false,
6174
- configurable: true,
6175
- writable: true,
6176
- value: function () {
6177
- return this.userInfo;
6178
- }
6179
- });
5361
+ getParams() {
5362
+ return this.userInfo;
5363
+ }
6180
5364
  /**
6181
5365
  * 更新用户信息
6182
5366
  */
6183
- Object.defineProperty(UserInfoService.prototype, "update", {
6184
- enumerable: false,
6185
- configurable: true,
6186
- writable: true,
6187
- value: function (userInfo) {
6188
- this.userInfo = __assign$4(__assign$4({}, this.userInfo), userInfo);
6189
- }
6190
- });
5367
+ update(userInfo) {
5368
+ this.userInfo = { ...this.userInfo, ...userInfo };
5369
+ }
6191
5370
  /**
6192
5371
  * 清除用户信息
6193
5372
  */
6194
- Object.defineProperty(UserInfoService.prototype, "clear", {
6195
- enumerable: false,
6196
- configurable: true,
6197
- writable: true,
6198
- value: function () {
6199
- this.userInfo = { name: '' };
6200
- }
6201
- });
6202
- return UserInfoService;
6203
- }());
5373
+ clear() {
5374
+ this.userInfo = { name: '' };
5375
+ }
5376
+ }
6204
5377
  // 导出单例实例
6205
- var beLinkUserInfo = new UserInfoService();
5378
+ const beLinkUserInfo = new UserInfoService();
6206
5379
 
6207
5380
  /**
6208
5381
  * 云函数客户端
6209
5382
  * 封装腾讯云 CloudBase SDK
6210
5383
  */
6211
- var CloudFunctionClient = /** @class */ (function () {
6212
- function CloudFunctionClient() {
6213
- Object.defineProperty(this, "app", {
6214
- enumerable: true,
6215
- configurable: true,
6216
- writable: true,
6217
- value: null
6218
- });
5384
+ class CloudFunctionClient {
5385
+ constructor() {
5386
+ this.app = null;
6219
5387
  }
6220
5388
  /**
6221
5389
  * 初始化 CloudBase App
6222
5390
  */
6223
- Object.defineProperty(CloudFunctionClient.prototype, "initApp", {
6224
- enumerable: false,
6225
- configurable: true,
6226
- writable: true,
6227
- value: function () {
6228
- if (this.app) {
6229
- return this.app;
6230
- }
6231
- var configManager = ConfigManager.getInstance();
6232
- var cloudbaseConfig = configManager.get('cloudbase');
6233
- var env = detectEnvironment();
6234
- var envId = (cloudbaseConfig === null || cloudbaseConfig === void 0 ? void 0 : cloudbaseConfig[env]) || 'dev-1gpp53ju3ceb46c7';
6235
- var region = (cloudbaseConfig === null || cloudbaseConfig === void 0 ? void 0 : cloudbaseConfig.region) || 'ap-shanghai';
6236
- var timeout = (cloudbaseConfig === null || cloudbaseConfig === void 0 ? void 0 : cloudbaseConfig.timeout) || 60000;
6237
- var options = {
6238
- region: region,
6239
- env: envId,
6240
- timeout: timeout,
6241
- };
6242
- this.app = cloudbase.init(options);
5391
+ initApp() {
5392
+ if (this.app) {
6243
5393
  return this.app;
6244
5394
  }
6245
- });
5395
+ const configManager = ConfigManager.getInstance();
5396
+ const cloudbaseConfig = configManager.get('cloudbase');
5397
+ const env = detectEnvironment();
5398
+ const envId = cloudbaseConfig?.[env] || 'dev-1gpp53ju3ceb46c7';
5399
+ const region = cloudbaseConfig?.region || 'ap-shanghai';
5400
+ const timeout = cloudbaseConfig?.timeout || 60000;
5401
+ const options = {
5402
+ region,
5403
+ env: envId,
5404
+ timeout,
5405
+ };
5406
+ this.app = cloudbase.init(options);
5407
+ return this.app;
5408
+ }
6246
5409
  /**
6247
5410
  * 调用云函数
6248
5411
  */
6249
- Object.defineProperty(CloudFunctionClient.prototype, "call", {
6250
- enumerable: false,
6251
- configurable: true,
6252
- writable: true,
6253
- value: function (params) {
6254
- return __awaiter$3(this, void 0, void 0, function () {
6255
- var app, data, callParams, result;
6256
- return __generator$3(this, function (_a) {
6257
- switch (_a.label) {
6258
- case 0:
6259
- app = this.initApp();
6260
- data = __assign$4({}, params.data);
6261
- // 请求拦截:自动注入用户信息
6262
- if (!data.operateUser) {
6263
- data.operateUser = __assign$4({}, beLinkUserInfo.getParams());
6264
- }
6265
- callParams = __assign$4(__assign$4({}, params), { data: data });
6266
- return [4 /*yield*/, app.callFunction(callParams)];
6267
- case 1:
6268
- result = _a.sent();
6269
- // 响应拦截
6270
- return [2 /*return*/, new Promise(function (resolve, reject) {
6271
- var _a;
6272
- if (!((_a = result.result) === null || _a === void 0 ? void 0 : _a.success)) {
6273
- reject(result.result);
6274
- }
6275
- else {
6276
- resolve(result.result.data);
6277
- }
6278
- })];
6279
- }
6280
- });
6281
- });
5412
+ async call(params) {
5413
+ const app = this.initApp();
5414
+ // 创建数据副本,避免修改原始参数
5415
+ const data = { ...params.data };
5416
+ // 请求拦截:自动注入用户信息
5417
+ if (!data.operateUser) {
5418
+ data.operateUser = {
5419
+ ...beLinkUserInfo.getParams(),
5420
+ };
6282
5421
  }
6283
- });
5422
+ const callParams = {
5423
+ ...params,
5424
+ data,
5425
+ };
5426
+ const result = await app.callFunction(callParams);
5427
+ // 响应拦截
5428
+ return new Promise((resolve, reject) => {
5429
+ if (!result.result?.success) {
5430
+ reject(result.result);
5431
+ }
5432
+ else {
5433
+ resolve(result.result.data);
5434
+ }
5435
+ });
5436
+ }
6284
5437
  /**
6285
5438
  * 重置 App 实例
6286
5439
  */
6287
- Object.defineProperty(CloudFunctionClient.prototype, "reset", {
6288
- enumerable: false,
6289
- configurable: true,
6290
- writable: true,
6291
- value: function () {
6292
- this.app = null;
6293
- }
6294
- });
6295
- return CloudFunctionClient;
6296
- }());
5440
+ reset() {
5441
+ this.app = null;
5442
+ }
5443
+ }
6297
5444
  // 创建单例
6298
- var cloudFunctionClient = new CloudFunctionClient();
5445
+ const cloudFunctionClient = new CloudFunctionClient();
6299
5446
  /**
6300
5447
  * 云函数调用函数(保持原 API 兼容)
6301
5448
  */
6302
- function callFunction(params) {
6303
- return __awaiter$3(this, void 0, void 0, function () {
6304
- return __generator$3(this, function (_a) {
6305
- return [2 /*return*/, cloudFunctionClient.call(params)];
6306
- });
6307
- });
5449
+ async function callFunction(params) {
5450
+ return cloudFunctionClient.call(params);
6308
5451
  }
6309
5452
 
6310
5453
  exports.AuthError = AuthError;