@0xchain/request 1.1.0-beta.7 → 1.1.0-beta.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present 0xchain
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.d.ts CHANGED
@@ -11,5 +11,7 @@ export interface ApiError extends AxiosError {
11
11
  }
12
12
  declare const axiosInstance: import('axios').AxiosInstance;
13
13
  export default axiosInstance;
14
- export type { ApiRequestConfig, Pagination, Status, IResponse, IFilters, IPageRequest, } from './types';
14
+ export { setServerHeaderProvider } from './interceptors/commonHeader';
15
+ export { refreshAccessToken, getCurrentAccessToken } from './tokenRefresh';
16
+ export type { ApiRequestConfig, ServerHeaderProvider, Pagination, Status, IResponse, IFilters, IPageRequest, } from './types';
15
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,KAAK,UAAU,EAAE,MAAM,OAAO,CAAC;AAQ/C,MAAM,WAAW,WAAW,CAAC,CAAC;IAC5B,MAAM,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,EAAE,MAAM,CAAC;KACb,CAAC;IACF,IAAI,EAAE,CAAC,CAAC;CACT;AAED,MAAM,WAAW,QAAS,SAAQ,UAAU;IAC1C,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAGD,QAAA,MAAM,aAAa,+BAYjB,CAAC;AASH,eAAe,aAAa,CAAC;AAE7B,YAAY,EACV,gBAAgB,EAChB,UAAU,EACV,MAAM,EACN,SAAS,EACT,QAAQ,EACR,YAAY,GACb,MAAM,SAAS,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,KAAK,UAAU,EAAE,MAAM,OAAO,CAAC;AAQ/C,MAAM,WAAW,WAAW,CAAC,CAAC;IAC5B,MAAM,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,EAAE,MAAM,CAAC;KACb,CAAC;IACF,IAAI,EAAE,CAAC,CAAC;CACT;AAED,MAAM,WAAW,QAAS,SAAQ,UAAU;IAC1C,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAGD,QAAA,MAAM,aAAa,+BAYjB,CAAC;AASH,eAAe,aAAa,CAAC;AAE7B,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAE3E,YAAY,EACV,gBAAgB,EAChB,oBAAoB,EACpB,UAAU,EACV,MAAM,EACN,SAAS,EACT,QAAQ,EACR,YAAY,GACb,MAAM,SAAS,CAAA"}
package/dist/index.js CHANGED
@@ -1,18 +1,25 @@
1
1
  import axios, { isAxiosError, AxiosError } from "axios";
2
2
  import qs from "qs";
3
3
  import jsCookie from "js-cookie";
4
+ import { envCookieName, getToken, removeAllToken, isTokenExpired } from "@0xchain/token";
4
5
  import { logger } from "@0xchain/logger";
5
- import TokenManager, { isTokenExpired, getToken, removeAllToken } from "@0xchain/token";
6
6
  const isSimplifiedChinese = () => {
7
- return /^(zh-hans|zh-cn|zh-sg|zh-my)$/.test(window == null ? void 0 : window.navigator.language.toLowerCase());
7
+ return /^(zh-hans|zh-cn|zh-sg|zh-my)$/.test(window?.navigator.language.toLowerCase());
8
8
  };
9
9
  const matchSystemLanguage = () => {
10
10
  return isSimplifiedChinese() ? "zh-hans" : "";
11
11
  };
12
+ function isServerRuntime() {
13
+ if (typeof window !== "undefined") {
14
+ return false;
15
+ }
16
+ return true;
17
+ }
12
18
  let httpAgent;
13
19
  let httpsAgent;
14
- function isServerRuntime() {
15
- return typeof window === "undefined" || process.env.IS_SERVER === "true";
20
+ let serverHeaderProvider;
21
+ function setServerHeaderProvider(provider) {
22
+ serverHeaderProvider = provider;
16
23
  }
17
24
  function isEdgeRuntime() {
18
25
  return process.env.NEXT_RUNTIME === "edge" || typeof globalThis.EdgeRuntime !== "undefined";
@@ -22,51 +29,60 @@ function isNodeRuntime() {
22
29
  }
23
30
  function getHeader(config, key) {
24
31
  const h = config.headers;
25
- if ((h == null ? void 0 : h.get) && typeof h.get === "function") return h.get(key);
26
- return h == null ? void 0 : h[key];
32
+ if (h?.get && typeof h.get === "function") return h.get(key);
33
+ return h?.[key];
27
34
  }
28
35
  function setHeader(config, key, value) {
29
36
  const h = config.headers;
30
- if ((h == null ? void 0 : h.set) && typeof h.set === "function") {
37
+ if (h?.set && typeof h.set === "function") {
31
38
  h.set(key, value);
32
39
  } else {
33
40
  h[key] = value;
34
41
  }
35
42
  }
36
43
  async function commonHeader(config) {
37
- var _a, _b;
38
44
  let access_token = "";
39
45
  let language = "";
40
46
  if (isServerRuntime()) {
41
47
  if (isNodeRuntime()) {
42
48
  try {
43
49
  const http = await import("http");
44
- const https = await import("./__vite-browser-external-2Ng8QIWW.js");
45
- const baseURL = config == null ? void 0 : config.baseURL;
50
+ const https = await import("https");
51
+ const baseURL = config?.baseURL;
46
52
  const isHttps = typeof baseURL === "string" ? baseURL.startsWith("https://") : false;
47
- if (!httpAgent && (http == null ? void 0 : http.Agent)) httpAgent = new http.Agent({ keepAlive: true });
48
- if (!httpsAgent && (https == null ? void 0 : https.Agent)) httpsAgent = new https.Agent({ keepAlive: true });
53
+ if (!httpAgent && http?.Agent) httpAgent = new http.Agent({ keepAlive: true });
54
+ if (!httpsAgent && https?.Agent) httpsAgent = new https.Agent({ keepAlive: true });
49
55
  config.httpAgent = isHttps ? void 0 : httpAgent;
50
56
  config.httpsAgent = isHttps ? httpsAgent : void 0;
51
57
  } catch {
52
58
  }
53
59
  }
54
- try {
60
+ setHeader(config, "x-whistle-nohost-env", process.env.NO_HOST_ENV || "ichaingo");
61
+ if (serverHeaderProvider) {
55
62
  const startLanguage = getHeader(config, "Accept-Language");
56
- setHeader(config, "x-whistle-nohost-env", process.env.NO_HOST_ENV || "ichaingo");
57
- const { cookies, headers } = await import("next/headers");
58
- const cookieStore = await cookies();
59
- access_token = ((_a = cookieStore.get("access_token")) == null ? void 0 : _a.value) || "";
60
- const hList = await headers();
61
- language = startLanguage || hList.get("x-next-intl-locale") || "en";
62
- } catch (error) {
63
- console.error("Error accessing cookies in server component:", error);
63
+ try {
64
+ access_token = await serverHeaderProvider.getAccessToken() || "";
65
+ language = startLanguage || await serverHeaderProvider.getLanguage() || "en";
66
+ } catch (error) {
67
+ console.error("Error accessing server headers via provider:", error);
68
+ }
69
+ } else {
70
+ try {
71
+ const startLanguage = getHeader(config, "Accept-Language");
72
+ const { cookies, headers } = await import("next/headers");
73
+ const cookieStore = await cookies();
74
+ access_token = cookieStore.get(envCookieName("access_token"))?.value || "";
75
+ const hList = await headers();
76
+ language = startLanguage || hList.get("x-next-intl-locale") || "en";
77
+ } catch (error) {
78
+ console.error("Error accessing cookies in server component:", error);
79
+ }
64
80
  }
65
81
  } else {
66
- access_token = jsCookie.get("access_token") || "";
82
+ access_token = jsCookie.get(envCookieName("access_token")) || "";
67
83
  language = jsCookie.get("NEXT_LOCALE") || matchSystemLanguage() || "en";
68
84
  }
69
- const isRefreshToken = (_b = config.headers) == null ? void 0 : _b["isRefreshToken"];
85
+ const isRefreshToken = config.headers?.["isRefreshToken"];
70
86
  setHeader(config, "Accept-Language", language);
71
87
  if (access_token && !isRefreshToken) {
72
88
  setHeader(config, "Authorization", `Bearer ${access_token}`);
@@ -78,13 +94,12 @@ function toUpperMethod(m) {
78
94
  return m ? m.toUpperCase() : void 0;
79
95
  }
80
96
  function getTypeName(v) {
81
- var _a;
82
97
  if (v === null) return "null";
83
98
  if (v === void 0) return "undefined";
84
99
  const t = typeof v;
85
100
  if (t !== "object") return t;
86
101
  try {
87
- return ((_a = v == null ? void 0 : v.constructor) == null ? void 0 : _a.name) || "object";
102
+ return v?.constructor?.name || "object";
88
103
  } catch {
89
104
  return "object";
90
105
  }
@@ -105,15 +120,14 @@ function n(v) {
105
120
  return v === void 0 ? null : v;
106
121
  }
107
122
  function buildErrorMessage(err) {
108
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
109
- const method = toUpperMethod((_a = err.config) == null ? void 0 : _a.method);
110
- const baseURL = ((_b = err.config) == null ? void 0 : _b.baseURL) || "";
111
- const url = ((_c = err.config) == null ? void 0 : _c.url) ? `${baseURL || ""}${err.config.url}` : "";
112
- const status = (_d = err.response) == null ? void 0 : _d.status;
113
- const statusText = (_e = err.response) == null ? void 0 : _e.statusText;
114
- const respData = (_f = err.response) == null ? void 0 : _f.data;
115
- const requestId = ((_h = (_g = err.response) == null ? void 0 : _g.headers) == null ? void 0 : _h["x-request-id"]) || ((_i = respData == null ? void 0 : respData.status) == null ? void 0 : _i.requestId);
116
- const serverMsg = (respData == null ? void 0 : respData.message) || (respData == null ? void 0 : respData.msg) || ((_j = respData == null ? void 0 : respData.status) == null ? void 0 : _j.msg);
123
+ const method = toUpperMethod(err.config?.method);
124
+ const baseURL = err.config?.baseURL || "";
125
+ const url = err.config?.url ? `${baseURL || ""}${err.config.url}` : "";
126
+ const status = err.response?.status;
127
+ const statusText = err.response?.statusText;
128
+ const respData = err.response?.data;
129
+ const requestId = err.response?.headers?.["x-request-id"] || respData?.status?.requestId;
130
+ const serverMsg = respData?.message || respData?.msg || respData?.status?.msg;
117
131
  const summary = [
118
132
  status ? `HTTP ${status}` : "HTTP ERROR",
119
133
  method,
@@ -127,18 +141,17 @@ function buildErrorMessage(err) {
127
141
  return [summary, shortMsg, ridMsg, codeMsg, localMsg].filter(Boolean).join(" | ");
128
142
  }
129
143
  function buildDetails(err) {
130
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
131
144
  const cfg = err.config;
132
- let body = cfg == null ? void 0 : cfg.data;
145
+ let body = cfg?.data;
133
146
  if (typeof body === "string") {
134
147
  try {
135
148
  body = JSON.parse(body);
136
149
  } catch {
137
150
  }
138
151
  }
139
- const baseURL = cfg == null ? void 0 : cfg.baseURL;
140
- const url = (cfg == null ? void 0 : cfg.url) ? baseURL ? `${baseURL}${cfg.url}` : cfg.url : void 0;
141
- const requestId = ((_b = (_a = err.response) == null ? void 0 : _a.headers) == null ? void 0 : _b["x-request-id"]) || ((_e = (_d = (_c = err.response) == null ? void 0 : _c.data) == null ? void 0 : _d.status) == null ? void 0 : _e.requestId);
152
+ const baseURL = cfg?.baseURL;
153
+ const url = cfg?.url ? baseURL ? `${baseURL}${cfg.url}` : cfg.url : void 0;
154
+ const requestId = err.response?.headers?.["x-request-id"] || err.response?.data?.status?.requestId;
142
155
  return {
143
156
  // error 基础信息(保证不会被 stringify 成 {})
144
157
  name: n(err.name),
@@ -146,29 +159,28 @@ function buildDetails(err) {
146
159
  code: n(err.code),
147
160
  stack: n(err.stack),
148
161
  // request 信息
149
- method: n(toUpperMethod(cfg == null ? void 0 : cfg.method)),
162
+ method: n(toUpperMethod(cfg?.method)),
150
163
  baseURL: n(baseURL),
151
164
  url: n(url),
152
- timeout: n(cfg == null ? void 0 : cfg.timeout),
153
- withCredentials: n(cfg == null ? void 0 : cfg.withCredentials),
154
- params: n(cfg == null ? void 0 : cfg.params),
165
+ timeout: n(cfg?.timeout),
166
+ withCredentials: n(cfg?.withCredentials),
167
+ params: n(cfg?.params),
155
168
  data: n(body),
156
169
  // response 信息
157
- status: n((_f = err.response) == null ? void 0 : _f.status),
158
- statusText: n((_g = err.response) == null ? void 0 : _g.statusText),
170
+ status: n(err.response?.status),
171
+ statusText: n(err.response?.statusText),
159
172
  requestId: n(requestId),
160
- responseDataType: n(getTypeName((_h = err.response) == null ? void 0 : _h.data)),
161
- responseData: n(safeResponseData((_i = err.response) == null ? void 0 : _i.data))
173
+ responseDataType: n(getTypeName(err.response?.data)),
174
+ responseData: n(safeResponseData(err.response?.data))
162
175
  };
163
176
  }
164
177
  function errorInterceptor(error) {
165
- var _a, _b, _c;
166
178
  const err = isAxiosError(error) ? error : new AxiosError(String(error));
167
179
  const isTimeout = err.code === "ECONNABORTED" || /timeout/i.test(err.message || "");
168
180
  if (isTimeout) {
169
- const method = toUpperMethod((_a = err.config) == null ? void 0 : _a.method);
170
- const baseURL = ((_b = err.config) == null ? void 0 : _b.baseURL) || "";
171
- const url = ((_c = err.config) == null ? void 0 : _c.url) ? `${baseURL || ""}${err.config.url}` : "";
181
+ const method = toUpperMethod(err.config?.method);
182
+ const baseURL = err.config?.baseURL || "";
183
+ const url = err.config?.url ? `${baseURL || ""}${err.config.url}` : "";
172
184
  const summary = [`TIMEOUT`, method, url].filter(Boolean).join(" | ");
173
185
  err.summary = summary;
174
186
  err.details = buildDetails(err);
@@ -181,40 +193,94 @@ function errorInterceptor(error) {
181
193
  logger.error({ message, details: err.details, errType: "server error" });
182
194
  return Promise.reject(err);
183
195
  }
184
- function ResponseInterceptor(response) {
185
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
186
- const config = response.config;
187
- if (config.returnFullResponse) {
188
- return response;
196
+ const refreshBaseURL = typeof window !== "undefined" ? process.env.NEXT_PUBLIC_AUTH_URL || window.location.origin : process.env.AUTH_INNER_API_URL || process.env.NEXT_PUBLIC_AUTH_URL;
197
+ const refreshClient = axios.create({
198
+ baseURL: refreshBaseURL,
199
+ timeout: 1e4,
200
+ withCredentials: true,
201
+ paramsSerializer(params) {
202
+ return qs.stringify(params, { arrayFormat: "brackets" });
203
+ }
204
+ });
205
+ let refreshPromise = null;
206
+ const REFRESH_DEDUPE_MS = 2e3;
207
+ let lastRefreshAt = 0;
208
+ let lastRefreshResult = null;
209
+ function refreshAccessToken() {
210
+ if (refreshPromise) {
211
+ return refreshPromise;
189
212
  }
190
- if (response.status === 401) {
191
- if (typeof window !== "undefined") {
192
- TokenManager.removeAllToken();
213
+ if (Date.now() - lastRefreshAt < REFRESH_DEDUPE_MS) {
214
+ return Promise.resolve(lastRefreshResult);
215
+ }
216
+ const refresh_token = getToken("refresh_token");
217
+ if (!refresh_token) {
218
+ return Promise.resolve(null);
219
+ }
220
+ const pending = refreshClient.get("/api/refresh/token", {
221
+ params: {
222
+ grant_type: "refresh_token",
223
+ refresh_token
224
+ },
225
+ headers: {
226
+ isRefreshToken: true
227
+ }
228
+ }).then((res) => {
229
+ const data = res?.data?.data;
230
+ if (data?.access_token) {
231
+ if (typeof window !== "undefined") {
232
+ window.dispatchEvent(new CustomEvent("user-profile-updated"));
233
+ }
234
+ return data.access_token;
193
235
  }
236
+ removeAllToken();
237
+ return null;
238
+ }).catch(() => null).then((result) => {
239
+ lastRefreshAt = Date.now();
240
+ lastRefreshResult = result;
241
+ return result;
242
+ }).finally(() => {
243
+ refreshPromise = null;
244
+ });
245
+ refreshPromise = pending;
246
+ return pending;
247
+ }
248
+ function getCurrentAccessToken() {
249
+ return jsCookie.get(envCookieName("access_token")) || getToken("access_token") || "";
250
+ }
251
+ function shouldSkipRefresh(config) {
252
+ const url = typeof config?.url === "string" ? config.url : "";
253
+ if (url.includes("/api/refresh/token")) return true;
254
+ if (url.includes("/v2/auth/")) return true;
255
+ if (config?.headers?.isRefreshToken) return true;
256
+ return false;
257
+ }
258
+ function handleBusinessResponse(response) {
259
+ const config = response.config;
260
+ if (config.returnFullResponse) {
194
261
  return response;
195
262
  }
196
263
  if (response.status === 200) {
197
- if ((_a = response.headers["content-type"]) == null ? void 0 : _a.includes("text/event-stream")) {
264
+ if (response.headers["content-type"]?.includes("text/event-stream")) {
198
265
  return response;
199
266
  }
200
267
  const data = response.data;
201
268
  const businessStatus = data.status;
202
269
  if (businessStatus && typeof businessStatus.code === "number" && ![0, 200].includes(businessStatus.code) && businessStatus.code !== 401) {
203
270
  const err = new AxiosError(
204
- (businessStatus == null ? void 0 : businessStatus.msg) || "Business error",
271
+ businessStatus?.msg || "Business error",
205
272
  String(businessStatus.code),
206
273
  response.config,
207
274
  response.request,
208
275
  response
209
276
  );
210
- const summary = `BIZ ${businessStatus.code} | ${(_c = (_b = response.config) == null ? void 0 : _b.method) == null ? void 0 : _c.toUpperCase()} | ${((_d = response.config) == null ? void 0 : _d.baseURL) || ""}${((_e = response.config) == null ? void 0 : _e.url) || ""} | server: ${businessStatus == null ? void 0 : businessStatus.msg}`;
277
+ const summary = `BIZ ${businessStatus.code} | ${response.config?.method?.toUpperCase()} | ${response.config?.baseURL || ""}${response.config?.url || ""} | server: ${businessStatus?.msg}`;
211
278
  const details = {
212
- method: (_g = (_f = response.config) == null ? void 0 : _f.method) == null ? void 0 : _g.toUpperCase(),
213
- url: ((_h = response.config) == null ? void 0 : _h.baseURL) ? `${response.config.baseURL}${response.config.url || ""}` : response.config.url,
214
- params: (_i = response.config) == null ? void 0 : _i.params,
279
+ method: response.config?.method?.toUpperCase(),
280
+ url: response.config?.baseURL ? `${response.config.baseURL}${response.config.url || ""}` : response.config.url,
281
+ params: response.config?.params,
215
282
  data: (() => {
216
- var _a2;
217
- let d = (_a2 = response.config) == null ? void 0 : _a2.data;
283
+ let d = response.config?.data;
218
284
  if (typeof d === "string") {
219
285
  try {
220
286
  d = JSON.parse(d);
@@ -225,7 +291,7 @@ function ResponseInterceptor(response) {
225
291
  })(),
226
292
  status: response.status,
227
293
  statusText: response.statusText,
228
- requestId: ((_j = response.headers) == null ? void 0 : _j["x-request-id"]) || (businessStatus == null ? void 0 : businessStatus.requestId),
294
+ requestId: response.headers?.["x-request-id"] || businessStatus?.requestId,
229
295
  responseData: data
230
296
  };
231
297
  if (process.env.NODE_ENV !== "development") {
@@ -237,26 +303,43 @@ function ResponseInterceptor(response) {
237
303
  }
238
304
  return response;
239
305
  }
240
- let refreshPromise = null;
241
- const axiosInstance$1 = axios.create({
242
- baseURL: process.env.AUTH_INNER_API_URL || process.env.NEXT_PUBLIC_AUTH_URL,
243
- timeout: 1e4,
244
- withCredentials: true,
245
- // Always include credentials by default
246
- paramsSerializer: function(params) {
247
- return qs.stringify(params, { arrayFormat: "brackets" });
306
+ function createResponseInterceptor(instance) {
307
+ return async function ResponseInterceptor(response) {
308
+ if (response.status === 401) {
309
+ const config = response.config;
310
+ const canRetry = !isServerRuntime() && !shouldSkipRefresh(config) && !config.__isRetryAfterRefresh;
311
+ if (canRetry) {
312
+ const newAccessToken = await refreshAccessToken();
313
+ if (newAccessToken) {
314
+ config.__isRetryAfterRefresh = true;
315
+ return instance(config);
316
+ }
317
+ }
318
+ return response;
319
+ }
320
+ return handleBusinessResponse(response);
321
+ };
322
+ }
323
+ function setAuthHeader(config, accessToken) {
324
+ const value = `Bearer ${accessToken}`;
325
+ const h = config.headers;
326
+ if (h?.set && typeof h.set === "function") {
327
+ h.set("Authorization", value);
328
+ } else {
329
+ h.Authorization = value;
248
330
  }
249
- });
331
+ }
250
332
  async function refreshToken(config) {
251
- if (typeof window === "undefined" || process.env.IS_SERVER === "true") {
333
+ if (isServerRuntime()) {
252
334
  return config;
253
335
  }
254
336
  if (typeof config.url === "string" && config.url.includes("/api/refresh/token")) {
255
337
  return config;
256
338
  }
257
- const headers = config.headers;
258
- if (refreshPromise) {
259
- await refreshPromise;
339
+ if (typeof config.url === "string" && config.url.includes("/v2/auth/")) {
340
+ return config;
341
+ }
342
+ if (config.headers?.isRefreshToken) {
260
343
  return config;
261
344
  }
262
345
  let expired = false;
@@ -266,42 +349,11 @@ async function refreshToken(config) {
266
349
  expired = false;
267
350
  }
268
351
  if (expired) {
269
- const refresh_token = getToken("refresh_token");
270
- if (!refresh_token) {
271
- removeAllToken();
272
- return config;
352
+ const newAccessToken = await refreshAccessToken();
353
+ const accessToken = newAccessToken || getCurrentAccessToken();
354
+ if (accessToken) {
355
+ setAuthHeader(config, accessToken);
273
356
  }
274
- if (refreshPromise) {
275
- await refreshPromise;
276
- return config;
277
- }
278
- const refreshHeaders = { ...headers };
279
- delete refreshHeaders.Authorization;
280
- delete refreshHeaders.authorization;
281
- refreshHeaders.isRefreshToken = true;
282
- refreshPromise = axiosInstance$1.get(`/api/refresh/token`, {
283
- params: {
284
- grant_type: "refresh_token",
285
- refresh_token
286
- },
287
- headers: {
288
- ...refreshHeaders
289
- }
290
- }).then((res) => {
291
- var _a;
292
- if ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.data) {
293
- return res.data.data;
294
- } else {
295
- removeAllToken();
296
- return null;
297
- }
298
- }).catch(() => {
299
- removeAllToken();
300
- return null;
301
- }).finally(() => {
302
- refreshPromise = null;
303
- });
304
- await refreshPromise;
305
357
  }
306
358
  return config;
307
359
  }
@@ -319,7 +371,10 @@ const axiosInstance = axios.create({
319
371
  });
320
372
  axiosInstance.interceptors.request.use(refreshToken);
321
373
  axiosInstance.interceptors.request.use(commonHeader, errorInterceptor);
322
- axiosInstance.interceptors.response.use(ResponseInterceptor, errorInterceptor);
374
+ axiosInstance.interceptors.response.use(createResponseInterceptor(axiosInstance), errorInterceptor);
323
375
  export {
324
- axiosInstance as default
376
+ axiosInstance as default,
377
+ getCurrentAccessToken,
378
+ refreshAccessToken,
379
+ setServerHeaderProvider
325
380
  };
@@ -1,3 +1,5 @@
1
1
  import { InternalAxiosRequestConfig } from 'axios';
2
+ import { ServerHeaderProvider } from '../types';
3
+ export declare function setServerHeaderProvider(provider: ServerHeaderProvider): void;
2
4
  export declare function commonHeader(config: InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig<any>>;
3
5
  //# sourceMappingURL=commonHeader.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"commonHeader.d.ts","sourceRoot":"","sources":["../../src/interceptors/commonHeader.ts"],"names":[],"mappings":"AAEA,OAAO,EAAoB,0BAA0B,EAAE,MAAM,OAAO,CAAC;AAiCrE,wBAAsB,YAAY,CAChC,MAAM,EAAE,0BAA0B,4CA+CnC"}
1
+ {"version":3,"file":"commonHeader.d.ts","sourceRoot":"","sources":["../../src/interceptors/commonHeader.ts"],"names":[],"mappings":"AAGA,OAAO,EAAoB,0BAA0B,EAAE,MAAM,OAAO,CAAC;AACrE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAQrD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,oBAAoB,QAErE;AAyBD,wBAAsB,YAAY,CAChC,MAAM,EAAE,0BAA0B,4CAwDnC"}
@@ -1,3 +1,7 @@
1
1
  import { InternalAxiosRequestConfig } from 'axios';
2
+ /**
3
+ * 请求前的「预测式刷新」:若本地判断 access_token 即将/已过期,提前刷新。
4
+ * 这是一层优化;真正的兜底由响应拦截器的 401 自动刷新+重放保证。
5
+ */
2
6
  export default function refreshToken(config: InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig<any>>;
3
7
  //# sourceMappingURL=refreshToken.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"refreshToken.d.ts","sourceRoot":"","sources":["../../src/interceptors/refreshToken.ts"],"names":[],"mappings":"AAAA,OAAc,EAAE,0BAA0B,EAAE,MAAM,OAAO,CAAC;AAY1D,wBAA8B,YAAY,CACxC,MAAM,EAAE,0BAA0B,4CAqEnC"}
1
+ {"version":3,"file":"refreshToken.d.ts","sourceRoot":"","sources":["../../src/interceptors/refreshToken.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,0BAA0B,EAAE,MAAM,OAAO,CAAC;AAerE;;;GAGG;AACH,wBAA8B,YAAY,CACxC,MAAM,EAAE,0BAA0B,4CAkCnC"}
@@ -1,3 +1,13 @@
1
- import { AxiosResponse } from 'axios';
2
- export default function ResponseInterceptor(response: AxiosResponse): any;
1
+ import { AxiosInstance, AxiosResponse } from 'axios';
2
+ /**
3
+ * 响应拦截器工厂。
4
+ *
5
+ * 业界标准 401 处理:业务接口返回 401 时,用 refresh_token 刷新一次并重放原请求;
6
+ * 仅当刷新失败时把 401 透传给上层(由显式 logout 决定是否清登录态)。
7
+ * - 仅在客户端重试(SSR 无 cookie jar)。
8
+ * - 每个请求最多重试一次,避免死循环。
9
+ * - /v2/auth/*、刷新接口本身不触发重试。
10
+ */
11
+ export declare function createResponseInterceptor(instance: AxiosInstance): (response: AxiosResponse) => Promise<any>;
12
+ export default createResponseInterceptor;
3
13
  //# sourceMappingURL=response.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"response.d.ts","sourceRoot":"","sources":["../../src/interceptors/response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,aAAa,EAAE,MAAM,OAAO,CAAC;AAKlD,MAAM,CAAC,OAAO,UAAU,mBAAmB,CAAC,QAAQ,EAAE,aAAa,GAAG,GAAG,CAuDxE"}
1
+ {"version":3,"file":"response.d.ts","sourceRoot":"","sources":["../../src/interceptors/response.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,aAAa,EAAE,aAAa,EAA8B,MAAM,OAAO,CAAC;AAqE7F;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,aAAa,IACrB,UAAU,aAAa,KAAG,OAAO,CAAC,GAAG,CAAC,CAoBjF;AAED,eAAe,yBAAyB,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 判断是否处于“服务端运行时”。
3
+ *
4
+ * 关键点:只要存在真实浏览器 window,就一律视为客户端,
5
+ * 避免业务方在客户端 bundle 中固化 IS_SERVER=true 时被误判为服务端,
6
+ * 从而走 next/headers 读 cookie 失败、请求不带 Authorization。
7
+ */
8
+ export declare function isServerRuntime(): boolean;
9
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,eAAe,IAAI,OAAO,CAKzC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 触发一次 token 刷新;并发/紧邻调用共享同一个结果。
3
+ *
4
+ * 关键设计:cookie 由服务端 `/api/refresh/token` 的 Set-Cookie 统一写入,
5
+ * 客户端这里「绝不」再用 js-cookie 写一遍,避免双写竞态把 cookie 写坏。
6
+ *
7
+ * @returns 新的 access_token;刷新失败返回 null。
8
+ */
9
+ export declare function refreshAccessToken(): Promise<string | null>;
10
+ export declare function getCurrentAccessToken(): string;
11
+ //# sourceMappingURL=tokenRefresh.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokenRefresh.d.ts","sourceRoot":"","sources":["../src/tokenRefresh.ts"],"names":[],"mappings":"AAqCA;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAwD3D;AAED,wBAAgB,qBAAqB,IAAI,MAAM,CAE9C"}
package/dist/types.d.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
+ export interface ServerHeaderProvider {
3
+ getAccessToken(): Promise<string | undefined>;
4
+ getLanguage(): Promise<string | undefined>;
5
+ }
2
6
  export interface ApiRequestConfig extends AxiosRequestConfig {
3
7
  withCredentials?: boolean;
4
8
  returnFullResponse?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE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ACF,MAAM,WAAW,QAAQ;IACvB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,CAAC;CACzB;AACD;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,OAAO,CAAC,EAAE,QAAQ,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,CAAC;CACzB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xchain/request",
3
- "version": "1.1.0-beta.7",
3
+ "version": "1.1.0-beta.70",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -17,17 +17,28 @@
17
17
  "dist",
18
18
  "!**/*.tsbuildinfo"
19
19
  ],
20
+ "peerDependencies": {
21
+ "axios": "1.13.2",
22
+ "js-cookie": "3.0.5",
23
+ "next": "16.1.6",
24
+ "qs": "6.14.0"
25
+ },
20
26
  "devDependencies": {
21
27
  "@types/js-cookie": "3.0.6",
22
- "@types/qs": "6.14.0"
23
- },
24
- "dependencies": {
28
+ "@types/qs": "6.14.0",
25
29
  "axios": "1.13.2",
26
30
  "js-cookie": "3.0.5",
27
- "next": "15.5.6",
28
- "qs": "6.14.0",
29
- "@0xchain/logger": "1.1.0-beta.7",
30
- "@0xchain/token": "1.1.0-beta.7"
31
+ "next": "16.1.6",
32
+ "qs": "6.14.0"
33
+ },
34
+ "dependencies": {
35
+ "@0xchain/logger": "1.1.0-beta.70",
36
+ "@0xchain/token": "1.1.0-beta.70"
37
+ },
38
+ "nx": {
39
+ "tags": [
40
+ "type:util"
41
+ ]
31
42
  },
32
43
  "publishConfig": {
33
44
  "access": "public"
@@ -1,4 +0,0 @@
1
- const __viteBrowserExternal = {};
2
- export {
3
- __viteBrowserExternal as default
4
- };