@seayoo-web/request 2.1.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,595 @@
1
+ var N = Object.defineProperty;
2
+ var G = (e, t, s) => t in e ? N(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
+ var b = (e, t, s) => G(e, typeof t != "symbol" ? t + "" : t, s);
4
+ const c = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : typeof window < "u" ? window : Function("return this")(), E = {
5
+ wx: "wx" in c && R(c.wx) && "getSystemInfo" in c.wx && d(c.wx.getSystemInfo),
6
+ fetch: "fetch" in c && d(c.fetch),
7
+ window: "window" in c && R(c.window),
8
+ requestAnimationFrame: "requestAnimationFrame" in c && d(c.requestAnimationFrame),
9
+ localStorage: "localStorage" in c && R(c.localStorage) && "getItem" in c.localStorage && d(c.localStorage.getItem),
10
+ sessionStorage: "sessionStorage" in c && R(c.sessionStorage) && "getItem" in c.sessionStorage && d(c.sessionStorage.getItem),
11
+ File: "File" in c && d(c.File),
12
+ Blob: "Blob" in c && d(c.Blob),
13
+ Proxy: "Proxy" in c && d(c.Proxy),
14
+ Request: "Request" in c && d(c.Request),
15
+ FormData: "FormData" in c && d(c.FormData),
16
+ TextDecoder: "TextDecoder" in c && d(c.TextDecoder),
17
+ ResizeObserver: "ResizeObserver" in c && d(c.ResizeObserver),
18
+ AbortController: "AbortController" in c && d(c.AbortController)
19
+ };
20
+ function d(e) {
21
+ return typeof e == "function";
22
+ }
23
+ function R(e) {
24
+ return typeof e == "object" && e !== null;
25
+ }
26
+ function K(e) {
27
+ return new Promise((t) => setTimeout(t, Math.max(0, e)));
28
+ }
29
+ function J() {
30
+ }
31
+ function B(e, t) {
32
+ const s = {
33
+ log: console.log.bind(console),
34
+ error: console.error.bind(console),
35
+ warn: console.warn.bind(console)
36
+ }, r = `[${e}]`;
37
+ return ["log", "error", "warn"].forEach((o) => {
38
+ const n = console[o];
39
+ s[o] = (...a) => {
40
+ n.apply(console, [r, ...a]);
41
+ };
42
+ }), s;
43
+ }
44
+ function z(e) {
45
+ const t = e || "CustomError";
46
+ return class extends Error {
47
+ constructor(s) {
48
+ super(s), Object.defineProperty(this, "name", {
49
+ value: t,
50
+ enumerable: !1,
51
+ configurable: !0
52
+ }), "setPrototypeOf" in Object && Object.setPrototypeOf(this, new.target.prototype), "captureStackTrace" in Error && typeof Error.captureStackTrace == "function" && Error.captureStackTrace(this, this.constructor);
53
+ }
54
+ };
55
+ }
56
+ const V = /^(?:https?:)?\/\/.+$/i, W = /^https?:\/\/.+$/i, Z = /^\{[\d\D]*\}$/, X = /^\[[\d\D]*\]$/;
57
+ function U(e, t = !1) {
58
+ return t ? V.test(e) : W.test(e);
59
+ }
60
+ function Q(e) {
61
+ return e == null;
62
+ }
63
+ function F(e, ...t) {
64
+ if (!e || typeof e != "object") return !1;
65
+ const s = Object.getPrototypeOf(e);
66
+ return s !== Object.prototype && s !== null ? !1 : t.every((r) => r in e);
67
+ }
68
+ function _(e) {
69
+ return Z.test(e) || X.test(e);
70
+ }
71
+ function j(e) {
72
+ return e ? e[0].toLowerCase() + e.slice(1) : "";
73
+ }
74
+ const q = /_\w*/, H = /-\w*/;
75
+ function x(e) {
76
+ const t = q.test(e) ? e.replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (s, r) => r.toUpperCase()) : H.test(e) ? e.replace(/(?:^-*|-*$)/g, "").replace(/-+(\w)/g, (s, r) => r.toUpperCase()) : e;
77
+ return j(t);
78
+ }
79
+ function M(e) {
80
+ return q.test(e) ? j(e).replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (t, s) => "_" + s.toLowerCase()) : H.test(e) ? j(e.replace(/(?:^-*|-*$)/g, "")).replace(/-+(\w)/g, (t, s) => "_" + s.toLowerCase()) : j(e).replace(/[A-Z]/g, (t) => `_${t.toLowerCase()}`);
81
+ }
82
+ function v(e, t) {
83
+ try {
84
+ const s = JSON.parse(e);
85
+ return t ? t(s) ? s : null : s;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ "" + Math.random().toString(32).slice(2);
91
+ function O(e, t = !1) {
92
+ return typeof e == "string" ? x(e) : Array.isArray(e) ? e.map((s) => !t || typeof s == "string" ? O(s) : typeof s == "object" && s ? O(s, !0) : s) : F(e) ? Object.keys(e).reduce(
93
+ (s, r) => {
94
+ const o = x(String(r)), n = o.charAt(0).toLowerCase() + o.slice(1);
95
+ return s[n] = t ? e[r] : O(e[r]), s;
96
+ },
97
+ {}
98
+ ) : e;
99
+ }
100
+ function k(e, t = !1) {
101
+ return typeof e == "string" ? M(e) : Array.isArray(e) ? e.map((s) => !t || typeof s == "string" ? k(s) : typeof s == "object" && s ? k(s, t) : s) : F(e) ? Object.keys(e).reduce(
102
+ (s, r) => {
103
+ const o = M(String(r));
104
+ return s[o] = t ? e[r] : k(e[r]), s;
105
+ },
106
+ {}
107
+ ) : e;
108
+ }
109
+ B("LoadUtils");
110
+ async function je(e) {
111
+ return await new Promise(function(t) {
112
+ const s = document.getElementsByTagName("head")[0], r = document.createElement("script");
113
+ r.setAttribute("type", "text/javascript"), r.setAttribute("charset", "utf-8"), r.onload = function() {
114
+ s.removeChild(r), t(!0);
115
+ }, r.onerror = function() {
116
+ s.removeChild(r), t(!1);
117
+ }, r.setAttribute("src", e), s.appendChild(r);
118
+ });
119
+ }
120
+ B("Validator");
121
+ function Y(e, t = "数据未能正确识别") {
122
+ return typeof e == "function" ? {
123
+ guard: e,
124
+ message: t
125
+ } : {
126
+ guard: e.guard,
127
+ message: e.message || t
128
+ };
129
+ }
130
+ function ee(e, t = "") {
131
+ return !t || U(e, !0) ? L(e) : (L(t) + "/" + e).replace(/\/{2,}/g, "/").replace(/:\//, "://");
132
+ }
133
+ function L(e) {
134
+ return U(e, !0) ? e.startsWith("http") ? e : ("location" in globalThis ? location.protocol : "https:") + e : ("location" in globalThis ? location.origin : "http://127.0.0.1") + "/" + e.replace(/^\/+/, "");
135
+ }
136
+ function te(e, t) {
137
+ const s = {};
138
+ return (e.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(r) {
139
+ const o = r.split("="), n = o[0], a = decodeURIComponent(o[1] || "");
140
+ s[n] !== void 0 ? s[n] += "," + a : s[n] = a;
141
+ }), t !== !0 ? s[t] || "" : s;
142
+ }
143
+ function se(e, t) {
144
+ if (t) {
145
+ if (t === !0)
146
+ return e.replace(/\?[^#]*/, "");
147
+ } else return e;
148
+ const s = e.split("#"), r = s[0].split("?"), o = r[0], n = r.length > 1 ? r[1] : "", a = s.length > 1 ? "#" + s[1] : "", i = typeof t == "string" ? [t] : Array.isArray(t) ? t : [];
149
+ return !i.length || !n ? s[0] + a : (i.map((u) => u.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (o + "?" + n.replace(new RegExp("(?:^|&)(?:" + i.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + a);
150
+ }
151
+ function Oe(e, t, s = !1) {
152
+ const r = typeof t == "string" ? t : Object.keys(t).map((a) => `${a}=${encodeURIComponent(t[a])}`).join("&");
153
+ if (!r)
154
+ return e;
155
+ const o = e.split("#");
156
+ s && (o[0] = se(
157
+ o[0],
158
+ (r.match(/([^=&#?]+)=[^&#]+/g) || []).map((a) => a.replace(/=.+$/, ""))
159
+ ));
160
+ const n = o[0].indexOf("?") + 1 ? "&" : "?";
161
+ return (o[0] + n + r + (o.length > 1 ? "#" + o[1] : "")).replace(/\?&/, "?");
162
+ }
163
+ function re(e) {
164
+ const t = e.match(/(?:\?|&)([^=]+)(?:&|$)/g);
165
+ return t ? t.join("").replace(/(?:\?|^&+|&+$)/g, "").replace(/&{2}/g, "&").split("&").sort() : [];
166
+ }
167
+ class ne {
168
+ constructor(t = 500) {
169
+ b(this, "ttl");
170
+ b(this, "cache");
171
+ this.cache = {}, this.ttl = Math.max(t, 0);
172
+ }
173
+ getKey(t, s) {
174
+ const r = t.replace(/#.+/, ""), o = r.replace(/\?.+/g, ""), n = Object.assign(te(r, !0), s), a = re(r), i = Object.keys(n).sort().map((u) => `${u}#${n[u]}`);
175
+ return `${o}_${i.join(",")}_${a.join(",")}`;
176
+ }
177
+ updateTTL(t) {
178
+ this.ttl = Math.max(t, 0);
179
+ }
180
+ get(t) {
181
+ if (this.ttl === 0)
182
+ return null;
183
+ const s = this.cache[t];
184
+ return s ? s.ttl < Date.now() ? (delete this.cache[t], null) : s.res : null;
185
+ }
186
+ set(t, s) {
187
+ this.ttl !== 0 && (this.cache[t] = {
188
+ ttl: Date.now() + this.ttl,
189
+ res: s
190
+ });
191
+ }
192
+ }
193
+ class oe {
194
+ constructor(t) {
195
+ // 保存的配置需要部分字段强制设置默认值
196
+ b(this, "config", {
197
+ baseURL: "/",
198
+ maxRetry: 0,
199
+ retryInterval: 100,
200
+ retryResolve: "network",
201
+ timeout: 1e4,
202
+ cacheTTL: 500,
203
+ credentials: "same-origin",
204
+ defaultTypeGuardMessage: "响应数据未能正确识别",
205
+ responseRule: {
206
+ ok: {
207
+ resolve: "body"
208
+ },
209
+ failed: {
210
+ resolve: "json",
211
+ messageField: "message"
212
+ }
213
+ }
214
+ });
215
+ t && this.set(t);
216
+ }
217
+ set(t) {
218
+ if (t.baseURL && !/^\/.+/.test(t.baseURL) && !U(t.baseURL))
219
+ throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
220
+ Object.assign(this.config, t);
221
+ }
222
+ get(t) {
223
+ return this.config[t];
224
+ }
225
+ /** 基于 baseURL 返回完整的 url 地址 */
226
+ getFullUrl(t) {
227
+ return ee(t, this.config.baseURL);
228
+ }
229
+ /** 提示消息 */
230
+ showMessage(t, s, r, o) {
231
+ this.config.messageHandler && s && this.config.messageHandler(t, s, r, o);
232
+ }
233
+ }
234
+ var S = /* @__PURE__ */ ((e) => (e.UnexpectResponse = "UnexpectResponse", e.Aborted = "Aborted", e.Unknown = "Unknown", e.NetworkError = "NetworkError", e.Timeout = "Timeout", e.NotSupport = "NotSupport", e.URLFormatError = "URLFormatError", e))(S || {});
235
+ function ae(e, t, s, r) {
236
+ if (t.ok && !Q(t.data) && r) {
237
+ const o = Y(r, s.get("defaultTypeGuardMessage"));
238
+ return o.guard(t.data) || (t.code = S.UnexpectResponse, s.showMessage(!0, `${e} ${o.message}`, t.code, t.status), console.error(t.code, e, t.data), t.data = null, t.message = o.message), t;
239
+ }
240
+ return t;
241
+ }
242
+ class ke {
243
+ constructor(t, s) {
244
+ b(this, "agent");
245
+ b(this, "config");
246
+ b(this, "cache");
247
+ this.config = new oe(s), this.agent = t, this.cache = new ne(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.bind(this), this.request = this.request.bind(this), this.get = this.get.bind(this), this.post = this.post.bind(this), this.del = this.del.bind(this), this.patch = this.patch.bind(this), this.put = this.put.bind(this), this.head = this.head.bind(this);
248
+ }
249
+ /**
250
+ * 执行网络请求
251
+ */
252
+ async request(t, s) {
253
+ try {
254
+ return await this.agent(t, this.config, s);
255
+ } catch (r) {
256
+ return console.error("RequestError", r), {
257
+ ok: !1,
258
+ status: -9,
259
+ code: S.Unknown,
260
+ message: r instanceof Error ? `${r.message}
261
+ ${r.stack || ""}` : String(r),
262
+ headers: {},
263
+ data: null
264
+ };
265
+ }
266
+ }
267
+ /**
268
+ * 检查响应的数据类型
269
+ */
270
+ async guard(t, s, r) {
271
+ return ae(t, s, this.config, r);
272
+ }
273
+ /**
274
+ * 修改默认请求配置: baseURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
275
+ */
276
+ setConfig(t) {
277
+ this.config.set(t), this.cache.updateTTL(this.config.get("cacheTTL"));
278
+ }
279
+ /**
280
+ * 读取默认的请求配置
281
+ */
282
+ getConfig(t) {
283
+ return this.config.get(t);
284
+ }
285
+ /**
286
+ * 发送一个 HEAD 请求,并且不处理响应 body
287
+ */
288
+ async head(t, s) {
289
+ const r = Object.assign({}, s || null);
290
+ return r.method = "HEAD", this.guard(t, await this.request(t, r), null);
291
+ }
292
+ async get(t, s, r) {
293
+ const o = Object.assign({}, r || null);
294
+ o.method = "GET";
295
+ const n = this.cache.getKey(t, o.params), a = this.cache.get(n);
296
+ if (a)
297
+ return this.guard(t, await a, s || null);
298
+ const i = this.request(t, o);
299
+ return this.cache.set(n, i), this.guard(t, await i, s || null);
300
+ }
301
+ async post(t, s, r, o) {
302
+ const n = Object.assign({}, o || null);
303
+ return n.method = "POST", n.body = s || {}, this.guard(t, await this.request(t, n), r || null);
304
+ }
305
+ async del(t, s, r) {
306
+ const o = Object.assign({}, r || null);
307
+ return o.method = "DELETE", this.guard(t, await this.request(t, o), s || null);
308
+ }
309
+ async put(t, s, r, o) {
310
+ const n = Object.assign({}, o || null);
311
+ return n.method = "PUT", n.body = s || {}, this.guard(t, await this.request(t, n), r || null);
312
+ }
313
+ async patch(t, s, r, o) {
314
+ const n = Object.assign({}, o || null);
315
+ return n.method = "PATCH", n.body = s || {}, this.guard(t, await this.request(t, n), r || null);
316
+ }
317
+ }
318
+ async function Ee(e, t, s) {
319
+ var y;
320
+ const r = Object.assign({ method: "GET" }, s), o = E.FormData ? r.body instanceof FormData : !1, n = o && r.method !== "POST" && r.method !== "PUT" ? "POST" : r.method, a = n === "GET" || n === "HEAD" || n === "DELETE";
321
+ a && r.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete r.body);
322
+ const i = Object.assign(
323
+ o || a ? {} : {
324
+ "Content-Type": E.Blob && r.body instanceof Blob ? r.body.type || "application/octet-stream" : "application/json;charset=utf-8"
325
+ },
326
+ r.headers
327
+ ), u = r.params || {}, f = {};
328
+ Object.keys(u).forEach((w) => {
329
+ u[w] !== void 0 && (f[w] = ce(u[w]));
330
+ });
331
+ const l = t.getFullUrl(e), h = ie(r.body), g = r.timeout || t.get("timeout"), m = await async function() {
332
+ const w = t.get("requestTransformer");
333
+ if (w)
334
+ return await w({ headers: i, params: f, method: n, url: l, body: h });
335
+ }(), p = typeof m == "string" && m ? m : l;
336
+ return (y = t.get("logHandler")) == null || y({ type: "ready", url: p, method: n, headers: i, timeout: g, body: h }), {
337
+ url: p,
338
+ method: n,
339
+ body: h,
340
+ params: f,
341
+ headers: i,
342
+ timeout: g,
343
+ abort: r.abort,
344
+ credentials: r.credentials || t.get("credentials")
345
+ };
346
+ }
347
+ function ce(e) {
348
+ return typeof e == "string" ? e : Array.isArray(e) ? e.join(",") : e + "";
349
+ }
350
+ function ie(e) {
351
+ if (e)
352
+ return typeof e == "string" || e instanceof URLSearchParams || e instanceof ArrayBuffer || E.Blob && e instanceof Blob || E.FormData && e instanceof FormData ? e : JSON.stringify(e);
353
+ }
354
+ const I = "data", $ = "message";
355
+ function ue(e, t, s, r, o) {
356
+ const n = o || r;
357
+ return C(e) ? me(n.ok || r.ok, e, t, s) : le(n.failed || r.failed, t, s);
358
+ }
359
+ const Fe = function(e) {
360
+ const t = [], s = e.failed || { resolve: "json" };
361
+ switch (t.push("- 当http状态码 <200 或者 >=400 时"), s.resolve) {
362
+ case "body":
363
+ t.push(" 将响应内容格式化为字符串并作为错误消息");
364
+ break;
365
+ case "json":
366
+ t.push(" 将响应解析为json,并读取 " + (s.messageField || $) + " 作为错误消息");
367
+ break;
368
+ }
369
+ const r = e.ok || { resolve: "body" };
370
+ switch (t.push("- 当http状态码 >=200 并且 <400 时"), r.resolve) {
371
+ case "body":
372
+ t.push(" 将响应尝试解析为 json,并作为数据内容返回");
373
+ break;
374
+ case "json":
375
+ t.push(
376
+ " 将响应解析为 json,读取 " + (r.dataField || I) + " 作为响应数据,读取 " + (r.messageField || $) + " 作为提示消息"
377
+ ), r.statusField && t.push(
378
+ " 当 " + r.statusField + " 为 " + (r.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"
379
+ ), r.ignoreMessage && t.push(" 并忽略以下消息:" + r.ignoreMessage);
380
+ break;
381
+ }
382
+ return t.join(`
383
+ `);
384
+ };
385
+ function le(e, t, s) {
386
+ const r = e || { resolve: "json", messageField: $ }, o = {
387
+ ok: !1,
388
+ code: t,
389
+ message: s,
390
+ data: null
391
+ };
392
+ switch (r.resolve) {
393
+ case "body":
394
+ o.message = D(s) || s;
395
+ break;
396
+ case "json":
397
+ const { code: n, message: a } = he(s, r.converter, r.statusField, r.messageField);
398
+ o.code = n || t, o.message = D(s) || a;
399
+ break;
400
+ }
401
+ return o;
402
+ }
403
+ function he(e, t, s, r = $) {
404
+ if (!_(e))
405
+ return { message: "" };
406
+ const o = A(v(e), t);
407
+ return !o || !F(o) ? { message: e } : {
408
+ code: s ? T(o, s) : "",
409
+ message: T(o, r) || e
410
+ };
411
+ }
412
+ function T(e, t) {
413
+ const s = Array.isArray(t) ? t : [t];
414
+ for (const r of s)
415
+ if (r in e)
416
+ return de(e[r]);
417
+ return "";
418
+ }
419
+ function de(e) {
420
+ return e ? typeof e == "string" ? e : JSON.stringify(e) : "";
421
+ }
422
+ const fe = /<title>([^<]+)<\/title>/i, ge = /<message>([^<]+)<\/message>/i;
423
+ function D(e) {
424
+ const t = e.match(fe);
425
+ if (t)
426
+ return t[1];
427
+ const s = e.match(ge);
428
+ return s ? s[1] : "";
429
+ }
430
+ function me(e, t, s, r) {
431
+ const o = e || { resolve: "body" }, n = {
432
+ ok: !0,
433
+ code: s,
434
+ message: "",
435
+ data: null
436
+ };
437
+ if (t === 204 || !r)
438
+ return n;
439
+ if (o.resolve === "body")
440
+ return n.data = _(r) ? A(v(r), e.converter) : r, n;
441
+ const a = A(v(r), e.converter);
442
+ if (!a || !F(a))
443
+ return n.ok = !1, n.code = "ResponseFormatError", n.message = "响应内容无法格式化为 Object", n;
444
+ const i = o.statusField, u = o.statusOKValue || "", f = o.dataField || I, l = o.messageField || $, h = o.ignoreMessage || "";
445
+ if (i && !(i in a))
446
+ return n.ok = !1, n.code = "ResponseFieldMissing", n.message = "响应内容找不到状态字段 " + i, n;
447
+ const g = i ? a[i] + "" : "";
448
+ return n.ok = i ? g === u : !0, n.code = g || s, n.data = f === !0 ? a : f in a ? a[f] : null, n.message = T(a, l), h && n.message && (Array.isArray(h) && h.includes(n.message) || typeof h == "string" && n.message === h) && (n.message = ""), n;
449
+ }
450
+ function C(e) {
451
+ return e >= 200 && e < 400;
452
+ }
453
+ function A(e, t) {
454
+ return t === "camelize" ? O(e) : t === "snakify" ? k(e) : e;
455
+ }
456
+ const ye = z("APIError");
457
+ function pe(e) {
458
+ const t = {};
459
+ for (const o in e.headers)
460
+ (o.startsWith("x-") || o.includes("trace") || o.includes("server") || /\b(?:id|uuid)\b/.test(o)) && (t[o] = e.headers[o]);
461
+ const s = e.url.replace(/^(?:https?:)?\/*/i, "").replace(/\?.+/, ""), r = e.status < 0 ? "unknown" : e.status;
462
+ return {
463
+ sentryError: new ye(`${s} | ${r}${e.code ? ` | ${e.code}` : ""}`),
464
+ sentryTags: {
465
+ ...t,
466
+ status: r,
467
+ method: e.method,
468
+ code: e.code || "unknown",
469
+ message: e.message || "empty"
470
+ },
471
+ sentryExtra: {
472
+ url: e.url,
473
+ responseBody: e.body || "empty",
474
+ responseHeaders: e.headers,
475
+ rawError: e.error
476
+ }
477
+ };
478
+ }
479
+ function be(e) {
480
+ return e.reduce(
481
+ (t, [s, r]) => (s && (t[s] = r || ""), t),
482
+ {}
483
+ );
484
+ }
485
+ function ve(e, t, s, r) {
486
+ var m;
487
+ const o = e.status, n = e.method, a = be(
488
+ Object.entries(e.headers || {}).map(([p, y]) => [p.toLowerCase(), y])
489
+ ), { ok: i, code: u, data: f, message: l } = ue(
490
+ o,
491
+ e.statusText,
492
+ e.body,
493
+ s.get("responseRule"),
494
+ r == null ? void 0 : r.responseRule
495
+ );
496
+ if (!C(o)) {
497
+ const p = pe({
498
+ url: e.url,
499
+ method: e.method,
500
+ status: o,
501
+ code: u,
502
+ message: l,
503
+ body: e.body,
504
+ headers: a,
505
+ error: e.rawError
506
+ });
507
+ (s.get("errorHandler") || we)({
508
+ url: t,
509
+ method: n,
510
+ status: o,
511
+ code: u,
512
+ message: l,
513
+ headers: a,
514
+ rawError: e.rawError,
515
+ responseBody: e.body,
516
+ ...p
517
+ });
518
+ }
519
+ if (o < 0)
520
+ return P(
521
+ { ok: !1, status: o, code: e.statusText, headers: {}, message: "", data: null },
522
+ `${n} ${t} ${e.statusText}`,
523
+ n,
524
+ t,
525
+ s,
526
+ r
527
+ );
528
+ const h = { ok: i, data: f, code: u, message: l, status: o, headers: a };
529
+ (m = s.get("responseHandler")) == null || m({ ...h }, n, t);
530
+ const g = i ? l : l || e.statusText;
531
+ return P(h, g, n, t, s, r);
532
+ }
533
+ function P(e, t, s, r, o, n) {
534
+ const a = o.get("message"), i = a === !1 || (n == null ? void 0 : n.message) === !1 ? !1 : (n == null ? void 0 : n.message) || a;
535
+ if (i !== !1) {
536
+ const u = typeof i == "function" ? i(e, s, r, t) : t;
537
+ u instanceof Error ? o.showMessage(!0, u.message, e.code, e.status) : u && typeof u == "object" && "message" in u ? o.showMessage(!1, u.message, e.code, e.status) : o.showMessage(!e.ok, u, e.code, e.status);
538
+ }
539
+ return e;
540
+ }
541
+ function we(e) {
542
+ const t = {};
543
+ for (const s in e)
544
+ s.startsWith("sentry") || (t[s] = e[s]);
545
+ console.error("RequestError", t);
546
+ }
547
+ async function $e(e, t, s, r, o) {
548
+ const n = o || 0, a = Math.max(0, Math.min(10, (r == null ? void 0 : r.maxRetry) ?? s.get("maxRetry") ?? 0)), i = (r == null ? void 0 : r.retryResolve) ?? s.get("retryResolve"), u = s.get("logHandler") || J;
549
+ u({
550
+ type: "prepare",
551
+ url: t,
552
+ method: (r == null ? void 0 : r.method) || "GET",
553
+ retry: n,
554
+ maxRetry: a,
555
+ message: n === 0 ? "start" : `retry ${n}/${a} start`,
556
+ headers: r == null ? void 0 : r.headers,
557
+ options: r
558
+ });
559
+ const f = Date.now(), l = await e(t, s, r), h = l.status, g = Date.now() - f, m = `[cost ${g}][${h}] ${h < 0 ? l.body : ""}`;
560
+ u({
561
+ type: "finished",
562
+ url: t,
563
+ method: l.method,
564
+ retry: n,
565
+ maxRetry: a,
566
+ message: n === 0 ? `finish ${m}` : `retry ${n}/${a} finish ${m}`,
567
+ response: l,
568
+ headers: l.headers,
569
+ cost: g
570
+ });
571
+ const p = C(h);
572
+ if (!a || i === "network" && h > 0 || i === "status" && p || Array.isArray(i) && !i.includes(h) || typeof i == "function" && i(l, n) !== !0 || n >= a)
573
+ return l;
574
+ const y = (r == null ? void 0 : r.retryInterval) ?? s.get("retryInterval") ?? 100;
575
+ return await K(
576
+ Math.max(
577
+ 100,
578
+ y === "2EB" ? Math.pow(2, n) * 100 : typeof y == "function" ? y(n + 1) || 0 : y
579
+ )
580
+ ), await $e(e, t, s, r, n + 1);
581
+ }
582
+ export {
583
+ U as $,
584
+ je as G,
585
+ ke as N,
586
+ oe as R,
587
+ Oe as a,
588
+ S as b,
589
+ Ee as c,
590
+ E as d,
591
+ be as f,
592
+ Fe as g,
593
+ ve as h,
594
+ $e as r
595
+ };
package/dist/wx.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-B9vBp2mw.cjs"),l=async function(t,n,u){return e.handleResponse(await e.retryRequest(f,t,n,u),t,n,u)},f=async function(t,n,u){const s=await e.convertOptions(t,n,u),a=s.method==="PATCH"?"POST":s.method,c=e.Zt(s.url,s.params);return e.lt.wx?new Promise(d=>{wx.request({url:c,data:s.body,header:s.headers,method:a,dataType:"string",responseType:"text",fail(){d({url:c,method:a,status:-1,statusText:e.RequestInteralError.Unknown,body:""})},success(r){d({url:c,method:a,status:r.statusCode,statusText:r.statusCode+"",headers:{...r.header},body:s.method==="HEAD"||r.statusCode===204?"":p(r.data)})}})}):{url:c,method:a,status:-1,statusText:e.RequestInteralError.NotSupport,body:""}};function p(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.lt.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(l,t)}const o=i(),y=o.setConfig,g=o.head,h=o.get,q=o.post,x=o.del,R=o.put;exports.NetRequest=i;exports.del=x;exports.get=h;exports.head=g;exports.post=q;exports.put=R;exports.setGlobalConfig=y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-DsJb9GfI.cjs"),l=async function(t,r,u){return e.handleResponse(await e.retryRequest(f,t,r,u),t,r,u)},f=async function(t,r,u){const s=await e.convertOptions(t,r,u),a=s.method==="PATCH"?"POST":s.method,c=e.ce(s.url,s.params);return e.Rt.wx?new Promise(d=>{wx.request({url:c,data:s.body,header:s.headers,method:a,dataType:"string",responseType:"text",fail(){d({url:c,method:a,status:-1,statusText:e.RequestInternalError.Unknown,body:""})},success(n){d({url:c,method:a,status:n.statusCode,statusText:n.statusCode+"",headers:{...n.header},body:s.method==="HEAD"||n.statusCode===204?"":p(n.data)})}})}):{url:c,method:a,status:-1,statusText:e.RequestInternalError.NotSupport,body:""}};function p(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.Rt.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(l,t)}const o=i(),y=o.setConfig,g=o.head,h=o.get,R=o.post,q=o.del,x=o.put;exports.NetRequest=i;exports.del=q;exports.get=h;exports.head=g;exports.post=R;exports.put=x;exports.setGlobalConfig=y;
package/dist/wx.js CHANGED
@@ -1,8 +1,8 @@
1
- import { h as l, r as f, c as p, Z as h, l as i, a as d, N as y } from "./retry-Ch1GFMrA.js";
1
+ import { h as f, r as p, c as l, a as h, d as i, b as d, N as y } from "./retry-zhJVeNp_.js";
2
2
  const x = async function(t, n, r) {
3
- return l(await f(m, t, n, r), t, n, r);
3
+ return f(await p(m, t, n, r), t, n, r);
4
4
  }, m = async function(t, n, r) {
5
- const e = await p(t, n, r), a = e.method === "PATCH" ? "POST" : e.method, u = h(e.url, e.params);
5
+ const e = await l(t, n, r), a = e.method === "PATCH" ? "POST" : e.method, u = h(e.url, e.params);
6
6
  return i.wx ? new Promise((c) => {
7
7
  wx.request({
8
8
  url: u,
@@ -42,16 +42,16 @@ const x = async function(t, n, r) {
42
42
  function w(t) {
43
43
  return typeof t == "string" ? t : t instanceof ArrayBuffer && i.TextDecoder ? new TextDecoder().decode(t) : JSON.stringify(t);
44
44
  }
45
- function T(t) {
45
+ function R(t) {
46
46
  return new y(x, t);
47
47
  }
48
- const s = T(), q = s.setConfig, R = s.head, b = s.get, C = s.post, N = s.del, S = s.put;
48
+ const s = R(), g = s.setConfig, q = s.head, b = s.get, C = s.post, N = s.del, S = s.put;
49
49
  export {
50
- T as NetRequest,
50
+ R as NetRequest,
51
51
  N as del,
52
52
  b as get,
53
- R as head,
53
+ q as head,
54
54
  C as post,
55
55
  S as put,
56
- q as setGlobalConfig
56
+ g as setGlobalConfig
57
57
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "2.1.2",
4
- "description": "requst tools for seayoo web",
3
+ "version": "3.0.0",
4
+ "description": "request tools for seayoo web",
5
5
  "type": "module",
6
6
  "source": "./src/index.ts",
7
7
  "main": "./dist/index.js",
@@ -59,7 +59,7 @@
59
59
  "happy-dom": "^12.10.3",
60
60
  "msw": "^2.7.0",
61
61
  "vitest": "^3.0.5",
62
- "@seayoo-web/utils": "^3.0.8"
62
+ "@seayoo-web/utils": "^3.3.3"
63
63
  },
64
64
  "scripts": {
65
65
  "build": "vite build && tsc --emitDeclarationOnly",
@@ -1,4 +1,4 @@
1
- import type { TypeGuardParam, IRequestOptions, IRequestGlobalConfig, IResponseResult, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./type";
1
+ import { type TypeGuardParam, type IRequestOptions, type IRequestGlobalConfig, type IResponseResult, type NetRequestAgent, type ResponseWithType, type ResponseWithoutType } from "./type";
2
2
  type RequestBody = NonNullable<IRequestOptions["body"]>;
3
3
  /** 工具函数主类 */
4
4
  export declare class NetRequestHandler {
@@ -15,7 +15,7 @@ export declare class NetRequestHandler {
15
15
  */
16
16
  private guard;
17
17
  /**
18
- * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
18
+ * 修改默认请求配置: baseURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
19
19
  */
20
20
  setConfig(config: IRequestGlobalConfig): void;
21
21
  /**
@@ -3,7 +3,7 @@ type ResponseInfo = Pick<IResponseResult, "ok" | "code" | "data" | "message">;
3
3
  /**
4
4
  * 分析响应内容中的错误信息和数据
5
5
  */
6
- export declare function analyseResponse(status: number, statusText: string, responseText: string, globalRule: IResponseRule, rule?: IResponseRule): ResponseInfo;
6
+ export declare function analysesResponse(status: number, statusText: string, responseText: string, globalRule: IResponseRule, rule?: IResponseRule): ResponseInfo;
7
7
  /**
8
8
  * 将 Response Rules 转化成为自然描述语言
9
9
  */