@varlet/axle 0.3.2 → 0.3.3-alpha.1703057804193

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/lib/index.cjs ADDED
@@ -0,0 +1,478 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+
47
+ // src/index.ts
48
+ var src_exports = {};
49
+ __export(src_exports, {
50
+ createAxle: () => createAxle,
51
+ createFetchRunner: () => createFetchRunner,
52
+ createMatcher: () => createMatcher,
53
+ createModifyRunner: () => createModifyRunner,
54
+ download: () => download,
55
+ matchPattern: () => matchPattern,
56
+ requestHeadersInterceptor: () => requestHeadersInterceptor,
57
+ requestMd5Interceptor: () => requestMd5Interceptor,
58
+ requestMockInterceptor: () => requestMockInterceptor,
59
+ responseBlobInterceptor: () => responseBlobInterceptor,
60
+ responseRetryInterceptor: () => responseRetryInterceptor,
61
+ responseStatusInterceptor: () => responseStatusInterceptor,
62
+ responseTimeoutInterceptor: () => responseTimeoutInterceptor
63
+ });
64
+ module.exports = __toCommonJS(src_exports);
65
+
66
+ // src/instance.ts
67
+ var import_axios = __toESM(require("axios"), 1);
68
+ var import_qs = __toESM(require("qs"), 1);
69
+ var import_shared = require("@varlet/shared");
70
+
71
+ // src/utils/index.ts
72
+ function isFormData(value) {
73
+ return typeof FormData !== "undefined" && value instanceof FormData;
74
+ }
75
+ function formDataToObject(formData) {
76
+ const normalizedData = {};
77
+ formData.forEach((value, key) => {
78
+ normalizedData[key] = value;
79
+ });
80
+ return normalizedData;
81
+ }
82
+ function objectToFormData(object) {
83
+ const formData = new FormData();
84
+ Object.keys(object).forEach((key) => formData.append(key, object[key]));
85
+ return formData;
86
+ }
87
+
88
+ // src/instance.ts
89
+ function createFetchRunner(service, method, responseType) {
90
+ return function(url, params, config) {
91
+ return service[method](url, __spreadValues({
92
+ params,
93
+ responseType
94
+ }, config));
95
+ };
96
+ }
97
+ function createModifyRunner(service, method, contentType) {
98
+ return function(url, params, config) {
99
+ if (contentType === "application/x-www-form-urlencoded") {
100
+ params = import_qs.default.stringify(params);
101
+ }
102
+ if (contentType === "multipart/form-data") {
103
+ params = objectToFormData(params);
104
+ }
105
+ return service[method](url, params, __spreadValues({
106
+ headers: {
107
+ "Content-Type": contentType
108
+ }
109
+ }, config));
110
+ };
111
+ }
112
+ function download(url, filename) {
113
+ if (!(0, import_shared.inBrowser)()) {
114
+ return;
115
+ }
116
+ const a = document.createElement("a");
117
+ a.download = filename;
118
+ a.style.display = "none";
119
+ a.href = typeof url === "string" ? url : URL.createObjectURL(url);
120
+ document.body.appendChild(a);
121
+ a.click();
122
+ URL.revokeObjectURL(a.href);
123
+ document.body.removeChild(a);
124
+ }
125
+ function createAxle(config = {}) {
126
+ const service = import_axios.default.create(config);
127
+ function getHeaders() {
128
+ return service.defaults.headers.common;
129
+ }
130
+ function setHeader(key, value) {
131
+ ;
132
+ service.defaults.headers.common[key] = value;
133
+ }
134
+ function removeHeader(key) {
135
+ if (typeof key === "string") {
136
+ Reflect.deleteProperty(service.defaults.headers.common, key);
137
+ return;
138
+ }
139
+ key.forEach((k) => Reflect.deleteProperty(service.defaults.headers.common, k));
140
+ }
141
+ function useRequestInterceptor(...interceptors) {
142
+ interceptors.forEach((interceptor) => {
143
+ service.interceptors.request.use(interceptor.onFulfilled, interceptor.onRejected, interceptor.options);
144
+ });
145
+ }
146
+ function useResponseInterceptor(...interceptors) {
147
+ interceptors.forEach((interceptor) => {
148
+ service.interceptors.response.use(interceptor.onFulfilled, interceptor.onRejected, interceptor.options);
149
+ });
150
+ }
151
+ return {
152
+ get: createFetchRunner(service, "get", "json"),
153
+ getBlob: createFetchRunner(service, "get", "blob"),
154
+ getDocument: createFetchRunner(service, "get", "document"),
155
+ getArrayBuffer: createFetchRunner(service, "get", "arraybuffer"),
156
+ getText: createFetchRunner(service, "get", "text"),
157
+ getStream: createFetchRunner(service, "get", "stream"),
158
+ head: createFetchRunner(service, "head", "json"),
159
+ headBlob: createFetchRunner(service, "head", "blob"),
160
+ headDocument: createFetchRunner(service, "head", "document"),
161
+ headArrayBuffer: createFetchRunner(service, "head", "arraybuffer"),
162
+ headText: createFetchRunner(service, "head", "text"),
163
+ headStream: createFetchRunner(service, "head", "stream"),
164
+ options: createFetchRunner(service, "options", "json"),
165
+ optionsBlob: createFetchRunner(service, "options", "blob"),
166
+ optionsDocument: createFetchRunner(service, "options", "document"),
167
+ optionsArrayBuffer: createFetchRunner(service, "options", "arraybuffer"),
168
+ optionsText: createFetchRunner(service, "options", "text"),
169
+ optionsStream: createFetchRunner(service, "options", "stream"),
170
+ delete: createFetchRunner(service, "delete", "json"),
171
+ deleteBlob: createFetchRunner(service, "delete", "blob"),
172
+ deleteDocument: createFetchRunner(service, "delete", "document"),
173
+ deleteArrayBuffer: createFetchRunner(service, "delete", "arraybuffer"),
174
+ deleteText: createFetchRunner(service, "delete", "text"),
175
+ deleteStream: createFetchRunner(service, "delete", "stream"),
176
+ post: createModifyRunner(service, "post", "application/json"),
177
+ postUrlEncode: createModifyRunner(service, "post", "application/x-www-form-urlencoded"),
178
+ postMultipart: createModifyRunner(service, "post", "multipart/form-data"),
179
+ put: createModifyRunner(service, "put", "application/json"),
180
+ putUrlEncode: createModifyRunner(service, "put", "application/x-www-form-urlencoded"),
181
+ putMultipart: createModifyRunner(service, "put", "multipart/form-data"),
182
+ patch: createModifyRunner(service, "patch", "application/json"),
183
+ patchUrlEncode: createModifyRunner(service, "patch", "application/x-www-form-urlencoded"),
184
+ patchMultipart: createModifyRunner(service, "patch", "multipart/form-data"),
185
+ getHeaders,
186
+ setHeader,
187
+ removeHeader,
188
+ useRequestInterceptor,
189
+ useResponseInterceptor,
190
+ axios: service
191
+ };
192
+ }
193
+
194
+ // src/matcher.ts
195
+ var import_minimatch = require("minimatch");
196
+ function matchPattern(pattern, method, url, status) {
197
+ if (pattern.startsWith("status:")) {
198
+ return pattern.replace("status:", "").trim() === String(status);
199
+ }
200
+ return pattern.startsWith("method:") ? pattern.replace("method:", "").trim() === method : (0, import_minimatch.minimatch)(url != null ? url : "", pattern);
201
+ }
202
+ function createMatcher(include, exclude) {
203
+ function matcher(method, url, status) {
204
+ if (!include && !exclude) {
205
+ return true;
206
+ }
207
+ const isExclude = (exclude != null ? exclude : []).some((pattern) => matchPattern(pattern, method, url, status));
208
+ if (isExclude) {
209
+ return false;
210
+ }
211
+ if (!include) {
212
+ return true;
213
+ }
214
+ const isInclude = (include != null ? include : []).some((pattern) => matchPattern(pattern, method, url, status));
215
+ return isInclude;
216
+ }
217
+ return matcher;
218
+ }
219
+
220
+ // src/interceptors/requestHeadersInterceptor.ts
221
+ var import_shared2 = require("@varlet/shared");
222
+ function requestHeadersInterceptor(options = {}) {
223
+ const { headers: headersOrGetter } = options;
224
+ return {
225
+ onFulfilled(config) {
226
+ var _a, _b, _c;
227
+ const matcher = createMatcher(options.include, options.exclude);
228
+ if (!matcher((_a = config.method) != null ? _a : "", (_b = config.url) != null ? _b : "")) {
229
+ return config;
230
+ }
231
+ const headers = (_c = (0, import_shared2.isFunction)(headersOrGetter) ? headersOrGetter() : headersOrGetter) != null ? _c : {};
232
+ Object.entries(headers).forEach(([key, value]) => {
233
+ config.headers[key] = value;
234
+ });
235
+ return config;
236
+ },
237
+ onRejected: (error) => Promise.reject(error),
238
+ options: options.axiosInterceptorOptions
239
+ };
240
+ }
241
+
242
+ // src/interceptors/requestMockInterceptor.ts
243
+ var import_axios2 = require("axios");
244
+ var import_minimatch2 = require("minimatch");
245
+ function settle(response, resolve, reject, delay = 0) {
246
+ if (delay > 0) {
247
+ setTimeout(() => {
248
+ settle(response, resolve, reject);
249
+ }, delay);
250
+ return;
251
+ }
252
+ if (!response.config.validateStatus || response.config.validateStatus(response.status)) {
253
+ resolve(response);
254
+ } else {
255
+ reject(new import_axios2.AxiosError(`Request failed with status code ${response.status}`, void 0, response.config, response));
256
+ }
257
+ }
258
+ function requestMockInterceptor(options = {}) {
259
+ return {
260
+ onFulfilled(config) {
261
+ var _a, _b;
262
+ const matcher = createMatcher(options.include, options.exclude);
263
+ if (!matcher((_a = config.method) != null ? _a : "", (_b = config.url) != null ? _b : "")) {
264
+ return config;
265
+ }
266
+ const findMapping = () => {
267
+ var _a2;
268
+ return ((_a2 = options.mappings) != null ? _a2 : []).find((mapping2) => {
269
+ var _a3;
270
+ const isMatchUrl = (0, import_minimatch2.minimatch)((_a3 = config.url) != null ? _a3 : "", mapping2.url);
271
+ const isMatchMethod = mapping2.method != null ? config.method === mapping2.method : true;
272
+ return isMatchUrl && isMatchMethod;
273
+ });
274
+ };
275
+ const mapping = findMapping();
276
+ if (!mapping) {
277
+ return config;
278
+ }
279
+ config.adapter = () => {
280
+ var _a2, _b2;
281
+ const partialResponse = mapping.handler(config);
282
+ const response = __spreadProps(__spreadValues({}, partialResponse), {
283
+ headers: config.headers,
284
+ config,
285
+ request: {},
286
+ data: partialResponse.data,
287
+ status: (_a2 = partialResponse.status) != null ? _a2 : 200,
288
+ statusText: (_b2 = partialResponse.statusText) != null ? _b2 : "OK"
289
+ });
290
+ return new Promise((resolve, reject) => {
291
+ settle(response, resolve, reject, mapping.delay);
292
+ });
293
+ };
294
+ return config;
295
+ },
296
+ onRejected: (error) => Promise.reject(error),
297
+ options: options.axiosInterceptorOptions
298
+ };
299
+ }
300
+
301
+ // src/interceptors/responseBlobInterceptor.ts
302
+ function responseBlobInterceptor(options = {}) {
303
+ return {
304
+ onFulfilled(response) {
305
+ var _a, _b, _c, _d;
306
+ const matcher = createMatcher(options.include, options.exclude);
307
+ if (!matcher((_a = response.config.method) != null ? _a : "", (_b = response.config.url) != null ? _b : "", response.status)) {
308
+ return response;
309
+ }
310
+ if (response.request.responseType === "blob") {
311
+ return (_d = (_c = options.onResponse) == null ? void 0 : _c.call(options, response)) != null ? _d : response;
312
+ }
313
+ return response;
314
+ },
315
+ onRejected: (error) => Promise.reject(error),
316
+ options: options.axiosInterceptorOptions
317
+ };
318
+ }
319
+
320
+ // src/interceptors/responseTimeoutInterceptor.ts
321
+ function responseTimeoutInterceptor(options = {}) {
322
+ return {
323
+ onFulfilled: (response) => response,
324
+ onRejected(error) {
325
+ var _a, _b, _c, _d;
326
+ const matcher = createMatcher(options.include, options.exclude);
327
+ if (!matcher((_a = error.config.method) != null ? _a : "", (_b = error.config.url) != null ? _b : "", (_c = error == null ? void 0 : error.response) == null ? void 0 : _c.status)) {
328
+ return Promise.reject(error);
329
+ }
330
+ if (error.code === "ECONNABORTED" && error.message.includes("timeout") || error.code === "ETIMEDOUT") {
331
+ error.code = (_d = options == null ? void 0 : options.normalizeErrorCode) != null ? _d : "TIMEOUT";
332
+ }
333
+ return Promise.reject(error);
334
+ },
335
+ options: options.axiosInterceptorOptions
336
+ };
337
+ }
338
+
339
+ // src/interceptors/responseRetryInterceptor.ts
340
+ var import_axios3 = __toESM(require("axios"), 1);
341
+ function responseRetryInterceptor(options) {
342
+ return {
343
+ onFulfilled: (response) => response,
344
+ async onRejected(error) {
345
+ var _a, _b, _c;
346
+ const matcher = createMatcher(options.include, options.exclude);
347
+ if (!matcher((_a = error.config.method) != null ? _a : "", (_b = error.config.url) != null ? _b : "", (_c = error == null ? void 0 : error.response) == null ? void 0 : _c.status) || (0, import_axios3.isCancel)(error)) {
348
+ return Promise.reject(error);
349
+ }
350
+ const { count = 1 } = options;
351
+ let retryCount = 0;
352
+ async function retry() {
353
+ try {
354
+ retryCount++;
355
+ return await import_axios3.default.create()(error.config);
356
+ } catch (error2) {
357
+ if (retryCount === count) {
358
+ return Promise.reject(error2);
359
+ }
360
+ return retry();
361
+ }
362
+ }
363
+ return retry();
364
+ },
365
+ options: options.axiosInterceptorOptions
366
+ };
367
+ }
368
+
369
+ // src/interceptors/responseStatusInterceptor.ts
370
+ function responseStatusInterceptor(options) {
371
+ return {
372
+ onFulfilled: (response) => {
373
+ var _a, _b, _c;
374
+ const matcher = createMatcher(options.include, options.exclude);
375
+ if (!matcher((_a = response.config.method) != null ? _a : "", (_b = response.config.url) != null ? _b : "", response.status)) {
376
+ return response;
377
+ }
378
+ const handler = ((_c = options.validStatusHandler) != null ? _c : {})[response.status];
379
+ if (!handler) {
380
+ return response;
381
+ }
382
+ const handlerResponse = handler(response);
383
+ return handlerResponse != null ? handlerResponse : response;
384
+ },
385
+ onRejected: (error) => {
386
+ var _a, _b, _c, _d;
387
+ const matcher = createMatcher(options.include, options.exclude);
388
+ if (!matcher((_a = error.config.method) != null ? _a : "", (_b = error.config.url) != null ? _b : "", (_c = error == null ? void 0 : error.response) == null ? void 0 : _c.status)) {
389
+ return Promise.reject(error);
390
+ }
391
+ const handler = ((_d = options.invalidStatusHandler) != null ? _d : {})[error.response.status];
392
+ if (!handler) {
393
+ return Promise.reject(error);
394
+ }
395
+ const handlerError = handler(error);
396
+ return handlerError != null ? handlerError : Promise.reject(error);
397
+ },
398
+ options: options.axiosInterceptorOptions
399
+ };
400
+ }
401
+
402
+ // src/interceptors/requestMd5Interceptor.ts
403
+ var import_qs2 = __toESM(require("qs"), 1);
404
+ var import_md5 = __toESM(require("crypto-js/md5"), 1);
405
+ var import_minimatch3 = require("minimatch");
406
+ var import_lodash_es = require("lodash-es");
407
+ var import_shared3 = require("@varlet/shared");
408
+ function withCtxMd5(ctx, mapping) {
409
+ mapping.path.forEach((path) => {
410
+ const targetValue = (0, import_lodash_es.get)(ctx, path);
411
+ if (targetValue != null) {
412
+ (0, import_lodash_es.set)(ctx, path, (0, import_md5.default)(String(targetValue)).toString());
413
+ }
414
+ });
415
+ }
416
+ function withMd5(config, mapping) {
417
+ const { data = {}, params = {}, headers = {} } = config;
418
+ const ctx = {
419
+ data: isFormData(data) ? data : JSON.parse(JSON.stringify(data)),
420
+ params: JSON.parse(JSON.stringify(params)),
421
+ headers: JSON.parse(JSON.stringify(headers))
422
+ };
423
+ if ((0, import_shared3.isString)(ctx.data) && ctx.data.length > 0 && ctx.headers["Content-Type"] === "application/x-www-form-urlencoded") {
424
+ ctx.data = import_qs2.default.parse(ctx.data);
425
+ withCtxMd5(ctx, mapping);
426
+ ctx.data = import_qs2.default.stringify(ctx.data);
427
+ } else if (isFormData(ctx.data)) {
428
+ ctx.data = formDataToObject(ctx.data);
429
+ withCtxMd5(ctx, mapping);
430
+ ctx.data = objectToFormData(ctx.data);
431
+ } else {
432
+ withCtxMd5(ctx, mapping);
433
+ }
434
+ return __spreadValues(__spreadValues({}, config), ctx);
435
+ }
436
+ function requestMd5Interceptor(options = {}) {
437
+ return {
438
+ onFulfilled(config) {
439
+ var _a, _b;
440
+ const matcher = createMatcher(options.include, options.exclude);
441
+ if (!matcher((_a = config.method) != null ? _a : "", (_b = config.url) != null ? _b : "")) {
442
+ return config;
443
+ }
444
+ const findMapping = () => {
445
+ var _a2;
446
+ return ((_a2 = options.mappings) != null ? _a2 : []).find((mapping2) => {
447
+ var _a3;
448
+ const isMatchUrl = (0, import_minimatch3.minimatch)((_a3 = config.url) != null ? _a3 : "", mapping2.url);
449
+ const isMatchMethod = mapping2.method != null ? config.method === mapping2.method : true;
450
+ return isMatchUrl && isMatchMethod;
451
+ });
452
+ };
453
+ const mapping = findMapping();
454
+ if (!mapping) {
455
+ return config;
456
+ }
457
+ return withMd5(config, mapping);
458
+ },
459
+ onRejected: (error) => Promise.reject(error),
460
+ options: options.axiosInterceptorOptions
461
+ };
462
+ }
463
+ // Annotate the CommonJS export names for ESM import in node:
464
+ 0 && (module.exports = {
465
+ createAxle,
466
+ createFetchRunner,
467
+ createMatcher,
468
+ createModifyRunner,
469
+ download,
470
+ matchPattern,
471
+ requestHeadersInterceptor,
472
+ requestMd5Interceptor,
473
+ requestMockInterceptor,
474
+ responseBlobInterceptor,
475
+ responseRetryInterceptor,
476
+ responseStatusInterceptor,
477
+ responseTimeoutInterceptor
478
+ });
package/lib/index.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { R as RequestInterceptor, a as ResponseInterceptor } from './instance-8e68a761.js';
2
+ export { e as AxleInstance, A as AxleRequestConfig, b as FetchMethod, F as FetchRunner, I as Interceptor, c as ModifyMethod, M as ModifyRunner, d as RunnerMethod, i as createAxle, f as createFetchRunner, g as createModifyRunner, h as download } from './instance-8e68a761.js';
3
+ import { AxiosInterceptorOptions, AxiosRequestConfig, AxiosResponse } from 'axios';
4
+
5
+ declare function matchPattern(pattern: string, method: string, url: string, status?: number | null | undefined): boolean;
6
+ declare function createMatcher(include?: string[], exclude?: string[]): (method: string, url: string, status?: number | null | undefined) => boolean;
7
+
8
+ interface RequestHeadersInterceptorOptions {
9
+ headers?: Record<string, string> | (() => Record<string, string>);
10
+ include?: string[];
11
+ exclude?: string[];
12
+ axiosInterceptorOptions?: AxiosInterceptorOptions;
13
+ }
14
+ declare function requestHeadersInterceptor(options?: RequestHeadersInterceptorOptions): RequestInterceptor;
15
+
16
+ type RequestMockInterceptorMapping = {
17
+ url: string;
18
+ handler: (config: AxiosRequestConfig) => {
19
+ data: any;
20
+ status?: number;
21
+ statusText?: string;
22
+ };
23
+ method?: string;
24
+ delay?: number;
25
+ };
26
+ interface RequestMockInterceptorOptions {
27
+ mappings?: RequestMockInterceptorMapping[];
28
+ include?: string[];
29
+ exclude?: string[];
30
+ axiosInterceptorOptions?: AxiosInterceptorOptions;
31
+ }
32
+ declare function requestMockInterceptor(options?: RequestMockInterceptorOptions): RequestInterceptor;
33
+
34
+ interface ResponseBlobInterceptorOptions {
35
+ onResponse?: (response: AxiosResponse<any, any>) => any;
36
+ include?: string[];
37
+ exclude?: string[];
38
+ axiosInterceptorOptions?: AxiosInterceptorOptions;
39
+ }
40
+ declare function responseBlobInterceptor(options?: ResponseBlobInterceptorOptions): ResponseInterceptor;
41
+
42
+ interface ResponseTimeoutInterceptorOptions {
43
+ normalizeErrorCode?: string;
44
+ include?: string[];
45
+ exclude?: string[];
46
+ axiosInterceptorOptions?: AxiosInterceptorOptions;
47
+ }
48
+ declare function responseTimeoutInterceptor(options?: ResponseTimeoutInterceptorOptions): ResponseInterceptor;
49
+
50
+ interface ResponseRetryInterceptorOptions {
51
+ count?: number;
52
+ include?: string[];
53
+ exclude?: string[];
54
+ axiosInterceptorOptions?: AxiosInterceptorOptions;
55
+ }
56
+ declare function responseRetryInterceptor(options: ResponseRetryInterceptorOptions): ResponseInterceptor;
57
+
58
+ interface ResponseStatusInterceptorOptions {
59
+ validStatusHandler?: Record<number | string, (response: AxiosResponse<any, any>) => any>;
60
+ invalidStatusHandler?: Record<number | string, (error: any) => any>;
61
+ include?: string[];
62
+ exclude?: string[];
63
+ axiosInterceptorOptions?: AxiosInterceptorOptions;
64
+ }
65
+ declare function responseStatusInterceptor(options: ResponseStatusInterceptorOptions): ResponseInterceptor;
66
+
67
+ type RequestMd5InterceptorMapping = {
68
+ url: string;
69
+ path: string[];
70
+ method?: string;
71
+ };
72
+ interface RequestMd5InterceptorOptions {
73
+ mappings?: RequestMd5InterceptorMapping[];
74
+ include?: string[];
75
+ exclude?: string[];
76
+ axiosInterceptorOptions?: AxiosInterceptorOptions;
77
+ }
78
+ declare function requestMd5Interceptor(options?: RequestMd5InterceptorOptions): RequestInterceptor;
79
+
80
+ export { RequestHeadersInterceptorOptions, RequestInterceptor, RequestMd5InterceptorMapping, RequestMd5InterceptorOptions, RequestMockInterceptorMapping, RequestMockInterceptorOptions, ResponseBlobInterceptorOptions, ResponseInterceptor, ResponseRetryInterceptorOptions, ResponseStatusInterceptorOptions, ResponseTimeoutInterceptorOptions, createMatcher, matchPattern, requestHeadersInterceptor, requestMd5Interceptor, requestMockInterceptor, responseBlobInterceptor, responseRetryInterceptor, responseStatusInterceptor, responseTimeoutInterceptor };
package/lib/use.cjs ADDED
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
+
34
+ // src/use.ts
35
+ var use_exports = {};
36
+ __export(use_exports, {
37
+ createUseAxle: () => createUseAxle,
38
+ useAverageProgress: () => useAverageProgress,
39
+ useHasLoading: () => useHasLoading,
40
+ useValues: () => useValues
41
+ });
42
+ module.exports = __toCommonJS(use_exports);
43
+ var import_vue4 = require("vue");
44
+ var import_shared = require("@varlet/shared");
45
+
46
+ // src/composables/useValues.ts
47
+ var import_vue = require("vue");
48
+ function useValues(...valueCollection) {
49
+ return (0, import_vue.computed)({
50
+ get: () => valueCollection.map((value) => value.value),
51
+ set(values) {
52
+ valueCollection.forEach((value, index) => {
53
+ value.value = values[index];
54
+ });
55
+ }
56
+ });
57
+ }
58
+
59
+ // src/composables/useHasLoading.ts
60
+ var import_vue2 = require("vue");
61
+ function useHasLoading(...loadings) {
62
+ const hasLoading = (0, import_vue2.ref)(false);
63
+ (0, import_vue2.watch)(
64
+ () => loadings.map((loading) => loading.value),
65
+ (newLoadings) => {
66
+ hasLoading.value = newLoadings.some(Boolean);
67
+ },
68
+ { immediate: true }
69
+ );
70
+ return hasLoading;
71
+ }
72
+
73
+ // src/composables/useAverageProgress.ts
74
+ var import_vue3 = require("vue");
75
+ function useAverageProgress(...progressCollection) {
76
+ const averageProgress = (0, import_vue3.ref)(0);
77
+ (0, import_vue3.watch)(
78
+ () => progressCollection.map((progress) => progress.value),
79
+ (newProgressCollection) => {
80
+ const total = newProgressCollection.reduce((total2, progress) => total2 + progress, 0);
81
+ averageProgress.value = total / progressCollection.length;
82
+ },
83
+ { immediate: true }
84
+ );
85
+ return averageProgress;
86
+ }
87
+
88
+ // src/use.ts
89
+ function createUseAxle(options) {
90
+ const { axle, onTransform: defaultOnTransform, immediate: defaultImmediate = false } = options;
91
+ const useAxle = (options2) => {
92
+ const {
93
+ url,
94
+ method,
95
+ immediate = defaultImmediate,
96
+ value: initialValue,
97
+ resetValue: initialResetValue,
98
+ params: initialParamsOrGetter,
99
+ config: initialConfig,
100
+ onBefore = () => {
101
+ },
102
+ onAfter = () => {
103
+ },
104
+ onTransform = defaultOnTransform != null ? defaultOnTransform : (response) => response,
105
+ onSuccess = () => {
106
+ },
107
+ onError = () => {
108
+ }
109
+ } = options2;
110
+ const initialUrl = url;
111
+ const value = (0, import_vue4.ref)(initialValue);
112
+ const loading = (0, import_vue4.ref)(false);
113
+ const error = (0, import_vue4.ref)();
114
+ const downloadProgress = (0, import_vue4.ref)(0);
115
+ const uploadProgress = (0, import_vue4.ref)(0);
116
+ const refs = {
117
+ value,
118
+ loading,
119
+ error,
120
+ downloadProgress,
121
+ uploadProgress
122
+ };
123
+ let controller = new AbortController();
124
+ const run = async (options3 = {}) => {
125
+ var _a, _b, _c;
126
+ if (controller.signal.aborted) {
127
+ controller = new AbortController();
128
+ }
129
+ const resetValue = (_b = (_a = options3.resetValue) != null ? _a : initialResetValue) != null ? _b : false;
130
+ if (resetValue === true) {
131
+ value.value = initialValue;
132
+ }
133
+ uploadProgress.value = 0;
134
+ downloadProgress.value = 0;
135
+ const url2 = (_c = options3.url) != null ? _c : initialUrl;
136
+ onBefore(refs);
137
+ loading.value = true;
138
+ try {
139
+ const getterParams = (0, import_shared.isFunction)(initialParamsOrGetter) ? initialParamsOrGetter() : {};
140
+ const response = await axle[method](
141
+ url2,
142
+ __spreadValues(__spreadValues({}, getterParams), options3.params),
143
+ __spreadValues({
144
+ signal: controller.signal,
145
+ onUploadProgress(event) {
146
+ var _a2;
147
+ uploadProgress.value = (_a2 = event.progress) != null ? _a2 : 0;
148
+ },
149
+ onDownloadProgress(event) {
150
+ var _a2;
151
+ downloadProgress.value = (_a2 = event.progress) != null ? _a2 : 0;
152
+ }
153
+ }, options3.config)
154
+ );
155
+ value.value = onTransform(response, refs);
156
+ error.value = void 0;
157
+ onSuccess(response, refs);
158
+ loading.value = false;
159
+ onAfter(refs);
160
+ return response;
161
+ } catch (responseError) {
162
+ error.value = responseError;
163
+ onError(responseError, refs);
164
+ loading.value = false;
165
+ onAfter(refs);
166
+ throw responseError;
167
+ }
168
+ };
169
+ const abort = () => {
170
+ controller.abort();
171
+ };
172
+ if (immediate) {
173
+ run({
174
+ url: initialUrl,
175
+ params: (0, import_shared.isFunction)(initialParamsOrGetter) ? {} : initialParamsOrGetter,
176
+ config: initialConfig
177
+ });
178
+ }
179
+ return [
180
+ value,
181
+ run,
182
+ {
183
+ loading,
184
+ error,
185
+ uploadProgress,
186
+ downloadProgress,
187
+ abort
188
+ }
189
+ ];
190
+ };
191
+ return useAxle;
192
+ }
193
+ // Annotate the CommonJS export names for ESM import in node:
194
+ 0 && (module.exports = {
195
+ createUseAxle,
196
+ useAverageProgress,
197
+ useHasLoading,
198
+ useValues
199
+ });
package/lib/use.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { Ref, WritableComputedRef } from 'vue';
2
+ import { A as AxleRequestConfig, d as RunnerMethod, e as AxleInstance } from './instance-8e68a761.js';
3
+ import 'axios';
4
+
5
+ declare function useValues<T extends Ref<any>[]>(...valueCollection: T): WritableComputedRef<T[number]['value'][]>;
6
+
7
+ declare function useHasLoading(...loadings: Ref<boolean>[]): Ref<boolean>;
8
+
9
+ declare function useAverageProgress(...progressCollection: Ref<number>[]): Ref<number>;
10
+
11
+ interface RunOptions<P> {
12
+ url?: string;
13
+ params?: P;
14
+ config?: AxleRequestConfig;
15
+ resetValue?: boolean;
16
+ }
17
+ type Run<R, P> = (options?: RunOptions<P>) => Promise<R>;
18
+ interface UseAxleRefs<V> {
19
+ value: Ref<V>;
20
+ loading: Ref<boolean>;
21
+ error: Ref<Error | undefined>;
22
+ uploadProgress: Ref<number>;
23
+ downloadProgress: Ref<number>;
24
+ }
25
+ interface UseAxleOptions<V = any, R = any, P = Record<string, any>> {
26
+ url: string;
27
+ method: RunnerMethod;
28
+ value?: V;
29
+ params?: P | (() => P);
30
+ resetValue?: boolean;
31
+ config?: AxleRequestConfig;
32
+ immediate?: boolean;
33
+ onBefore?(refs: UseAxleRefs<V>): void;
34
+ onAfter?(refs: UseAxleRefs<V>): void;
35
+ onTransform?(response: R, refs: UseAxleRefs<V>): V;
36
+ onSuccess?(response: R, refs: UseAxleRefs<V>): void;
37
+ onError?(error: Error, refs: UseAxleRefs<V>): void;
38
+ }
39
+ type UseAxleInstance<V, R, P> = [
40
+ value: Ref<V>,
41
+ run: Run<R, P>,
42
+ extra: {
43
+ uploadProgress: Ref<number>;
44
+ downloadProgress: Ref<number>;
45
+ loading: Ref<boolean>;
46
+ error: Ref<Error | undefined>;
47
+ abort(): void;
48
+ }
49
+ ];
50
+ interface CreateUseAxleOptions {
51
+ axle: AxleInstance;
52
+ immediate?: boolean;
53
+ onTransform?(response: any, refs: any): any;
54
+ }
55
+ declare function createUseAxle(options: CreateUseAxleOptions): <V = any, R = any, P = Record<string, any>>(options: UseAxleOptions<V, R, P>) => UseAxleInstance<V, R, P>;
56
+
57
+ export { CreateUseAxleOptions, Run, RunOptions, UseAxleInstance, UseAxleOptions, UseAxleRefs, createUseAxle, useAverageProgress, useHasLoading, useValues };
package/package.json CHANGED
@@ -1,25 +1,26 @@
1
1
  {
2
2
  "name": "@varlet/axle",
3
- "version": "0.3.2",
3
+ "version": "0.3.3-alpha.1703057804193",
4
4
  "description": "Progressive request tool based on axios",
5
5
  "type": "module",
6
- "main": "es/index.js",
7
- "module": "es/index.js",
8
- "types": "index.d.ts",
9
- "typesVersions": {
10
- "*": {
11
- "*": [
12
- "./es/*"
13
- ]
14
- }
15
- },
6
+ "main": "lib/index.cjs",
7
+ "module": "lib/index.js",
8
+ "types": "lib/index.d.ts",
16
9
  "exports": {
17
- ".": "./es/index.js",
18
- "./use": "./es/use.js",
10
+ ".": {
11
+ "import": "./lib/index.js",
12
+ "require": "./lib/index.cjs",
13
+ "types": "./lib/index.d.ts"
14
+ },
15
+ "./use": {
16
+ "import": "./lib/use.js",
17
+ "require": "./lib/use.cjs",
18
+ "types": "./lib/use.d.ts"
19
+ },
19
20
  "./*": "./*"
20
21
  },
21
22
  "files": [
22
- "es"
23
+ "lib"
23
24
  ],
24
25
  "keywords": [
25
26
  "axle",
@@ -58,7 +59,7 @@
58
59
  "url": "https://github.com/varletjs/axle/issues"
59
60
  },
60
61
  "scripts": {
61
- "dev": "tsup src/index.ts src/use.ts --format esm --out-dir=es --watch --dts",
62
- "build": "tsup src/index.ts src/use.ts --format esm --out-dir=es --dts --clean"
62
+ "dev": "tsup src/index.ts src/use.ts --format esm --out-dir=lib --watch --dts",
63
+ "build": "tsup src/index.ts src/use.ts --format esm,cjs --out-dir=lib --dts --clean"
63
64
  }
64
65
  }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes