@ametie/vue-muza-use 0.0.1
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/README.md +267 -0
- package/dist/index.cjs +573 -0
- package/dist/index.d.cts +350 -0
- package/dist/index.d.ts +350 -0
- package/dist/index.mjs +521 -0
- package/package.json +48 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
AuthEventType: () => AuthEventType,
|
|
34
|
+
createApi: () => createApi,
|
|
35
|
+
createApiClient: () => createApiClient,
|
|
36
|
+
setAuthMonitor: () => setAuthMonitor,
|
|
37
|
+
setupInterceptors: () => setupInterceptors,
|
|
38
|
+
tokenManager: () => tokenManager,
|
|
39
|
+
useAbortController: () => useAbortController,
|
|
40
|
+
useApi: () => useApi,
|
|
41
|
+
useApiConfig: () => useApiConfig,
|
|
42
|
+
useApiDelete: () => useApiDelete,
|
|
43
|
+
useApiGet: () => useApiGet,
|
|
44
|
+
useApiPatch: () => useApiPatch,
|
|
45
|
+
useApiPost: () => useApiPost,
|
|
46
|
+
useApiPut: () => useApiPut,
|
|
47
|
+
useApiState: () => useApiState
|
|
48
|
+
});
|
|
49
|
+
module.exports = __toCommonJS(index_exports);
|
|
50
|
+
|
|
51
|
+
// src/plugin.ts
|
|
52
|
+
var import_vue = require("vue");
|
|
53
|
+
var API_INJECTION_KEY = /* @__PURE__ */ Symbol("use-api-config");
|
|
54
|
+
function createApi(options) {
|
|
55
|
+
return {
|
|
56
|
+
install(app) {
|
|
57
|
+
app.provide(API_INJECTION_KEY, options);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function useApiConfig() {
|
|
62
|
+
const config = (0, import_vue.inject)(API_INJECTION_KEY);
|
|
63
|
+
if (!config) {
|
|
64
|
+
throw new Error("API plugin not installed! Did you forget app.use(createApi(...))?");
|
|
65
|
+
}
|
|
66
|
+
return config;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// src/utils/debounce.ts
|
|
70
|
+
function debounceFn(fn, delay) {
|
|
71
|
+
let timeoutId = null;
|
|
72
|
+
return function(...args) {
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
if (timeoutId) {
|
|
75
|
+
clearTimeout(timeoutId);
|
|
76
|
+
}
|
|
77
|
+
timeoutId = setTimeout(async () => {
|
|
78
|
+
const result = await fn(...args);
|
|
79
|
+
resolve(result);
|
|
80
|
+
timeoutId = null;
|
|
81
|
+
}, delay);
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// src/useApi.ts
|
|
87
|
+
var import_vue4 = require("vue");
|
|
88
|
+
|
|
89
|
+
// src/utils/errorParser.ts
|
|
90
|
+
function parseApiError(error) {
|
|
91
|
+
if (error && typeof error === "object" && "isAxiosError" in error && error.isAxiosError) {
|
|
92
|
+
const axiosError = error;
|
|
93
|
+
if (axiosError.response) {
|
|
94
|
+
const { data, status } = axiosError.response;
|
|
95
|
+
const message = data?.message || data?.error || axiosError.message || "Unknown Error";
|
|
96
|
+
return {
|
|
97
|
+
message,
|
|
98
|
+
status,
|
|
99
|
+
code: data?.code,
|
|
100
|
+
errors: data?.errors,
|
|
101
|
+
details: data
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
message: error instanceof Error ? error.message : String(error),
|
|
107
|
+
status: 0
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/composables/useApiState.ts
|
|
112
|
+
var import_vue2 = require("vue");
|
|
113
|
+
function useApiState(initialData = null, options = {}) {
|
|
114
|
+
const { initialLoading = false } = options;
|
|
115
|
+
const data = (0, import_vue2.ref)(initialData);
|
|
116
|
+
const loading = (0, import_vue2.ref)(initialLoading);
|
|
117
|
+
const error = (0, import_vue2.ref)(null);
|
|
118
|
+
const statusCode = (0, import_vue2.ref)(null);
|
|
119
|
+
const response = (0, import_vue2.ref)(null);
|
|
120
|
+
const setData = (newData, fullResponse) => {
|
|
121
|
+
data.value = newData;
|
|
122
|
+
error.value = null;
|
|
123
|
+
if (fullResponse) {
|
|
124
|
+
response.value = fullResponse;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const setError = (newError) => {
|
|
128
|
+
error.value = newError;
|
|
129
|
+
};
|
|
130
|
+
const setLoading = (isLoading) => {
|
|
131
|
+
loading.value = isLoading;
|
|
132
|
+
};
|
|
133
|
+
const setStatusCode = (code) => {
|
|
134
|
+
statusCode.value = code;
|
|
135
|
+
};
|
|
136
|
+
const reset = () => {
|
|
137
|
+
data.value = initialData;
|
|
138
|
+
loading.value = false;
|
|
139
|
+
error.value = null;
|
|
140
|
+
statusCode.value = null;
|
|
141
|
+
response.value = null;
|
|
142
|
+
};
|
|
143
|
+
return {
|
|
144
|
+
data,
|
|
145
|
+
loading,
|
|
146
|
+
error,
|
|
147
|
+
statusCode,
|
|
148
|
+
response,
|
|
149
|
+
setData,
|
|
150
|
+
setError,
|
|
151
|
+
setLoading,
|
|
152
|
+
setStatusCode,
|
|
153
|
+
reset
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/composables/useAbortController.ts
|
|
158
|
+
var import_vue3 = require("vue");
|
|
159
|
+
var abortController = new AbortController();
|
|
160
|
+
var abortCount = (0, import_vue3.ref)(0);
|
|
161
|
+
function useAbortController() {
|
|
162
|
+
const signal = (0, import_vue3.readonly)((0, import_vue3.ref)(abortController.signal));
|
|
163
|
+
const abort = () => {
|
|
164
|
+
abortCount.value++;
|
|
165
|
+
abortController.abort();
|
|
166
|
+
abortController = new AbortController();
|
|
167
|
+
};
|
|
168
|
+
const getSignal = () => {
|
|
169
|
+
return abortController.signal;
|
|
170
|
+
};
|
|
171
|
+
const isAbortError = (error) => {
|
|
172
|
+
return error instanceof DOMException && error.name === "AbortError";
|
|
173
|
+
};
|
|
174
|
+
return {
|
|
175
|
+
signal,
|
|
176
|
+
abort,
|
|
177
|
+
getSignal,
|
|
178
|
+
isAbortError,
|
|
179
|
+
abortCount: (0, import_vue3.readonly)(abortCount)
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/useApi.ts
|
|
184
|
+
function useApi(url, options = {}) {
|
|
185
|
+
const { axios: axios2, onError: globalErrorHandler, globalOptions } = useApiConfig();
|
|
186
|
+
const {
|
|
187
|
+
method = "GET",
|
|
188
|
+
immediate = false,
|
|
189
|
+
onSuccess,
|
|
190
|
+
onError,
|
|
191
|
+
onBefore,
|
|
192
|
+
onFinish,
|
|
193
|
+
initialData = null,
|
|
194
|
+
debounce = 0,
|
|
195
|
+
skipErrorNotification = false,
|
|
196
|
+
retry = globalOptions?.retry ?? false,
|
|
197
|
+
retryDelay = globalOptions?.retryDelay ?? 1e3,
|
|
198
|
+
authMode = "default",
|
|
199
|
+
useGlobalAbort = globalOptions?.useGlobalAbort ?? true,
|
|
200
|
+
initialLoading = false,
|
|
201
|
+
...axiosConfig
|
|
202
|
+
} = options;
|
|
203
|
+
const startLoading = initialLoading ?? immediate;
|
|
204
|
+
const state = useApiState(initialData, { initialLoading: startLoading });
|
|
205
|
+
const abortController2 = (0, import_vue4.ref)(null);
|
|
206
|
+
const globalAbort = useGlobalAbort ? useAbortController() : null;
|
|
207
|
+
const executeRequest = async (config) => {
|
|
208
|
+
const requestUrl = typeof url === "string" ? url : url.value;
|
|
209
|
+
if (abortController2.value) abortController2.value.abort("Cancelled by new request");
|
|
210
|
+
const controller = new AbortController();
|
|
211
|
+
abortController2.value = controller;
|
|
212
|
+
let globalAbortHandler = null;
|
|
213
|
+
let subscribedSignal = null;
|
|
214
|
+
if (globalAbort) {
|
|
215
|
+
const gs = globalAbort.getSignal();
|
|
216
|
+
if (!gs.aborted) {
|
|
217
|
+
subscribedSignal = gs;
|
|
218
|
+
const currentCount = globalAbort.abortCount.value;
|
|
219
|
+
globalAbortHandler = () => {
|
|
220
|
+
if (globalAbort.abortCount.value === currentCount) controller.abort("Global filter change");
|
|
221
|
+
};
|
|
222
|
+
gs.addEventListener("abort", globalAbortHandler);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
onBefore?.();
|
|
226
|
+
state.setLoading(true);
|
|
227
|
+
state.setError(null);
|
|
228
|
+
let wasCancelled = false;
|
|
229
|
+
try {
|
|
230
|
+
const rawData = config?.data !== void 0 ? config.data : axiosConfig.data;
|
|
231
|
+
const resolvedData = (0, import_vue4.toValue)(rawData);
|
|
232
|
+
const response = await axios2.request({
|
|
233
|
+
url: requestUrl,
|
|
234
|
+
method,
|
|
235
|
+
...axiosConfig,
|
|
236
|
+
...config,
|
|
237
|
+
data: resolvedData,
|
|
238
|
+
signal: controller.signal,
|
|
239
|
+
authMode: config?.authMode || authMode
|
|
240
|
+
});
|
|
241
|
+
state.setData(response.data, response);
|
|
242
|
+
state.setStatusCode(response.status);
|
|
243
|
+
onSuccess?.(response);
|
|
244
|
+
return response.data;
|
|
245
|
+
} catch (err) {
|
|
246
|
+
if (controller.signal.aborted || err?.code === "ERR_CANCELED") {
|
|
247
|
+
wasCancelled = true;
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
const apiError = parseApiError(err);
|
|
251
|
+
if (!skipErrorNotification && globalErrorHandler) {
|
|
252
|
+
globalErrorHandler(apiError, err);
|
|
253
|
+
}
|
|
254
|
+
state.setError(apiError);
|
|
255
|
+
state.setStatusCode(apiError.status);
|
|
256
|
+
onError?.(apiError);
|
|
257
|
+
return null;
|
|
258
|
+
} finally {
|
|
259
|
+
if (globalAbortHandler && subscribedSignal) subscribedSignal.removeEventListener("abort", globalAbortHandler);
|
|
260
|
+
if (!wasCancelled) {
|
|
261
|
+
state.setLoading(false);
|
|
262
|
+
onFinish?.();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
const execute = debounce > 0 ? debounceFn(executeRequest, debounce) : executeRequest;
|
|
267
|
+
const abort = (msg) => {
|
|
268
|
+
abortController2.value?.abort(msg);
|
|
269
|
+
abortController2.value = null;
|
|
270
|
+
};
|
|
271
|
+
const reset = () => {
|
|
272
|
+
abort();
|
|
273
|
+
state.reset();
|
|
274
|
+
state.setLoading(false);
|
|
275
|
+
};
|
|
276
|
+
if ((0, import_vue4.getCurrentScope)()) {
|
|
277
|
+
(0, import_vue4.onScopeDispose)(() => abort("Scope disposed"));
|
|
278
|
+
}
|
|
279
|
+
if (immediate) execute();
|
|
280
|
+
return { ...state, execute, abort, reset };
|
|
281
|
+
}
|
|
282
|
+
function useApiGet(url, options) {
|
|
283
|
+
return useApi(url, { ...options, method: "GET" });
|
|
284
|
+
}
|
|
285
|
+
function useApiPost(url, options) {
|
|
286
|
+
return useApi(url, { ...options, method: "POST" });
|
|
287
|
+
}
|
|
288
|
+
function useApiPut(url, options) {
|
|
289
|
+
return useApi(url, { ...options, method: "PUT" });
|
|
290
|
+
}
|
|
291
|
+
function useApiPatch(url, options) {
|
|
292
|
+
return useApi(url, { ...options, method: "PATCH" });
|
|
293
|
+
}
|
|
294
|
+
function useApiDelete(url, options) {
|
|
295
|
+
return useApi(url, { ...options, method: "DELETE" });
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/features/createInstance.ts
|
|
299
|
+
var import_axios = __toESM(require("axios"), 1);
|
|
300
|
+
|
|
301
|
+
// src/features/monitor.ts
|
|
302
|
+
var import_meta = {};
|
|
303
|
+
var AuthEventType = /* @__PURE__ */ ((AuthEventType2) => {
|
|
304
|
+
AuthEventType2["REFRESH_START"] = "AUTH_REFRESH_START";
|
|
305
|
+
AuthEventType2["REQUEST_QUEUED"] = "AUTH_REQUEST_QUEUED";
|
|
306
|
+
AuthEventType2["REFRESH_SUCCESS"] = "AUTH_REFRESH_SUCCESS";
|
|
307
|
+
AuthEventType2["REFRESH_ERROR"] = "AUTH_REFRESH_ERROR";
|
|
308
|
+
return AuthEventType2;
|
|
309
|
+
})(AuthEventType || {});
|
|
310
|
+
var defaultMonitor = (type, payload) => {
|
|
311
|
+
const isDev = typeof process !== "undefined" && process.env?.NODE_ENV === "development" || import_meta?.env?.DEV;
|
|
312
|
+
if (isDev) {
|
|
313
|
+
console.debug(`[AuthMonitor] ${type}`, payload);
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
var currentMonitor = defaultMonitor;
|
|
317
|
+
function setAuthMonitor(fn) {
|
|
318
|
+
currentMonitor = fn;
|
|
319
|
+
}
|
|
320
|
+
function trackAuthEvent(type, payload = {}) {
|
|
321
|
+
currentMonitor(type, { ...payload, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// src/features/tokenManager.ts
|
|
325
|
+
var TOKEN_TYPE = "Bearer";
|
|
326
|
+
var ACCESS_TOKEN_KEY = "accessToken";
|
|
327
|
+
var TOKEN_EXPIRES_KEY = "tokenExpiresAt";
|
|
328
|
+
var LocalStorageTokenStorage = class {
|
|
329
|
+
getAccessToken() {
|
|
330
|
+
return localStorage.getItem(ACCESS_TOKEN_KEY);
|
|
331
|
+
}
|
|
332
|
+
getRefreshToken() {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
setTokens(tokens) {
|
|
336
|
+
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken);
|
|
337
|
+
if (tokens.expiresIn) {
|
|
338
|
+
const expiresAt = Date.now() + tokens.expiresIn * 1e3;
|
|
339
|
+
localStorage.setItem(TOKEN_EXPIRES_KEY, expiresAt.toString());
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
clearTokens() {
|
|
343
|
+
localStorage.removeItem(ACCESS_TOKEN_KEY);
|
|
344
|
+
localStorage.removeItem(TOKEN_EXPIRES_KEY);
|
|
345
|
+
}
|
|
346
|
+
getTokenExpiresAt() {
|
|
347
|
+
const expiresAt = localStorage.getItem(TOKEN_EXPIRES_KEY);
|
|
348
|
+
return expiresAt ? parseInt(expiresAt, 10) : null;
|
|
349
|
+
}
|
|
350
|
+
isTokenExpired() {
|
|
351
|
+
const expiresAt = this.getTokenExpiresAt();
|
|
352
|
+
if (!expiresAt) return false;
|
|
353
|
+
return Date.now() >= expiresAt - 5e3;
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
var TokenManager = class {
|
|
357
|
+
storage;
|
|
358
|
+
refreshPromise = null;
|
|
359
|
+
constructor(storage = new LocalStorageTokenStorage()) {
|
|
360
|
+
this.storage = storage;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Get access token
|
|
364
|
+
*/
|
|
365
|
+
getAccessToken() {
|
|
366
|
+
return this.storage.getAccessToken();
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Get refresh token
|
|
370
|
+
*/
|
|
371
|
+
getRefreshToken() {
|
|
372
|
+
return this.storage.getRefreshToken();
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Save tokens
|
|
376
|
+
*/
|
|
377
|
+
setTokens(tokens) {
|
|
378
|
+
this.storage.setTokens(tokens);
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Clear tokens
|
|
382
|
+
*/
|
|
383
|
+
clearTokens() {
|
|
384
|
+
this.storage.clearTokens();
|
|
385
|
+
this.refreshPromise = null;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Check if token is expired
|
|
389
|
+
*/
|
|
390
|
+
isTokenExpired() {
|
|
391
|
+
return this.storage.isTokenExpired();
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Get token expiration time
|
|
395
|
+
*/
|
|
396
|
+
getTokenExpiresAt() {
|
|
397
|
+
return this.storage.getTokenExpiresAt();
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Check if tokens exist
|
|
401
|
+
*/
|
|
402
|
+
hasTokens() {
|
|
403
|
+
return !!this.getAccessToken();
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Get Authorization header
|
|
407
|
+
*/
|
|
408
|
+
getAuthHeader() {
|
|
409
|
+
const token = this.getAccessToken();
|
|
410
|
+
return token ? `${TOKEN_TYPE} ${token}` : null;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Set token refresh promise (to prevent race conditions)
|
|
414
|
+
*/
|
|
415
|
+
setRefreshPromise(promise) {
|
|
416
|
+
this.refreshPromise = promise;
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Get token refresh promise
|
|
420
|
+
*/
|
|
421
|
+
getRefreshPromise() {
|
|
422
|
+
return this.refreshPromise;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Clear token refresh promise
|
|
426
|
+
*/
|
|
427
|
+
clearRefreshPromise() {
|
|
428
|
+
this.refreshPromise = null;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Set storage (useful for tests)
|
|
432
|
+
*/
|
|
433
|
+
setStorage(storage) {
|
|
434
|
+
this.storage = storage;
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
var tokenManager = new TokenManager();
|
|
438
|
+
|
|
439
|
+
// src/features/interceptors.ts
|
|
440
|
+
var AUTH_HEADER = "Authorization";
|
|
441
|
+
var TOKEN_TYPE2 = "Bearer";
|
|
442
|
+
var failedQueue = [];
|
|
443
|
+
var isRefreshing = false;
|
|
444
|
+
function processQueue(error, token = null) {
|
|
445
|
+
failedQueue.forEach((promise) => {
|
|
446
|
+
if (error) promise.reject(error);
|
|
447
|
+
else if (token) promise.resolve(token);
|
|
448
|
+
});
|
|
449
|
+
failedQueue = [];
|
|
450
|
+
}
|
|
451
|
+
function setupInterceptors(axiosInstance, options = {}) {
|
|
452
|
+
const {
|
|
453
|
+
refreshUrl = "/auth/refresh",
|
|
454
|
+
onTokenRefreshFailed,
|
|
455
|
+
extractTokens
|
|
456
|
+
} = options;
|
|
457
|
+
axiosInstance.interceptors.request.use(
|
|
458
|
+
(config) => {
|
|
459
|
+
const extendedConfig = config;
|
|
460
|
+
if (extendedConfig.authMode === "public") return config;
|
|
461
|
+
const token = tokenManager.getAccessToken();
|
|
462
|
+
if (token) {
|
|
463
|
+
config.headers.set(AUTH_HEADER, `${TOKEN_TYPE2} ${token}`);
|
|
464
|
+
}
|
|
465
|
+
return config;
|
|
466
|
+
},
|
|
467
|
+
(error) => Promise.reject(error)
|
|
468
|
+
);
|
|
469
|
+
axiosInstance.interceptors.response.use(
|
|
470
|
+
(response) => response,
|
|
471
|
+
async (error) => {
|
|
472
|
+
const originalRequest = error.config;
|
|
473
|
+
if (!originalRequest || error.response?.status !== 401 || originalRequest._retry) {
|
|
474
|
+
return Promise.reject(error);
|
|
475
|
+
}
|
|
476
|
+
if (originalRequest.authMode === "public" || originalRequest.authMode === "optional") {
|
|
477
|
+
return Promise.reject(error);
|
|
478
|
+
}
|
|
479
|
+
if (originalRequest.url?.includes(refreshUrl)) {
|
|
480
|
+
isRefreshing = false;
|
|
481
|
+
processQueue(error, null);
|
|
482
|
+
tokenManager.clearTokens();
|
|
483
|
+
onTokenRefreshFailed?.();
|
|
484
|
+
return Promise.reject(error);
|
|
485
|
+
}
|
|
486
|
+
if (isRefreshing) {
|
|
487
|
+
trackAuthEvent("AUTH_REQUEST_QUEUED" /* REQUEST_QUEUED */, { url: originalRequest.url });
|
|
488
|
+
return new Promise((resolve, reject) => {
|
|
489
|
+
failedQueue.push({
|
|
490
|
+
resolve: (token) => {
|
|
491
|
+
originalRequest.headers.set(AUTH_HEADER, `${TOKEN_TYPE2} ${token}`);
|
|
492
|
+
resolve(axiosInstance(originalRequest));
|
|
493
|
+
},
|
|
494
|
+
reject: (err) => reject(err)
|
|
495
|
+
});
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
originalRequest._retry = true;
|
|
499
|
+
isRefreshing = true;
|
|
500
|
+
trackAuthEvent("AUTH_REFRESH_START" /* REFRESH_START */, { url: originalRequest.url });
|
|
501
|
+
try {
|
|
502
|
+
const response = await axiosInstance.post(
|
|
503
|
+
refreshUrl,
|
|
504
|
+
{},
|
|
505
|
+
{
|
|
506
|
+
// @ts-expect-error
|
|
507
|
+
authMode: "public",
|
|
508
|
+
withCredentials: true
|
|
509
|
+
}
|
|
510
|
+
);
|
|
511
|
+
let accessToken = "";
|
|
512
|
+
if (extractTokens) {
|
|
513
|
+
const tokens = extractTokens(response);
|
|
514
|
+
accessToken = tokens.accessToken;
|
|
515
|
+
} else {
|
|
516
|
+
const data = response.data;
|
|
517
|
+
accessToken = data.accessToken || data.access_token;
|
|
518
|
+
}
|
|
519
|
+
if (!accessToken) throw new Error("No access token in refresh response");
|
|
520
|
+
tokenManager.setTokens({ accessToken });
|
|
521
|
+
axiosInstance.defaults.headers.common[AUTH_HEADER] = `${TOKEN_TYPE2} ${accessToken}`;
|
|
522
|
+
trackAuthEvent("AUTH_REFRESH_SUCCESS" /* REFRESH_SUCCESS */);
|
|
523
|
+
processQueue(null, accessToken);
|
|
524
|
+
originalRequest.headers.set(AUTH_HEADER, `${TOKEN_TYPE2} ${accessToken}`);
|
|
525
|
+
return axiosInstance(originalRequest);
|
|
526
|
+
} catch (refreshError) {
|
|
527
|
+
trackAuthEvent("AUTH_REFRESH_ERROR" /* REFRESH_ERROR */, { error: refreshError });
|
|
528
|
+
processQueue(refreshError, null);
|
|
529
|
+
tokenManager.clearTokens();
|
|
530
|
+
onTokenRefreshFailed?.();
|
|
531
|
+
return Promise.reject(refreshError);
|
|
532
|
+
} finally {
|
|
533
|
+
isRefreshing = false;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// src/features/createInstance.ts
|
|
540
|
+
function createApiClient(options = {}) {
|
|
541
|
+
const {
|
|
542
|
+
withAuth = true,
|
|
543
|
+
authOptions,
|
|
544
|
+
...axiosConfig
|
|
545
|
+
} = options;
|
|
546
|
+
const instance = import_axios.default.create({
|
|
547
|
+
timeout: 6e4,
|
|
548
|
+
headers: { "Content-Type": "application/json" },
|
|
549
|
+
...axiosConfig
|
|
550
|
+
});
|
|
551
|
+
if (withAuth) {
|
|
552
|
+
setupInterceptors(instance, authOptions);
|
|
553
|
+
}
|
|
554
|
+
return instance;
|
|
555
|
+
}
|
|
556
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
557
|
+
0 && (module.exports = {
|
|
558
|
+
AuthEventType,
|
|
559
|
+
createApi,
|
|
560
|
+
createApiClient,
|
|
561
|
+
setAuthMonitor,
|
|
562
|
+
setupInterceptors,
|
|
563
|
+
tokenManager,
|
|
564
|
+
useAbortController,
|
|
565
|
+
useApi,
|
|
566
|
+
useApiConfig,
|
|
567
|
+
useApiDelete,
|
|
568
|
+
useApiGet,
|
|
569
|
+
useApiPatch,
|
|
570
|
+
useApiPost,
|
|
571
|
+
useApiPut,
|
|
572
|
+
useApiState
|
|
573
|
+
});
|