@seayoo-web/request 1.7.10 → 2.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.
@@ -1,499 +0,0 @@
1
- var K = Object.defineProperty;
2
- var q = (t, e, n) => e in t ? K(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n;
3
- var f = (t, e, n) => (q(t, typeof e != "symbol" ? e + "" : e, n), n);
4
- const m = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof window < "u" ? window : {}, O = {
5
- fetch: "fetch" in m,
6
- window: "window" in m,
7
- FormData: "FormData" in m,
8
- Blob: "Blob" in m,
9
- wx: "wx" in m,
10
- TextDecoder: "TextDecoder" in m,
11
- AbortController: "AbortController" in m
12
- };
13
- function N(t) {
14
- return t.reduce(
15
- (e, [n, s]) => (n && (e[n] = s || ""), e),
16
- {}
17
- );
18
- }
19
- function G(t) {
20
- return new Promise((e) => setTimeout(e, Math.max(0, t)));
21
- }
22
- function J() {
23
- }
24
- function j(t) {
25
- return t ? t[0].toLowerCase() + t.slice(1) : "";
26
- }
27
- const P = /_\w*/, S = /-\w*/;
28
- function M(t) {
29
- const e = P.test(t) ? t.replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (n, s) => s.toUpperCase()) : S.test(t) ? t.replace(/(?:^-*|-*$)/g, "").replace(/-+(\w)/g, (n, s) => s.toUpperCase()) : t;
30
- return j(e);
31
- }
32
- function U(t) {
33
- return P.test(t) ? j(t).replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (e, n) => "_" + n.toLowerCase()) : S.test(t) ? j(t.replace(/(?:^-*|-*$)/g, "")).replace(/-+(\w)/g, (e, n) => "_" + n.toLowerCase()) : j(t).replace(/[A-Z]/g, (e) => `_${e.toLowerCase()}`);
34
- }
35
- const V = /^(?:https?:)?\/\/.+$/i, W = /^https?:\/\/.+$/i, Z = /^\{[\d\D]*\}$/, z = /^\[[\d\D]*\]$/;
36
- function T(t, e = !1) {
37
- return e ? V.test(t) : W.test(t);
38
- }
39
- function Q(t) {
40
- return t == null;
41
- }
42
- function v(t, ...e) {
43
- if (!t || typeof t != "object")
44
- return !1;
45
- const n = Object.getPrototypeOf(t);
46
- return n !== Object.prototype && n !== null ? !1 : e.every((s) => s in t);
47
- }
48
- function H(t) {
49
- return Z.test(t) || z.test(t);
50
- }
51
- function C(t, e) {
52
- try {
53
- const n = JSON.parse(t);
54
- return e ? e(n) ? n : null : n;
55
- } catch {
56
- return null;
57
- }
58
- }
59
- "" + Math.random().toString(32).slice(2);
60
- function R(t, e = !1) {
61
- return typeof t == "string" ? M(t) : Array.isArray(t) ? t.map((n) => !e || typeof n == "string" ? R(n) : typeof n == "object" && n ? R(n, !0) : n) : v(t) ? Object.keys(t).reduce(
62
- (n, s) => {
63
- const r = M(String(s)), a = r.charAt(0).toLowerCase() + r.slice(1);
64
- return n[a] = e ? t[s] : R(t[s]), n;
65
- },
66
- {}
67
- ) : t;
68
- }
69
- function $(t, e = !1) {
70
- return typeof t == "string" ? U(t) : Array.isArray(t) ? t.map((n) => !e || typeof n == "string" ? $(n) : typeof n == "object" && n ? $(n, e) : n) : v(t) ? Object.keys(t).reduce(
71
- (n, s) => {
72
- const r = U(String(s));
73
- return n[r] = e ? t[s] : $(t[s]), n;
74
- },
75
- {}
76
- ) : t;
77
- }
78
- async function ye(t) {
79
- return await new Promise(function(e) {
80
- const n = document.getElementsByTagName("head")[0], s = document.createElement("script");
81
- s.setAttribute("type", "text/javascript"), s.setAttribute("charset", "utf-8"), s.onload = function() {
82
- n.removeChild(s), e(!0);
83
- }, s.onerror = function() {
84
- n.removeChild(s), e(!1);
85
- }, s.setAttribute("src", t), n.appendChild(s);
86
- });
87
- }
88
- function X(t, e = "数据未能正确识别") {
89
- return typeof t == "function" ? {
90
- guard: t,
91
- message: e
92
- } : {
93
- guard: t.guard,
94
- message: t.message || e
95
- };
96
- }
97
- function x(t, e = "") {
98
- return !e || T(t, !0) ? L(t) : (L(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
99
- }
100
- function L(t) {
101
- return T(t, !0) ? t.startsWith("http") ? t : ("location" in globalThis ? location.protocol : "https:") + t : ("location" in globalThis ? location.origin : "http://127.0.0.1") + "/" + t.replace(/^\/+/, "");
102
- }
103
- function Y(t, e) {
104
- const n = {};
105
- return (t.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(s) {
106
- const r = s.split("="), a = r[0], o = decodeURIComponent(r[1] || "");
107
- n[a] !== void 0 ? n[a] += "," + o : n[a] = o;
108
- }), e !== !0 ? n[e] || "" : n;
109
- }
110
- function ee(t, e) {
111
- if (e) {
112
- if (e === !0)
113
- return t.replace(/\?[^#]*/, "");
114
- } else
115
- return t;
116
- const n = t.split("#"), s = n[0].split("?"), r = s[0], a = s.length > 1 ? s[1] : "", o = n.length > 1 ? "#" + n[1] : "", c = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
117
- return !c.length || !a ? n[0] + o : (c.map((i) => i.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + a.replace(new RegExp("(?:^|&)(?:" + c.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
118
- }
119
- function pe(t, e, n = !1) {
120
- const s = typeof e == "string" ? e : Object.keys(e).map((o) => `${o}=${encodeURIComponent(e[o])}`).join("&");
121
- if (!s)
122
- return t;
123
- const r = t.split("#");
124
- n && (r[0] = ee(
125
- r[0],
126
- (s.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
127
- ));
128
- const a = r[0].indexOf("?") + 1 ? "&" : "?";
129
- return (r[0] + a + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
130
- }
131
- function te(t) {
132
- const e = t.match(/(?:\?|&)([^=]+)(?:&|$)/g);
133
- return e ? e.join("").replace(/(?:\?|^&+|&+$)/g, "").replace(/&{2}/g, "&").split("&").sort() : [];
134
- }
135
- class se {
136
- constructor(e = 500) {
137
- f(this, "ttl");
138
- f(this, "cache");
139
- this.cache = {}, this.ttl = Math.max(e, 0);
140
- }
141
- getKey(e, n) {
142
- const s = e.replace(/#.+/, ""), r = s.replace(/\?.+/g, ""), a = Object.assign(Y(s, !0), n), o = te(s), c = Object.keys(a).sort().map((i) => `${i}#${a[i]}`);
143
- return `${r}_${c.join(",")}_${o.join(",")}`;
144
- }
145
- updateTTL(e) {
146
- this.ttl = Math.max(e, 0);
147
- }
148
- get(e) {
149
- if (this.ttl === 0)
150
- return null;
151
- const n = this.cache[e];
152
- return n ? n.ttl < Date.now() ? (delete this.cache[e], null) : n.res : null;
153
- }
154
- set(e, n) {
155
- this.ttl !== 0 && (this.cache[e] = {
156
- ttl: Date.now() + this.ttl,
157
- res: n
158
- });
159
- }
160
- }
161
- const D = "UnexpectResponse";
162
- function ne(t, e, n, s) {
163
- if (e.ok && !Q(e.data) && s) {
164
- const r = X(s, "响应数据未能正确识别");
165
- return r.guard(e.data) || (n.showMessage(!0, `${t} ${r.message}`, e.code, e.status), console.error(D, t, e.data), e.data = null, e.code = D, e.message = r.message), e;
166
- }
167
- return e;
168
- }
169
- class ae {
170
- constructor(e) {
171
- // 保存的配置需要部分字段强制设置默认值
172
- f(this, "config", {
173
- baseURL: "",
174
- maxRetry: 0,
175
- retryInterval: 1e3,
176
- retryResolve: "network",
177
- timeout: 1e4,
178
- cacheTTL: 500,
179
- credentials: "same-origin",
180
- responseRule: {
181
- ok: {
182
- resolve: "body"
183
- },
184
- failed: {
185
- resolve: "json",
186
- messageField: "message"
187
- }
188
- }
189
- });
190
- e && this.set(e);
191
- }
192
- set(e) {
193
- if (e.baseURL && !/^\/.+/.test(e.baseURL) && !T(e.baseURL))
194
- throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
195
- Object.assign(this.config, e);
196
- }
197
- get(e) {
198
- return this.config[e];
199
- }
200
- /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
201
- getFullUrl(e) {
202
- return e.startsWith("/") ? x(e) : x(e, this.config.baseURL);
203
- }
204
- /** 提示消息 */
205
- showMessage(e, n, s, r) {
206
- this.config.messageHandler && n && this.config.messageHandler(e, n, s, r);
207
- }
208
- }
209
- class be {
210
- constructor(e, n) {
211
- f(this, "agent");
212
- f(this, "config");
213
- f(this, "cache");
214
- this.config = new ae(n), this.agent = e, this.cache = new se(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.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);
215
- }
216
- /**
217
- * 执行网络请求
218
- */
219
- async exec(e, n) {
220
- try {
221
- return await this.agent(e, this.config, n);
222
- } catch (s) {
223
- return console.error("RequestError", s), {
224
- ok: !1,
225
- status: -9,
226
- code: "Unkonwn",
227
- message: String(s),
228
- headers: {},
229
- data: null
230
- };
231
- }
232
- }
233
- /**
234
- * 检查响应的数据类型
235
- */
236
- async guard(e, n, s) {
237
- return ne(e, n, this.config, s);
238
- }
239
- /**
240
- * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
241
- */
242
- setConfig(e) {
243
- this.config.set(e), this.cache.updateTTL(this.config.get("cacheTTL"));
244
- }
245
- /**
246
- * 读取默认的请求配置
247
- */
248
- getConfig(e) {
249
- return this.config.get(e);
250
- }
251
- /**
252
- * 发送一个 HEAD 请求,并且不处理响应 body
253
- */
254
- async head(e, n) {
255
- const s = Object.assign({}, n || null);
256
- return s.method = "HEAD", this.guard(e, await this.exec(e, s), null);
257
- }
258
- async get(e, n, s) {
259
- const r = Object.assign({}, s || null);
260
- r.method = "GET";
261
- const a = this.cache.getKey(e, r.params), o = this.cache.get(a);
262
- if (o)
263
- return this.guard(e, await o, n || null);
264
- const c = this.exec(e, r);
265
- return this.cache.set(a, c), this.guard(e, await c, n || null);
266
- }
267
- async post(e, n, s, r) {
268
- const a = Object.assign({}, r || null);
269
- return a.method = "POST", a.body = n, this.guard(e, await this.exec(e, a), s || null);
270
- }
271
- async del(e, n, s) {
272
- const r = Object.assign({}, s || null);
273
- return r.method = "DELETE", this.guard(e, await this.exec(e, r), n || null);
274
- }
275
- async put(e, n, s, r) {
276
- const a = Object.assign({}, r || null);
277
- return a.method = "PUT", a.body = n, this.guard(e, await this.exec(e, a), s || null);
278
- }
279
- async patch(e, n, s, r) {
280
- const a = Object.assign({}, r || null);
281
- return a.method = "PATCH", a.body = n, this.guard(e, await this.exec(e, a), s || null);
282
- }
283
- }
284
- const I = "data", b = "message";
285
- function re(t, e, n, s, r) {
286
- const a = r || s;
287
- return A(t) ? he(a.ok || s.ok, t, e, n) : oe(a.failed || s.failed, e, n);
288
- }
289
- const we = function(t) {
290
- const e = [], n = t.failed || { resolve: "json" };
291
- switch (e.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
292
- case "body":
293
- e.push(" 将响应内容格式化为字符串并作为错误消息");
294
- break;
295
- case "json":
296
- e.push(" 将响应解析为json,并读取 " + (n.messageField || b) + " 作为错误消息");
297
- break;
298
- }
299
- const s = t.ok || { resolve: "body" };
300
- switch (e.push("- 当http状态码 >=200 并且 <400 时"), s.resolve) {
301
- case "body":
302
- e.push(" 将响应尝试解析为 json,并作为数据内容返回");
303
- break;
304
- case "json":
305
- e.push(
306
- " 将响应解析为 json,读取 " + (s.dataField || I) + " 作为响应数据,读取 " + (s.messageField || b) + " 作为提示消息"
307
- ), s.statusField && e.push(" 当 " + s.statusField + " 为 " + (s.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"), s.ignoreMessage && e.push(" 并忽略以下消息:" + s.ignoreMessage);
308
- break;
309
- }
310
- return e.join(`
311
- `);
312
- };
313
- function oe(t, e, n) {
314
- const s = t || { resolve: "json", messageField: b }, r = {
315
- ok: !1,
316
- code: e,
317
- message: n,
318
- data: null
319
- };
320
- switch (s.resolve) {
321
- case "body":
322
- r.message = _(n) || n;
323
- break;
324
- case "json":
325
- const { code: a, message: o } = ce(n, s.converter, s.statusField, s.messageField);
326
- r.code = a || e, r.message = _(n) || o;
327
- break;
328
- }
329
- return r;
330
- }
331
- function ce(t, e, n, s = b) {
332
- if (!H(t))
333
- return { message: "" };
334
- const r = k(C(t), e);
335
- return !r || !v(r) ? { message: t } : {
336
- code: n ? F(r, n) : "",
337
- message: F(r, s) || t
338
- };
339
- }
340
- function F(t, e) {
341
- const n = Array.isArray(e) ? e : [e];
342
- for (const s of n)
343
- if (s in t)
344
- return ie(t[s]);
345
- return "";
346
- }
347
- function ie(t) {
348
- return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
349
- }
350
- const ue = /<title>([^<]+)<\/title>/i, le = /<message>([^<]+)<\/message>/i;
351
- function _(t) {
352
- const e = t.match(ue);
353
- if (e)
354
- return e[1];
355
- const n = t.match(le);
356
- return n ? n[1] : "";
357
- }
358
- function he(t, e, n, s) {
359
- const r = t || { resolve: "body" }, a = {
360
- ok: !0,
361
- code: n,
362
- message: "",
363
- data: null
364
- };
365
- if (e === 204 || !s)
366
- return a;
367
- if (r.resolve === "body")
368
- return a.data = H(s) ? k(C(s), t.converter) : s, a;
369
- const o = k(C(s), t.converter);
370
- if (!o || !v(o))
371
- return a.ok = !1, a.code = "ResponseFormatError", a.message = "响应内容无法格式化为 Object", a;
372
- const c = r.statusField, i = r.statusOKValue || "", h = r.dataField || I, l = r.messageField || b, u = r.ignoreMessage || "";
373
- if (c && !(c in o))
374
- return a.ok = !1, a.code = "ResponseFieldMissing", a.message = "响应内容找不到状态字段 " + c, a;
375
- const d = c ? o[c] + "" : "";
376
- return a.ok = c ? d === i : !0, a.code = d || n, a.data = h === !0 ? o : h in o ? o[h] : null, a.message = F(o, l), u && a.message && (Array.isArray(u) && u.includes(a.message) || typeof u == "string" && a.message === u) && (a.message = ""), a;
377
- }
378
- function A(t) {
379
- return t >= 200 && t < 400;
380
- }
381
- function k(t, e) {
382
- return e === "camelize" ? R(t) : e === "snakify" ? $(t) : t;
383
- }
384
- async function de(t, e, n, s, r) {
385
- const a = r || 0, o = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? n.get("maxRetry") ?? 0)), c = (s == null ? void 0 : s.retryResolve) ?? n.get("retryResolve"), i = n.get("logHandler") || J;
386
- i({
387
- type: "prepear",
388
- url: e,
389
- method: (s == null ? void 0 : s.method) || "GET",
390
- retry: a,
391
- maxRetry: o,
392
- message: a === 0 ? "start" : `retry ${a}/${o} start`,
393
- headers: s == null ? void 0 : s.headers,
394
- options: s
395
- });
396
- const h = Date.now(), l = await t(e, n, s), u = l.status, d = Date.now() - h, y = `[cost ${d}][${u}] ${u < 0 ? l.body : ""}`;
397
- i({
398
- type: "finished",
399
- url: e,
400
- method: l.method,
401
- retry: a,
402
- maxRetry: o,
403
- message: a === 0 ? `finish ${y}` : `retry ${a}/${o} finish ${y}`,
404
- response: l,
405
- headers: l.headers,
406
- cost: d
407
- });
408
- const w = A(u);
409
- if (!o || c === "network" && u > 0 || c === "status" && w || Array.isArray(c) && !c.includes(u) || typeof c == "function" && c(l, a) !== !0 || a >= o)
410
- return l;
411
- const g = (s == null ? void 0 : s.retryInterval) ?? n.get("retryInterval") ?? 1e3;
412
- return await G(
413
- Math.max(
414
- 100,
415
- g === "2EB" ? Math.pow(2, a) * 1e3 : typeof g == "function" ? g(a + 1) || 0 : g
416
- )
417
- ), await de(t, e, n, s, a + 1);
418
- }
419
- async function je(t, e, n) {
420
- var g;
421
- const s = Object.assign({ method: "GET" }, n), r = O.FormData ? s.body instanceof FormData : !1, a = r && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method, o = a === "GET" || a === "HEAD" || a === "DELETE";
422
- o && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
423
- const c = Object.assign(
424
- r || o ? {} : {
425
- "Content-Type": O.Blob && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8"
426
- },
427
- s.headers
428
- ), i = s.params || {}, h = {};
429
- Object.keys(i).forEach((p) => {
430
- i[p] !== void 0 && (h[p] = ge(i[p]));
431
- });
432
- const l = e.getFullUrl(t), u = fe(s.body), d = s.timeout || e.get("timeout"), y = await async function() {
433
- var E;
434
- const p = e.get("requestTransformer");
435
- return p ? await p({ headers: c, params: h, method: a, url: l, body: u }) : await ((E = e.get("requestHandler")) == null ? void 0 : E(c, h, a, t));
436
- }(), w = typeof y == "string" && y ? y : l;
437
- return (g = e.get("logHandler")) == null || g({ type: "ready", url: w, method: a, headers: c, timeout: d, body: u }), {
438
- url: w,
439
- method: a,
440
- body: u,
441
- params: h,
442
- headers: c,
443
- timeout: d,
444
- abort: s.abort,
445
- credentials: s.credentials || e.get("credentials")
446
- };
447
- }
448
- function ge(t) {
449
- return typeof t == "string" ? t : Array.isArray(t) ? t.join(",") : t + "";
450
- }
451
- function fe(t) {
452
- if (t)
453
- return typeof t == "string" || t instanceof URLSearchParams || t instanceof ArrayBuffer || O.Blob && t instanceof Blob || O.FormData && t instanceof FormData ? t : JSON.stringify(t);
454
- }
455
- function Re(t, e, n, s) {
456
- var c, i;
457
- if (t.status < 0)
458
- return B(
459
- { ok: !1, status: t.status, code: t.statusText, headers: {}, message: "", data: null },
460
- `${t.method} ${e} ${t.statusText}`,
461
- t.method,
462
- e,
463
- n,
464
- s
465
- );
466
- const r = N(Object.entries(t.headers || {}).map(([h, l]) => [h.toLowerCase(), l]));
467
- A(t.status) || (c = n.get("errorHandler")) == null || c(t.status, t.method, e, r, t.rawError);
468
- const a = {
469
- ...re(t.status, t.statusText, t.body, n.get("responseRule"), s == null ? void 0 : s.responseRule),
470
- status: t.status,
471
- headers: r
472
- };
473
- (i = n.get("responseHandler")) == null || i({ ...a }, t.method, e);
474
- const o = a.ok ? a.message : a.message || t.statusText;
475
- return B(a, o, t.method, e, n, s);
476
- }
477
- function B(t, e, n, s, r, a) {
478
- const o = r.get("message"), c = o === !1 || (a == null ? void 0 : a.message) === !1 ? !1 : (a == null ? void 0 : a.message) || o;
479
- if (c !== !1) {
480
- const i = typeof c == "function" ? c(t, n, s, e) : e;
481
- i instanceof Error ? r.showMessage(!0, i.message, t.code, t.status) : i && typeof i == "object" && "message" in i ? r.showMessage(!1, i.message, t.code, t.status) : r.showMessage(!t.ok, i, t.code, t.status);
482
- }
483
- return t;
484
- }
485
- const $e = "1.7.10";
486
- export {
487
- T as G,
488
- be as N,
489
- ae as R,
490
- O as S,
491
- pe as W,
492
- je as c,
493
- N as f,
494
- we as g,
495
- Re as h,
496
- de as r,
497
- $e as v,
498
- ye as x
499
- };