@seayoo-web/request 3.3.1 → 3.3.3
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/dist/index.cjs +2 -2
- package/dist/index.js +32 -32
- package/dist/node.cjs +1 -1
- package/dist/node.js +13 -13
- package/dist/{request.fetch-BJaP3VPV.js → request.fetch-CHbeHmeX.js} +1 -1
- package/dist/{request.fetch-0OA7qu9S.cjs → request.fetch-Ce3_4Yuj.cjs} +1 -1
- package/dist/{retry-vMhW20_a.js → retry-BXoyQlSJ.js} +169 -137
- package/dist/retry-D_7OkloZ.cjs +3 -0
- package/dist/wx.cjs +1 -1
- package/dist/wx.js +10 -10
- package/package.json +2 -2
- package/types/inc/cache.d.ts +3 -0
- package/dist/retry-sL4_1f7S.cjs +0 -3
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./retry-
|
|
2
|
-
`).forEach(n=>{const o=n.trim();if(!o)return;const u=o.split(":"),c=u[0].trim();c&&(s[c]=(u[1]||"").trim())}),s}async function H(t,s,e={}){const n=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const o=e.callback+"";if(!t)return null;const u=r.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./retry-D_7OkloZ.cjs"),m=require("./request.fetch-Ce3_4Yuj.cjs"),y=async function(t,s,e){return r.handleResponse(await r.retryRequest(R,t,s,e),t,s,e)};async function E(t,s,e,n){const o=e?.body,u=e?.method==="PUT"?"PUT":"POST";if(s instanceof Blob){const l=new r.RequestGlobalConfig(n),f=await R(t,l,{...e,method:u,body:s});return r.handleResponse(f,t,l,e)}const c=new FormData,d={...s};o instanceof Object&&Object.entries(o).forEach(([l,f])=>{f instanceof Blob?d[l]=f:Array.isArray(f)?f.forEach((a,b)=>{c.append(`${l}[${b}]`,String(a))}):c.append(l,String(f))});for(const l in d)c.append(l,d[l]);const g=new r.RequestGlobalConfig(n),w=await R(t,g,{...e,method:u,body:c});return r.handleResponse(w,t,g,e)}const R=async function(t,s,e){const n=await r.convertOptions(t,s,e),o=n.method,u=e?.onUploadProgress,c=r.pe(n.url,n.params);return await new Promise(d=>{let g=null,w=!1;const l=function(){w||(a.abort(),w=!0)};function f(){g!==null&&clearTimeout(g),n.abort&&n.abort.removeEventListener("abort",l)}const a=new XMLHttpRequest;let b=!1;if(a.open(o,c,!0),u){let p=1;a.upload.addEventListener("progress",h=>{p=h.total,u({total:h.total,loaded:h.loaded})}),a.addEventListener("load",()=>{u({loaded:p,total:p})})}a.addEventListener("load",()=>{const p=a.status;f(),d({url:c,method:o,status:p,statusText:a.statusText,headers:T(a),body:o==="HEAD"||p===204?"":a.responseText})}),a.addEventListener("error",p=>{f(),d({url:c,method:o,status:a.status||-1,statusText:a.statusText||r.RequestInternalError.NetworkError,body:"",rawError:p})},!0),a.addEventListener("abort",()=>{f(),d({url:c,method:o,status:b?-1:0,statusText:b?r.RequestInternalError.Timeout:r.RequestInternalError.Aborted,body:""})}),Object.entries(n.headers).forEach(([p,h])=>{a.setRequestHeader(p,h)}),n.credentials==="include"&&(a.withCredentials=!0),a.send(n.body||void 0),n.abort&&n.abort.addEventListener("abort",l),n.timeout>0&&(g=setTimeout(function(){b=!0,l()},n.timeout))})};function T(t){const s={};if(!t)return s;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
|
|
2
|
+
`).forEach(n=>{const o=n.trim();if(!o)return;const u=o.split(":"),c=u[0].trim();c&&(s[c]=(u[1]||"").trim())}),s}async function H(t,s,e={}){const n=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const o=e.callback+"";if(!t)return null;const u=r.pe(t,e,!0);return new Promise(c=>{n[o]=function(d){if(o in window&&delete n[o],s(d))return d;console.warn("response type check failed",t,d),c(null)},r.ce(u).catch(function(){c(null),delete n[o]})})}async function x(t,s,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await r.ce(r.pe(t,e,!0)).then(()=>{const o=n[e.var+""];return s(o)?o:(console.warn("response type check failed",t,o),null)}).catch(()=>null):null}const C=async function(t,s,e){return await E(t,s,e,{baseURL:i.getConfig("baseURL"),logHandler:i.getConfig("logHandler"),errorHandler:i.getConfig("errorHandler"),requestTransformer:i.getConfig("requestTransformer"),messageHandler:i.getConfig("messageHandler"),responseHandler:i.getConfig("responseHandler")})};function q(t){if(!r.St.window)throw new Error("Default Module Only Support In Browser");return r.St.fetch?new r.NetRequestHandler(m.fetchRequest,t):new r.NetRequestHandler(y,t)}const i=q(),S=i.setConfig,j=i.request,L=i.head,k=i.get,v=i.post,D=i.del,U=i.put,O=i.patch;exports.RequestInternalError=r.RequestInternalError;exports.getResponseRulesDescription=r.getResponseRulesDescription;exports.NetRequest=q;exports.del=D;exports.get=k;exports.head=L;exports.jsonp=H;exports.jsonx=x;exports.patch=O;exports.post=v;exports.put=U;exports.request=j;exports.setGlobalConfig=S;exports.upload=C;
|
package/dist/index.js
CHANGED
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
import { h as m, r as x, R as T, c as C,
|
|
2
|
-
import { g as K } from "./retry-
|
|
3
|
-
import { f as L } from "./request.fetch-
|
|
4
|
-
const
|
|
1
|
+
import { h as m, r as x, R as T, c as C, p as R, a as w, b as q, S as E, N as H } from "./retry-BXoyQlSJ.js";
|
|
2
|
+
import { g as K } from "./retry-BXoyQlSJ.js";
|
|
3
|
+
import { f as L } from "./request.fetch-CHbeHmeX.js";
|
|
4
|
+
const S = async function(t, o, e) {
|
|
5
5
|
return m(await x(y, t, o, e), t, o, e);
|
|
6
6
|
};
|
|
7
|
-
async function
|
|
7
|
+
async function k(t, o, e, n) {
|
|
8
8
|
const r = e?.body, l = e?.method === "PUT" ? "PUT" : "POST";
|
|
9
9
|
if (o instanceof Blob) {
|
|
10
|
-
const i = new T(n),
|
|
10
|
+
const i = new T(n), u = await y(t, i, {
|
|
11
11
|
...e,
|
|
12
12
|
method: l,
|
|
13
13
|
body: o
|
|
14
14
|
});
|
|
15
|
-
return m(
|
|
15
|
+
return m(u, t, i, e);
|
|
16
16
|
}
|
|
17
|
-
const a = new FormData(),
|
|
18
|
-
r instanceof Object && Object.entries(r).forEach(([i,
|
|
19
|
-
|
|
17
|
+
const a = new FormData(), d = { ...o };
|
|
18
|
+
r instanceof Object && Object.entries(r).forEach(([i, u]) => {
|
|
19
|
+
u instanceof Blob ? d[i] = u : Array.isArray(u) ? u.forEach((s, g) => {
|
|
20
20
|
a.append(`${i}[${g}]`, String(s));
|
|
21
|
-
}) : a.append(i, String(
|
|
21
|
+
}) : a.append(i, String(u));
|
|
22
22
|
});
|
|
23
|
-
for (const i in
|
|
24
|
-
a.append(i,
|
|
25
|
-
const b = new T(n),
|
|
23
|
+
for (const i in d)
|
|
24
|
+
a.append(i, d[i]);
|
|
25
|
+
const b = new T(n), h = await y(t, b, {
|
|
26
26
|
...e,
|
|
27
27
|
method: l,
|
|
28
28
|
body: a
|
|
29
29
|
});
|
|
30
|
-
return m(
|
|
30
|
+
return m(h, t, b, e);
|
|
31
31
|
}
|
|
32
32
|
const y = async function(t, o, e) {
|
|
33
33
|
const n = await C(t, o, e), r = n.method, l = e?.onUploadProgress, a = R(n.url, n.params);
|
|
34
|
-
return await new Promise((
|
|
35
|
-
let b = null,
|
|
34
|
+
return await new Promise((d) => {
|
|
35
|
+
let b = null, h = !1;
|
|
36
36
|
const i = function() {
|
|
37
|
-
|
|
37
|
+
h || (s.abort(), h = !0);
|
|
38
38
|
};
|
|
39
|
-
function
|
|
39
|
+
function u() {
|
|
40
40
|
b !== null && clearTimeout(b), n.abort && n.abort.removeEventListener("abort", i);
|
|
41
41
|
}
|
|
42
42
|
const s = new XMLHttpRequest();
|
|
43
43
|
let g = !1;
|
|
44
44
|
if (s.open(r, a, !0), l) {
|
|
45
45
|
let f = 1;
|
|
46
|
-
s.upload.addEventListener("progress", (
|
|
47
|
-
f =
|
|
46
|
+
s.upload.addEventListener("progress", (p) => {
|
|
47
|
+
f = p.total, l({ total: p.total, loaded: p.loaded });
|
|
48
48
|
}), s.addEventListener("load", () => {
|
|
49
49
|
l({ loaded: f, total: f });
|
|
50
50
|
});
|
|
51
51
|
}
|
|
52
52
|
s.addEventListener("load", () => {
|
|
53
53
|
const f = s.status;
|
|
54
|
-
|
|
54
|
+
u(), d({
|
|
55
55
|
url: a,
|
|
56
56
|
method: r,
|
|
57
57
|
status: f,
|
|
@@ -62,7 +62,7 @@ const y = async function(t, o, e) {
|
|
|
62
62
|
}), s.addEventListener(
|
|
63
63
|
"error",
|
|
64
64
|
(f) => {
|
|
65
|
-
|
|
65
|
+
u(), d({
|
|
66
66
|
url: a,
|
|
67
67
|
method: r,
|
|
68
68
|
status: s.status || -1,
|
|
@@ -73,7 +73,7 @@ const y = async function(t, o, e) {
|
|
|
73
73
|
},
|
|
74
74
|
!0
|
|
75
75
|
), s.addEventListener("abort", () => {
|
|
76
|
-
|
|
76
|
+
u(), d({
|
|
77
77
|
url: a,
|
|
78
78
|
method: r,
|
|
79
79
|
status: g ? -1 : 0,
|
|
@@ -81,8 +81,8 @@ const y = async function(t, o, e) {
|
|
|
81
81
|
statusText: g ? w.Timeout : w.Aborted,
|
|
82
82
|
body: ""
|
|
83
83
|
});
|
|
84
|
-
}), Object.entries(n.headers).forEach(([f,
|
|
85
|
-
s.setRequestHeader(f,
|
|
84
|
+
}), Object.entries(n.headers).forEach(([f, p]) => {
|
|
85
|
+
s.setRequestHeader(f, p);
|
|
86
86
|
}), n.credentials === "include" && (s.withCredentials = !0), s.send(n.body || void 0), n.abort && n.abort.addEventListener("abort", i), n.timeout > 0 && (b = setTimeout(function() {
|
|
87
87
|
g = !0, i();
|
|
88
88
|
}, n.timeout));
|
|
@@ -110,10 +110,10 @@ async function O(t, o, e = {}) {
|
|
|
110
110
|
return null;
|
|
111
111
|
const l = R(t, e, !0);
|
|
112
112
|
return new Promise((a) => {
|
|
113
|
-
n[r] = function(
|
|
114
|
-
if (r in window && delete n[r], o(
|
|
115
|
-
return
|
|
116
|
-
console.warn("response type check failed", t,
|
|
113
|
+
n[r] = function(d) {
|
|
114
|
+
if (r in window && delete n[r], o(d))
|
|
115
|
+
return d;
|
|
116
|
+
console.warn("response type check failed", t, d), a(null);
|
|
117
117
|
}, q(l).catch(function() {
|
|
118
118
|
a(null), delete n[r];
|
|
119
119
|
});
|
|
@@ -127,7 +127,7 @@ async function P(t, o, e = {}) {
|
|
|
127
127
|
}).catch(() => null) : null;
|
|
128
128
|
}
|
|
129
129
|
const A = async function(t, o, e) {
|
|
130
|
-
return await
|
|
130
|
+
return await k(t, o, e, {
|
|
131
131
|
baseURL: c.getConfig("baseURL"),
|
|
132
132
|
logHandler: c.getConfig("logHandler"),
|
|
133
133
|
errorHandler: c.getConfig("errorHandler"),
|
|
@@ -139,7 +139,7 @@ const A = async function(t, o, e) {
|
|
|
139
139
|
function j(t) {
|
|
140
140
|
if (!E.window)
|
|
141
141
|
throw new Error("Default Module Only Support In Browser");
|
|
142
|
-
return E.fetch ? new H(L, t) : new H(
|
|
142
|
+
return E.fetch ? new H(L, t) : new H(S, t);
|
|
143
143
|
}
|
|
144
144
|
const c = j(), M = c.setConfig, N = c.request, B = c.head, X = c.get, F = c.post, G = c.del, I = c.put, $ = c.patch;
|
|
145
145
|
export {
|
package/dist/node.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-D_7OkloZ.cjs"),y=require("./request.fetch-Ce3_4Yuj.cjs"),b=require("node:http"),g=require("node:https"),E=async function(r,a,c){return e.handleResponse(await e.retryRequest(w,r,a,c),r,a,c)},w=async function(r,a,c){const t=await e.convertOptions(r,a,c);if(!e.At(t.url))return{url:t.url,method:t.method,status:-1,statusText:e.RequestInternalError.URLFormatError,headers:{},body:""};const R=/^https:\/\//i.test(t.url)?g:b,u=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>u.searchParams.set(n,i[n]));const q=t.method==="HEAD";return new Promise(n=>{const d=R.request(u,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(o){const m=[];o.on("data",h=>m.push(h)),o.on("end",()=>{const h=e.fromEntries(Object.entries(o.headers).map(([f,l])=>[f.toLowerCase(),Array.isArray(l)?l.join(","):l]));n({url:u.toString(),method:t.method,status:o.statusCode||-1,statusText:o.statusMessage||e.RequestInternalError.Unknown,headers:h,body:q||o.statusCode===204?"":Buffer.concat(m).toString("utf-8")})})});d.on("error",o=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.NetworkError,body:"",rawError:o})}),d.on("timeout",()=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.Timeout,body:""})}),t.body&&d.write(t.body),d.end()})};function p(r){return e.St.fetch?new e.NetRequestHandler(y.fetchRequest,r):new e.NetRequestHandler(E,r)}const s=p(),S=s.setConfig,C=s.head,I=s.get,N=s.post,T=s.del,j=s.put,O=s.patch;exports.RequestInternalError=e.RequestInternalError;exports.getResponseRulesDescription=e.getResponseRulesDescription;exports.NetRequest=p;exports.del=T;exports.get=I;exports.head=C;exports.patch=O;exports.post=N;exports.put=j;exports.setGlobalConfig=S;
|
package/dist/node.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { h as b, r as q, c as w,
|
|
2
|
-
import { g as J } from "./retry-
|
|
3
|
-
import { f as
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
const
|
|
7
|
-
return b(await q(
|
|
8
|
-
},
|
|
1
|
+
import { h as b, r as q, c as w, A as g, a as d, f as E, N as f, S as x } from "./retry-BXoyQlSJ.js";
|
|
2
|
+
import { g as J } from "./retry-BXoyQlSJ.js";
|
|
3
|
+
import { f as S } from "./request.fetch-CHbeHmeX.js";
|
|
4
|
+
import A from "node:http";
|
|
5
|
+
import C from "node:https";
|
|
6
|
+
const N = async function(o, a, u) {
|
|
7
|
+
return b(await q(T, o, a, u), o, a, u);
|
|
8
|
+
}, T = async function(o, a, u) {
|
|
9
9
|
const t = await w(o, a, u);
|
|
10
10
|
if (!g(t.url))
|
|
11
11
|
return {
|
|
@@ -16,7 +16,7 @@ const j = async function(o, a, u) {
|
|
|
16
16
|
headers: {},
|
|
17
17
|
body: ""
|
|
18
18
|
};
|
|
19
|
-
const R = /^https:\/\//i.test(t.url) ?
|
|
19
|
+
const R = /^https:\/\//i.test(t.url) ? C : A, n = new URL(t.url), i = t.params;
|
|
20
20
|
i instanceof Object && Object.keys(i).forEach((r) => n.searchParams.set(r, i[r]));
|
|
21
21
|
const l = t.method === "HEAD";
|
|
22
22
|
return new Promise((r) => {
|
|
@@ -64,12 +64,12 @@ const j = async function(o, a, u) {
|
|
|
64
64
|
}), t.body && c.write(t.body), c.end();
|
|
65
65
|
});
|
|
66
66
|
};
|
|
67
|
-
function
|
|
68
|
-
return
|
|
67
|
+
function j(o) {
|
|
68
|
+
return x.fetch ? new f(S, o) : new f(N, o);
|
|
69
69
|
}
|
|
70
|
-
const s =
|
|
70
|
+
const s = j(), k = s.setConfig, B = s.head, D = s.get, P = s.post, F = s.del, G = s.put, I = s.patch;
|
|
71
71
|
export {
|
|
72
|
-
|
|
72
|
+
j as NetRequest,
|
|
73
73
|
d as RequestInternalError,
|
|
74
74
|
F as del,
|
|
75
75
|
D as get,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { h as w, r as y, c as E,
|
|
1
|
+
import { h as w, r as y, c as E, S as T, f as R, a as c } from "./retry-BXoyQlSJ.js";
|
|
2
2
|
const x = async function(a, s, n) {
|
|
3
3
|
return w(await y(g, a, s, n), a, s, n);
|
|
4
4
|
}, g = async function(a, s, n) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const r=require("./retry-
|
|
1
|
+
"use strict";const r=require("./retry-D_7OkloZ.cjs"),E=async function(s,a,i){return r.handleResponse(await r.retryRequest(w,s,a,i),s,a,i)},w=async function(s,a,i){const t=await r.convertOptions(s,a,i),c=new URL(t.url),u=t.params;u instanceof Object&&Object.keys(u).forEach(e=>c.searchParams.set(e,u[e]));const o=r.St.AbortController?new AbortController:null;function l(){o&&!o.signal.aborted&&o.abort()}t.abort&&t.abort.addEventListener("abort",l);let d=!1;const h=t.timeout>0?setTimeout(function(){d=!0,l()},t.timeout):null,f=t.method==="HEAD";return await fetch(c,{method:t.method,headers:Object.keys(t.headers).length>0?new Headers(t.headers):void 0,body:t.body,credentials:t.credentials,signal:o?.signal,redirect:"follow"}).then(async e=>{const n={url:c.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:r.fromEntries([...e.headers.entries()])},b=f||e.status===204?"":await e.text().catch(m=>m);return b instanceof Error?{...n,body:"",statusText:r.RequestInternalError.Unknown,rawError:b}:{...n,body:b}}).catch(e=>{const n=o?.signal.aborted;return{url:c.toString(),method:t.method,status:n&&!d?0:-1,statusText:d?r.RequestInternalError.Timeout:n?r.RequestInternalError.Aborted:r.RequestInternalError.NetworkError,body:"",rawError:e}}).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",l)})};exports.fetchRequest=E;
|
|
@@ -1,10 +1,29 @@
|
|
|
1
|
-
const l = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : typeof window < "u" ? window : Function("return this")()
|
|
2
|
-
|
|
1
|
+
const l = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : typeof window < "u" ? window : Function("return this")();
|
|
2
|
+
function d(t) {
|
|
3
|
+
return typeof t == "function";
|
|
4
|
+
}
|
|
5
|
+
function R(t) {
|
|
6
|
+
return typeof t == "object" && t !== null;
|
|
7
|
+
}
|
|
8
|
+
function G() {
|
|
9
|
+
return "wx" in l && R(l.wx) && "getSystemInfo" in l.wx && d(l.wx.getSystemInfo);
|
|
10
|
+
}
|
|
11
|
+
const k = {
|
|
12
|
+
/**
|
|
13
|
+
* 此处的 wx 由微信 jssdk 动态注入,如果不加载 jssdk 则没有该对象
|
|
14
|
+
*/
|
|
15
|
+
wx: G(),
|
|
16
|
+
/**
|
|
17
|
+
* 检测运行环境是否支持 fetch
|
|
18
|
+
*/
|
|
3
19
|
fetch: "fetch" in l && d(l.fetch),
|
|
4
|
-
|
|
20
|
+
/**
|
|
21
|
+
* 检测是否在普通浏览器中(含 WebView),特别的,排除了微信环境(!Support.wx)
|
|
22
|
+
*/
|
|
23
|
+
window: "window" in l && R(l.window) && !G(),
|
|
5
24
|
requestAnimationFrame: "requestAnimationFrame" in l && d(l.requestAnimationFrame),
|
|
6
|
-
localStorage: "localStorage" in l &&
|
|
7
|
-
sessionStorage: "sessionStorage" in l &&
|
|
25
|
+
localStorage: "localStorage" in l && R(l.localStorage) && "getItem" in l.localStorage && d(l.localStorage.getItem),
|
|
26
|
+
sessionStorage: "sessionStorage" in l && R(l.sessionStorage) && "getItem" in l.sessionStorage && d(l.sessionStorage.getItem),
|
|
8
27
|
File: "File" in l && d(l.File),
|
|
9
28
|
Blob: "Blob" in l && d(l.Blob),
|
|
10
29
|
Proxy: "Proxy" in l && d(l.Proxy),
|
|
@@ -16,18 +35,12 @@ const l = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : type
|
|
|
16
35
|
URLSearchParams: "URLSearchParams" in l && d(l.URLSearchParams),
|
|
17
36
|
EventSource: "EventSource" in l && d(l.EventSource)
|
|
18
37
|
};
|
|
19
|
-
function d(t) {
|
|
20
|
-
return typeof t == "function";
|
|
21
|
-
}
|
|
22
|
-
function E(t) {
|
|
23
|
-
return typeof t == "object" && t !== null;
|
|
24
|
-
}
|
|
25
38
|
function te(t) {
|
|
26
39
|
return new Promise((e) => setTimeout(e, Math.max(0, t)));
|
|
27
40
|
}
|
|
28
41
|
function J() {
|
|
29
42
|
}
|
|
30
|
-
function
|
|
43
|
+
function Q(t, e) {
|
|
31
44
|
const s = {
|
|
32
45
|
log: console.log.bind(console),
|
|
33
46
|
error: console.error.bind(console),
|
|
@@ -62,7 +75,7 @@ function A(t, e = !1) {
|
|
|
62
75
|
function le(t) {
|
|
63
76
|
return t == null;
|
|
64
77
|
}
|
|
65
|
-
function
|
|
78
|
+
function X(t, ...e) {
|
|
66
79
|
return t !== null && typeof t == "object" && !(t instanceof Map) && !(t instanceof Set) && !(t instanceof WeakMap) && !(t instanceof WeakSet) && !Array.isArray(t) && e.every((s) => s in t);
|
|
67
80
|
}
|
|
68
81
|
function y(t, ...e) {
|
|
@@ -83,7 +96,7 @@ function x(t) {
|
|
|
83
96
|
const e = Math.abs(t);
|
|
84
97
|
return e >= Number.EPSILON && e <= Number.MAX_SAFE_INTEGER;
|
|
85
98
|
}
|
|
86
|
-
function
|
|
99
|
+
function Z(t) {
|
|
87
100
|
return oe.test(t) || ie.test(t);
|
|
88
101
|
}
|
|
89
102
|
function ue(t, e = 20) {
|
|
@@ -99,7 +112,7 @@ function O(t, e) {
|
|
|
99
112
|
}
|
|
100
113
|
}
|
|
101
114
|
"" + Math.random().toString(32).slice(2);
|
|
102
|
-
|
|
115
|
+
Q("LoadUtils");
|
|
103
116
|
async function Me(t) {
|
|
104
117
|
return await new Promise(function(e) {
|
|
105
118
|
const s = document.getElementsByTagName("head")[0], n = document.createElement("script");
|
|
@@ -115,7 +128,49 @@ function K(t) {
|
|
|
115
128
|
delete t[e];
|
|
116
129
|
}), t;
|
|
117
130
|
}
|
|
118
|
-
|
|
131
|
+
function ce(t, e = "数据未能正确识别") {
|
|
132
|
+
return typeof t == "function" ? {
|
|
133
|
+
guard: t,
|
|
134
|
+
message: e
|
|
135
|
+
} : {
|
|
136
|
+
guard: t.guard,
|
|
137
|
+
message: t.message || e
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function he(t, e = "") {
|
|
141
|
+
return !e || A(t, !0) ? z(t) : (z(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
|
|
142
|
+
}
|
|
143
|
+
function z(t) {
|
|
144
|
+
return A(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(/^\/+/, "");
|
|
145
|
+
}
|
|
146
|
+
function fe(t, e) {
|
|
147
|
+
const s = {};
|
|
148
|
+
return (t.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(n) {
|
|
149
|
+
const r = n.split("="), o = r[0], i = decodeURIComponent(r[1] || "");
|
|
150
|
+
s[o] !== void 0 ? s[o] += "," + i : s[o] = i;
|
|
151
|
+
}), e !== !0 ? s[e] || "" : s;
|
|
152
|
+
}
|
|
153
|
+
function de(t, e) {
|
|
154
|
+
if (e) {
|
|
155
|
+
if (e === !0)
|
|
156
|
+
return t.replace(/\?[^#]*/, "");
|
|
157
|
+
} else return t;
|
|
158
|
+
const s = t.split("#"), n = s[0].split("?"), r = n[0], o = n.length > 1 ? n[1] : "", i = s.length > 1 ? "#" + s[1] : "", u = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
|
|
159
|
+
return !u.length || !o ? s[0] + i : (u.map((h) => h.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + o.replace(new RegExp("(?:^|&)(?:" + u.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + i);
|
|
160
|
+
}
|
|
161
|
+
function Ce(t, e, s = !1) {
|
|
162
|
+
const n = typeof e == "string" ? e : Object.keys(e).map((i) => `${i}=${encodeURIComponent(e[i])}`).join("&");
|
|
163
|
+
if (!n)
|
|
164
|
+
return t;
|
|
165
|
+
const r = t.split("#");
|
|
166
|
+
s && (r[0] = de(
|
|
167
|
+
r[0],
|
|
168
|
+
(n.match(/([^=&#?]+)=[^&#]+/g) || []).map((i) => i.replace(/=.+$/, ""))
|
|
169
|
+
));
|
|
170
|
+
const o = r[0].indexOf("?") + 1 ? "&" : "?";
|
|
171
|
+
return (r[0] + o + n + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
|
|
172
|
+
}
|
|
173
|
+
const g = Q("Validator");
|
|
119
174
|
function j(t) {
|
|
120
175
|
return t ? `"${ue(t).replace(/"/g, '\\"')}"` : "empty string";
|
|
121
176
|
}
|
|
@@ -197,7 +252,7 @@ class M {
|
|
|
197
252
|
}) ? (s(`${j(e)} is not match pattern ${n.join(" | ")}`), !1) : !0;
|
|
198
253
|
}
|
|
199
254
|
}
|
|
200
|
-
class
|
|
255
|
+
class C {
|
|
201
256
|
_int = !1;
|
|
202
257
|
_min = -1 / 0;
|
|
203
258
|
_max = 1 / 0;
|
|
@@ -257,7 +312,7 @@ class L {
|
|
|
257
312
|
return this._locked = !0, this;
|
|
258
313
|
}
|
|
259
314
|
clone() {
|
|
260
|
-
const e = new
|
|
315
|
+
const e = new C();
|
|
261
316
|
return e._int = this._int, e._min = this._min, e._max = this._max, e._allow = [...this._allow], e._reject = [...this._reject], e._infinite = this._infinite, e._unsafe = this._unsafe, e._nan = this._nan, e._locked = !1, e;
|
|
262
317
|
}
|
|
263
318
|
validate(e, s = g.warn) {
|
|
@@ -310,7 +365,7 @@ class P {
|
|
|
310
365
|
), !1) : (s(`should be a bigint, but got ${typeof e}`), !1);
|
|
311
366
|
}
|
|
312
367
|
}
|
|
313
|
-
class
|
|
368
|
+
class L {
|
|
314
369
|
_locked = !1;
|
|
315
370
|
_opt = !1;
|
|
316
371
|
_null = !1;
|
|
@@ -326,7 +381,7 @@ class C {
|
|
|
326
381
|
return this._locked = !0, this;
|
|
327
382
|
}
|
|
328
383
|
clone() {
|
|
329
|
-
return new
|
|
384
|
+
return new L();
|
|
330
385
|
}
|
|
331
386
|
validate(e, s = g.warn) {
|
|
332
387
|
return e === void 0 ? this._opt || (s("should be a boolean, but got undefined"), !1) : e === null ? this._null || (s("should be a boolean, but got null"), !1) : typeof e != "boolean" ? (s(`should be a boolean, but got ${typeof e}`), !1) : !0;
|
|
@@ -373,7 +428,7 @@ class v {
|
|
|
373
428
|
return e in this._shape ? this._shape[e].validate(s, J) : !1;
|
|
374
429
|
}
|
|
375
430
|
validate(e, s = g.warn) {
|
|
376
|
-
return e === void 0 ? this._opt || (s("should be a object, but got undefined"), !1) : e === null ? this._null || (s("should be a object, but got null"), !1) :
|
|
431
|
+
return e === void 0 ? this._opt || (s("should be a object, but got undefined"), !1) : e === null ? this._null || (s("should be a object, but got null"), !1) : X(e) ? this._plain && !y(e) ? (s(`should be a plain object, but got ${F(e)}`), !1) : Object.keys(this._shape).every((n) => this._shape[n].validate(e[n], (...r) => {
|
|
377
432
|
s(`[.${String(n)}]`, ...r);
|
|
378
433
|
})) : (s(`should be a object, but got ${F(e)}`), !1);
|
|
379
434
|
}
|
|
@@ -523,7 +578,7 @@ class B {
|
|
|
523
578
|
return this._opt || (s("should be a union, but got undefined"), !1);
|
|
524
579
|
if (e === null)
|
|
525
580
|
return this._null || (s("should be a union, but got null"), !1);
|
|
526
|
-
if (this._key &&
|
|
581
|
+
if (this._key && X(e) && e) {
|
|
527
582
|
const r = e[this._key];
|
|
528
583
|
if (r === void 0)
|
|
529
584
|
return s(`key field "${this._key}" is not found`, e), !1;
|
|
@@ -536,7 +591,7 @@ class B {
|
|
|
536
591
|
return n || s("value is not match union definition", e), n;
|
|
537
592
|
}
|
|
538
593
|
}
|
|
539
|
-
class
|
|
594
|
+
class E {
|
|
540
595
|
_name = "";
|
|
541
596
|
_guard;
|
|
542
597
|
_locked = !1;
|
|
@@ -557,22 +612,22 @@ class R {
|
|
|
557
612
|
return this._locked = !0, this;
|
|
558
613
|
}
|
|
559
614
|
clone() {
|
|
560
|
-
return new
|
|
615
|
+
return new E(this._name, this._guard);
|
|
561
616
|
}
|
|
562
617
|
validate(e, s = g.warn) {
|
|
563
618
|
const n = this._name || "custom type";
|
|
564
619
|
return e === void 0 ? this._opt || (s(`should be ${n}, but got undefined`), !1) : e === null ? this._null || (s(`should be ${n}, but got null`), !1) : this._guard(e) || (s(`custom validation${this._name ? `(${this._name})` : ""} failed`), !1);
|
|
565
620
|
}
|
|
566
621
|
}
|
|
567
|
-
function
|
|
622
|
+
function me(t, e) {
|
|
568
623
|
if (typeof t == "string") {
|
|
569
624
|
if (!e)
|
|
570
625
|
throw new Error("custom type guard must be defined");
|
|
571
|
-
return new
|
|
626
|
+
return new E(t, e);
|
|
572
627
|
}
|
|
573
|
-
return new
|
|
628
|
+
return new E("", t);
|
|
574
629
|
}
|
|
575
|
-
const
|
|
630
|
+
const _e = {
|
|
576
631
|
/**
|
|
577
632
|
* object shape 的定义辅助函数
|
|
578
633
|
*/
|
|
@@ -623,18 +678,18 @@ const he = {
|
|
|
623
678
|
},
|
|
624
679
|
/** 布尔型类型验证 */
|
|
625
680
|
bool() {
|
|
626
|
-
return new
|
|
681
|
+
return new L();
|
|
627
682
|
},
|
|
628
683
|
/** 数字验证 */
|
|
629
684
|
number() {
|
|
630
|
-
return new
|
|
685
|
+
return new C();
|
|
631
686
|
},
|
|
632
687
|
/** bigint 验证 */
|
|
633
688
|
bigint() {
|
|
634
689
|
return new P();
|
|
635
690
|
},
|
|
636
691
|
/** 自定义验证 */
|
|
637
|
-
custom:
|
|
692
|
+
custom: me,
|
|
638
693
|
/**
|
|
639
694
|
* 允许一个 unknown 类型,validate 总是返回 true
|
|
640
695
|
*/
|
|
@@ -655,50 +710,8 @@ const he = {
|
|
|
655
710
|
}
|
|
656
711
|
};
|
|
657
712
|
}
|
|
658
|
-
},
|
|
659
|
-
|
|
660
|
-
function de(t, e = "数据未能正确识别") {
|
|
661
|
-
return typeof t == "function" ? {
|
|
662
|
-
guard: t,
|
|
663
|
-
message: e
|
|
664
|
-
} : {
|
|
665
|
-
guard: t.guard,
|
|
666
|
-
message: t.message || e
|
|
667
|
-
};
|
|
668
|
-
}
|
|
669
|
-
function me(t, e = "") {
|
|
670
|
-
return !e || A(t, !0) ? z(t) : (z(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
|
|
671
|
-
}
|
|
672
|
-
function z(t) {
|
|
673
|
-
return A(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(/^\/+/, "");
|
|
674
|
-
}
|
|
675
|
-
function _e(t, e) {
|
|
676
|
-
const s = {};
|
|
677
|
-
return (t.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(n) {
|
|
678
|
-
const r = n.split("="), o = r[0], i = decodeURIComponent(r[1] || "");
|
|
679
|
-
s[o] !== void 0 ? s[o] += "," + i : s[o] = i;
|
|
680
|
-
}), e !== !0 ? s[e] || "" : s;
|
|
681
|
-
}
|
|
682
|
-
function ge(t, e) {
|
|
683
|
-
if (e) {
|
|
684
|
-
if (e === !0)
|
|
685
|
-
return t.replace(/\?[^#]*/, "");
|
|
686
|
-
} else return t;
|
|
687
|
-
const s = t.split("#"), n = s[0].split("?"), r = n[0], o = n.length > 1 ? n[1] : "", i = s.length > 1 ? "#" + s[1] : "", u = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
|
|
688
|
-
return !u.length || !o ? s[0] + i : (u.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + o.replace(new RegExp("(?:^|&)(?:" + u.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + i);
|
|
689
|
-
}
|
|
690
|
-
function Le(t, e, s = !1) {
|
|
691
|
-
const n = typeof e == "string" ? e : Object.keys(e).map((i) => `${i}=${encodeURIComponent(e[i])}`).join("&");
|
|
692
|
-
if (!n)
|
|
693
|
-
return t;
|
|
694
|
-
const r = t.split("#");
|
|
695
|
-
s && (r[0] = ge(
|
|
696
|
-
r[0],
|
|
697
|
-
(n.match(/([^=&#?]+)=[^&#]+/g) || []).map((i) => i.replace(/=.+$/, ""))
|
|
698
|
-
));
|
|
699
|
-
const o = r[0].indexOf("?") + 1 ? "&" : "?";
|
|
700
|
-
return (r[0] + o + n + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
|
|
701
|
-
}
|
|
713
|
+
}, ge = (t) => y(t) && Object.keys(t).length === 0;
|
|
714
|
+
_e.custom("EmptyObject", ge);
|
|
702
715
|
function pe(t) {
|
|
703
716
|
const e = t.match(/(?:\?|&)([^=]+)(?:&|$)/g);
|
|
704
717
|
return e ? e.join("").replace(/(?:\?|^&+|&+$)/g, "").replace(/&{2}/g, "&").split("&").sort() : [];
|
|
@@ -706,18 +719,32 @@ function pe(t) {
|
|
|
706
719
|
class be {
|
|
707
720
|
ttl;
|
|
708
721
|
cache;
|
|
722
|
+
timer = null;
|
|
723
|
+
// 定时循环以清理缓存
|
|
724
|
+
loopCheck() {
|
|
725
|
+
if (Object.keys(this.cache).forEach((s) => {
|
|
726
|
+
this.cache[s].ttl < Date.now() && delete this.cache[s];
|
|
727
|
+
}), Object.keys(this.cache).length === 0) {
|
|
728
|
+
this.timer = null;
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
this.timer = setTimeout(this.loopCheck, 5e3);
|
|
732
|
+
}
|
|
709
733
|
constructor(e = 500) {
|
|
710
|
-
this.cache = {}, this.ttl = Math.max(e, 0);
|
|
734
|
+
this.cache = {}, this.ttl = Math.max(e, 0), this.loopCheck = this.loopCheck.bind(this);
|
|
711
735
|
}
|
|
712
736
|
getKey(e, s, n, r) {
|
|
713
737
|
if (e.toLowerCase() !== "get" && !r)
|
|
714
738
|
return "";
|
|
715
739
|
const o = e.toLowerCase(), i = s.replace(/#.+/, ""), u = i.replace(/\?.+/g, "");
|
|
716
|
-
if (r)
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
740
|
+
if (r)
|
|
741
|
+
try {
|
|
742
|
+
const c = r() || "";
|
|
743
|
+
return c ? `${u}_${o}_${c}` : "";
|
|
744
|
+
} catch (c) {
|
|
745
|
+
return console.warn("[RequestCache] cacheResolve error", s, n, c), "";
|
|
746
|
+
}
|
|
747
|
+
const h = Object.assign(fe(i, !0), n), m = pe(i), f = Object.keys(h).sort().map((c) => `${c}#${h[c]}`);
|
|
721
748
|
return `${u}_${o}_${f.join(",")}_${m.join(",")}`;
|
|
722
749
|
}
|
|
723
750
|
updateTTL(e) {
|
|
@@ -734,7 +761,10 @@ class be {
|
|
|
734
761
|
r !== 0 && (this.cache[e] = {
|
|
735
762
|
ttl: Date.now() + r,
|
|
736
763
|
res: s
|
|
737
|
-
});
|
|
764
|
+
}, this.timer === null && (this.timer = setTimeout(this.loopCheck, 5e3)));
|
|
765
|
+
}
|
|
766
|
+
del(e) {
|
|
767
|
+
this.cache[e] && delete this.cache[e];
|
|
738
768
|
}
|
|
739
769
|
}
|
|
740
770
|
class ye {
|
|
@@ -771,14 +801,14 @@ class ye {
|
|
|
771
801
|
}
|
|
772
802
|
/** 基于 baseURL 返回完整的 url 地址 */
|
|
773
803
|
getFullUrl(e) {
|
|
774
|
-
return
|
|
804
|
+
return he(e, this.config.baseURL);
|
|
775
805
|
}
|
|
776
806
|
/** 提示消息 */
|
|
777
807
|
showMessage(e, s, n, r) {
|
|
778
808
|
this.config.messageHandler && s && this.config.messageHandler(e, s, n, r);
|
|
779
809
|
}
|
|
780
810
|
}
|
|
781
|
-
const
|
|
811
|
+
const Y = {
|
|
782
812
|
/** 响应数据校验失败 */
|
|
783
813
|
UnexpectResponse: "UnexpectResponse",
|
|
784
814
|
/** 请求被取消 */
|
|
@@ -796,8 +826,8 @@ const Z = {
|
|
|
796
826
|
};
|
|
797
827
|
function we(t, e, s, n) {
|
|
798
828
|
if (e.ok && !le(e.data) && n) {
|
|
799
|
-
const r =
|
|
800
|
-
return r.guard(e.data) || (e.code =
|
|
829
|
+
const r = ce(n, s.get("defaultTypeGuardMessage"));
|
|
830
|
+
return r.guard(e.data) || (e.code = Y.UnexpectResponse, s.showMessage(!0, `${t} ${r.message}`, e.code, e.status), console.error(e.code, t, e.data), e.data = null, e.message = r.message), e;
|
|
801
831
|
}
|
|
802
832
|
return e;
|
|
803
833
|
}
|
|
@@ -820,12 +850,14 @@ class Pe {
|
|
|
820
850
|
}
|
|
821
851
|
try {
|
|
822
852
|
const r = this.agent(e, this.config, s);
|
|
823
|
-
|
|
853
|
+
n && this.cache.set(n, r, s?.cacheTTL);
|
|
854
|
+
const o = await r;
|
|
855
|
+
return (!o.ok || o.status < 0) && this.cache.del(n), o;
|
|
824
856
|
} catch (r) {
|
|
825
857
|
return console.error("RequestError", r), {
|
|
826
858
|
ok: !1,
|
|
827
859
|
status: -9,
|
|
828
|
-
code:
|
|
860
|
+
code: Y.Unknown,
|
|
829
861
|
message: r instanceof Error ? `${r.message}
|
|
830
862
|
${r.stack || ""}` : String(r),
|
|
831
863
|
headers: {},
|
|
@@ -881,7 +913,7 @@ ${r.stack || ""}` : String(r),
|
|
|
881
913
|
return o.method = "PATCH", o.body = s || {}, this.guard(e, await this.request(e, o), n || null);
|
|
882
914
|
}
|
|
883
915
|
}
|
|
884
|
-
async function
|
|
916
|
+
async function Le(t, e, s) {
|
|
885
917
|
const n = Object.assign({ method: "GET" }, s), r = k.FormData ? n.body instanceof FormData : !1, o = r && n.method !== "POST" && n.method !== "PUT" ? "POST" : n.method, i = o === "GET" || o === "HEAD" || o === "DELETE";
|
|
886
918
|
i && n.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete n.body);
|
|
887
919
|
const u = Object.assign(
|
|
@@ -889,19 +921,19 @@ async function Ce(t, e, s) {
|
|
|
889
921
|
"Content-Type": k.Blob && n.body instanceof Blob ? n.body.type || "application/octet-stream" : "application/json;charset=utf-8"
|
|
890
922
|
},
|
|
891
923
|
n.headers
|
|
892
|
-
),
|
|
893
|
-
Object.keys(
|
|
894
|
-
|
|
924
|
+
), h = n.params || {}, m = {};
|
|
925
|
+
Object.keys(h).forEach((_) => {
|
|
926
|
+
h[_] !== void 0 && (m[_] = ke(h[_]));
|
|
895
927
|
});
|
|
896
|
-
const f = e.getFullUrl(t),
|
|
928
|
+
const f = e.getFullUrl(t), c = ve(n.body), p = n.timeout || e.get("timeout"), b = await async function() {
|
|
897
929
|
const _ = e.get("requestTransformer");
|
|
898
930
|
if (_)
|
|
899
|
-
return await _({ headers: u, params: m, method: o, url: f, body:
|
|
931
|
+
return await _({ headers: u, params: m, method: o, url: f, body: c });
|
|
900
932
|
}(), w = typeof b == "string" && b ? b : f;
|
|
901
|
-
return e.get("logHandler")?.({ type: "ready", url: w, method: o, headers: u, timeout: p, body:
|
|
933
|
+
return e.get("logHandler")?.({ type: "ready", url: w, method: o, headers: u, timeout: p, body: c }), {
|
|
902
934
|
url: w,
|
|
903
935
|
method: o,
|
|
904
|
-
body:
|
|
936
|
+
body: c,
|
|
905
937
|
params: m,
|
|
906
938
|
headers: u,
|
|
907
939
|
timeout: p,
|
|
@@ -959,29 +991,29 @@ function je(t, e, s) {
|
|
|
959
991
|
r.message = V(s) || s;
|
|
960
992
|
break;
|
|
961
993
|
case "json":
|
|
962
|
-
const { code: o, message: i } =
|
|
994
|
+
const { code: o, message: i } = Re(s, n.converter, n.statusField, n.messageField);
|
|
963
995
|
r.code = o || e, r.message = V(s) || i;
|
|
964
996
|
break;
|
|
965
997
|
}
|
|
966
998
|
return r;
|
|
967
999
|
}
|
|
968
|
-
function
|
|
969
|
-
if (!
|
|
1000
|
+
function Re(t, e, s, n = $) {
|
|
1001
|
+
if (!Z(t))
|
|
970
1002
|
return { message: "" };
|
|
971
|
-
const r =
|
|
1003
|
+
const r = T(O(t), e);
|
|
972
1004
|
return !r || !y(r) ? { message: t } : {
|
|
973
|
-
code: s ?
|
|
974
|
-
message:
|
|
1005
|
+
code: s ? S(r, s) : "",
|
|
1006
|
+
message: S(r, n) || t
|
|
975
1007
|
};
|
|
976
1008
|
}
|
|
977
|
-
function
|
|
1009
|
+
function S(t, e) {
|
|
978
1010
|
const s = Array.isArray(e) ? e : [e];
|
|
979
1011
|
for (const n of s)
|
|
980
1012
|
if (n in t)
|
|
981
|
-
return
|
|
1013
|
+
return Ee(t[n]);
|
|
982
1014
|
return "";
|
|
983
1015
|
}
|
|
984
|
-
function
|
|
1016
|
+
function Ee(t) {
|
|
985
1017
|
return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
|
|
986
1018
|
}
|
|
987
1019
|
const xe = /<title>([^<]+)<\/title>/i, Ne = /<message>([^<]+)<\/message>/i;
|
|
@@ -1002,24 +1034,24 @@ function Oe(t, e, s, n) {
|
|
|
1002
1034
|
if (e === 204 || !n)
|
|
1003
1035
|
return o;
|
|
1004
1036
|
if (r.resolve === "body")
|
|
1005
|
-
return o.data =
|
|
1006
|
-
const i =
|
|
1037
|
+
return o.data = Z(n) ? T(O(n), t.converter) : n, o;
|
|
1038
|
+
const i = T(O(n), t.converter);
|
|
1007
1039
|
if (!i || !y(i))
|
|
1008
1040
|
return o.ok = !1, o.code = "ResponseFormatError", o.message = "响应内容无法格式化为 Object", o;
|
|
1009
|
-
const u = r.statusField,
|
|
1041
|
+
const u = r.statusField, h = r.statusOKValue || "", m = r.dataField || ee, f = r.messageField || $, c = r.ignoreMessage || "";
|
|
1010
1042
|
if (u && !(u in i))
|
|
1011
1043
|
return o.ok = !1, o.code = "ResponseFieldMissing", o.message = "响应内容找不到状态字段 " + u, o;
|
|
1012
1044
|
const p = u ? i[u] + "" : "";
|
|
1013
|
-
return o.ok = u ? p ===
|
|
1045
|
+
return o.ok = u ? p === h : !0, o.code = p || s, o.data = m === !0 ? i : m in i ? i[m] : null, o.message = S(i, f), c && o.message && (Array.isArray(c) && c.includes(o.message) || typeof c == "string" && o.message === c) && (o.message = ""), o;
|
|
1014
1046
|
}
|
|
1015
1047
|
function H(t) {
|
|
1016
1048
|
return t >= 200 && t < 400;
|
|
1017
1049
|
}
|
|
1018
|
-
function
|
|
1050
|
+
function T(t, e) {
|
|
1019
1051
|
return e ? typeof e == "function" ? e(t) : (console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'), t) : t;
|
|
1020
1052
|
}
|
|
1021
1053
|
const Fe = se("APIError");
|
|
1022
|
-
function
|
|
1054
|
+
function Se(t) {
|
|
1023
1055
|
const e = {};
|
|
1024
1056
|
for (const r in t.headers)
|
|
1025
1057
|
(r.startsWith("x-") || r.includes("trace") || r.includes("server") || /\b(?:id|uuid)\b/.test(r)) && (e[r] = t.headers[r]);
|
|
@@ -1041,16 +1073,16 @@ function Te(t) {
|
|
|
1041
1073
|
}
|
|
1042
1074
|
};
|
|
1043
1075
|
}
|
|
1044
|
-
function
|
|
1076
|
+
function Te(t) {
|
|
1045
1077
|
return t.reduce(
|
|
1046
1078
|
(e, [s, n]) => (s && (e[s] = n || ""), e),
|
|
1047
1079
|
{}
|
|
1048
1080
|
);
|
|
1049
1081
|
}
|
|
1050
1082
|
function De(t, e, s, n) {
|
|
1051
|
-
const r = t.status, o = t.method, i =
|
|
1083
|
+
const r = t.status, o = t.method, i = Te(
|
|
1052
1084
|
Object.entries(t.headers || {}).map(([b, w]) => [b.toLowerCase(), w])
|
|
1053
|
-
), { ok: u, code:
|
|
1085
|
+
), { ok: u, code: h, data: m, message: f } = $e(
|
|
1054
1086
|
r,
|
|
1055
1087
|
t.statusText,
|
|
1056
1088
|
t.body,
|
|
@@ -1058,11 +1090,11 @@ function De(t, e, s, n) {
|
|
|
1058
1090
|
n?.responseRule
|
|
1059
1091
|
);
|
|
1060
1092
|
if (!H(r)) {
|
|
1061
|
-
const b =
|
|
1093
|
+
const b = Se({
|
|
1062
1094
|
url: t.url,
|
|
1063
1095
|
method: t.method,
|
|
1064
1096
|
status: r,
|
|
1065
|
-
code:
|
|
1097
|
+
code: h,
|
|
1066
1098
|
message: f,
|
|
1067
1099
|
body: t.body,
|
|
1068
1100
|
headers: i,
|
|
@@ -1072,7 +1104,7 @@ function De(t, e, s, n) {
|
|
|
1072
1104
|
url: e,
|
|
1073
1105
|
method: o,
|
|
1074
1106
|
status: r,
|
|
1075
|
-
code:
|
|
1107
|
+
code: h,
|
|
1076
1108
|
message: f,
|
|
1077
1109
|
headers: i,
|
|
1078
1110
|
rawError: t.rawError,
|
|
@@ -1089,16 +1121,16 @@ function De(t, e, s, n) {
|
|
|
1089
1121
|
s,
|
|
1090
1122
|
n
|
|
1091
1123
|
);
|
|
1092
|
-
const
|
|
1093
|
-
s.get("responseHandler")?.({ ...
|
|
1124
|
+
const c = { ok: u, data: m, code: h, message: f, status: r, headers: i };
|
|
1125
|
+
s.get("responseHandler")?.({ ...c }, o, e);
|
|
1094
1126
|
const p = u ? f : f || t.statusText;
|
|
1095
|
-
return W(
|
|
1127
|
+
return W(c, p, o, e, s, n);
|
|
1096
1128
|
}
|
|
1097
1129
|
function W(t, e, s, n, r, o) {
|
|
1098
1130
|
const i = r.get("message"), u = i === !1 || o?.message === !1 ? !1 : o?.message || i;
|
|
1099
1131
|
if (u !== !1) {
|
|
1100
|
-
const
|
|
1101
|
-
|
|
1132
|
+
const h = typeof u == "function" ? u(t, s, n, e) : e;
|
|
1133
|
+
h instanceof Error ? r.showMessage(!0, h.message, t.code, t.status) : h && typeof h == "object" && "message" in h ? r.showMessage(!1, h.message, t.code, t.status) : r.showMessage(!t.ok, h, t.code, t.status);
|
|
1102
1134
|
}
|
|
1103
1135
|
return t;
|
|
1104
1136
|
}
|
|
@@ -1109,8 +1141,8 @@ function Ae(t) {
|
|
|
1109
1141
|
console.error("RequestError", e);
|
|
1110
1142
|
}
|
|
1111
1143
|
async function Ue(t, e, s, n, r) {
|
|
1112
|
-
const o = r || 0, i = Math.max(0, Math.min(10, n?.maxRetry ?? s.get("maxRetry") ?? 0)), u = n?.retryResolve ?? s.get("retryResolve"),
|
|
1113
|
-
|
|
1144
|
+
const o = r || 0, i = Math.max(0, Math.min(10, n?.maxRetry ?? s.get("maxRetry") ?? 0)), u = n?.retryResolve ?? s.get("retryResolve"), h = s.get("logHandler");
|
|
1145
|
+
h?.({
|
|
1114
1146
|
type: "prepare",
|
|
1115
1147
|
url: e,
|
|
1116
1148
|
method: n?.method || "GET",
|
|
@@ -1120,8 +1152,8 @@ async function Ue(t, e, s, n, r) {
|
|
|
1120
1152
|
headers: n?.headers,
|
|
1121
1153
|
options: n
|
|
1122
1154
|
});
|
|
1123
|
-
const m = Date.now(), f = await t(e, s, n),
|
|
1124
|
-
|
|
1155
|
+
const m = Date.now(), f = await t(e, s, n), c = f.status, p = Date.now() - m, b = `[cost ${p}][${c}] ${c < 0 ? f.body : ""}`;
|
|
1156
|
+
h?.({
|
|
1125
1157
|
type: "finished",
|
|
1126
1158
|
url: e,
|
|
1127
1159
|
method: f.method,
|
|
@@ -1132,28 +1164,28 @@ async function Ue(t, e, s, n, r) {
|
|
|
1132
1164
|
headers: f.headers,
|
|
1133
1165
|
cost: p
|
|
1134
1166
|
});
|
|
1135
|
-
const w = H(
|
|
1136
|
-
if (!i || o >= i || u === "network" &&
|
|
1167
|
+
const w = H(c);
|
|
1168
|
+
if (!i || o >= i || u === "network" && c > 0 || u === "status" && w || Array.isArray(u) && !u.includes(c) || typeof u == "function" && u(f, o) !== !0)
|
|
1137
1169
|
return f;
|
|
1138
1170
|
const _ = n?.retryInterval ?? s.get("retryInterval") ?? 100;
|
|
1139
1171
|
return await te(
|
|
1140
1172
|
Math.max(
|
|
1141
1173
|
100,
|
|
1142
|
-
_ === "2EB" ? Math.pow(2, o) * 100 : typeof _ == "function" ? _(o + 1, { url: e, status:
|
|
1174
|
+
_ === "2EB" ? Math.pow(2, o) * 100 : typeof _ == "function" ? _(o + 1, { url: e, status: c, method: f.method }) || 0 : _
|
|
1143
1175
|
)
|
|
1144
1176
|
), await Ue(t, e, s, n, o + 1);
|
|
1145
1177
|
}
|
|
1146
1178
|
export {
|
|
1147
|
-
|
|
1148
|
-
A as E,
|
|
1179
|
+
A,
|
|
1149
1180
|
Pe as N,
|
|
1150
1181
|
ye as R,
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1182
|
+
k as S,
|
|
1183
|
+
Y as a,
|
|
1184
|
+
Me as b,
|
|
1185
|
+
Le as c,
|
|
1186
|
+
Te as f,
|
|
1154
1187
|
Ie as g,
|
|
1155
1188
|
De as h,
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
Le as y
|
|
1189
|
+
Ce as p,
|
|
1190
|
+
Ue as r
|
|
1159
1191
|
};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";const l=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Function("return this")();function d(t){return typeof t=="function"}function R(t){return typeof t=="object"&&t!==null}function K(){return"wx"in l&&R(l.wx)&&"getSystemInfo"in l.wx&&d(l.wx.getSystemInfo)}const k={wx:K(),fetch:"fetch"in l&&d(l.fetch),window:"window"in l&&R(l.window)&&!K(),requestAnimationFrame:"requestAnimationFrame"in l&&d(l.requestAnimationFrame),localStorage:"localStorage"in l&&R(l.localStorage)&&"getItem"in l.localStorage&&d(l.localStorage.getItem),sessionStorage:"sessionStorage"in l&&R(l.sessionStorage)&&"getItem"in l.sessionStorage&&d(l.sessionStorage.getItem),File:"File"in l&&d(l.File),Blob:"Blob"in l&&d(l.Blob),Proxy:"Proxy"in l&&d(l.Proxy),Request:"Request"in l&&d(l.Request),FormData:"FormData"in l&&d(l.FormData),TextDecoder:"TextDecoder"in l&&d(l.TextDecoder),ResizeObserver:"ResizeObserver"in l&&d(l.ResizeObserver),AbortController:"AbortController"in l&&d(l.AbortController),URLSearchParams:"URLSearchParams"in l&&d(l.URLSearchParams),EventSource:"EventSource"in l&&d(l.EventSource)};function re(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function Q(){}function X(t,e){const s={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)},n=`[${t}]`;return["log","error","warn"].forEach(r=>{const o=console[r];s[r]=(...i)=>{o.apply(console,[n,...i])}}),s}function oe(t){const e=t||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:e,enumerable:!1,configurable:!0}),"setPrototypeOf"in Object&&Object.setPrototypeOf(this,new.target.prototype),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,this.constructor)}}}const ie=/^(?:https?:)?\/\/.+$/i,ae=/^https?:\/\/.+$/i,le=/^\{[\d\D]*\}$/,ue=/^\[[\d\D]*\]$/;function ce(t){return typeof t=="string"}function x(t,e=!1){return e?ie.test(t):ae.test(t)}function he(t){return t==null}function Z(t,...e){return t!==null&&typeof t=="object"&&!(t instanceof Map)&&!(t instanceof Set)&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!Array.isArray(t)&&e.every(s=>s in t)}function y(t,...e){if(!t||typeof t!="object")return!1;const s=Object.getPrototypeOf(t);return s!==Object.prototype&&s!==null?!1:e.every(n=>n in t)}function U(t,e){return Array.isArray(t)&&t.every(s=>e(s))}function N(t){if(typeof t!="number"||Number.isNaN(t)||!Number.isFinite(t))return!1;if(Number.isInteger(t))return Number.isSafeInteger(t);if(t===0)return!0;const e=Math.abs(t);return e>=Number.EPSILON&&e<=Number.MAX_SAFE_INTEGER}function Y(t){return le.test(t)||ue.test(t)}function fe(t,e=20){const s=Math.max(e,10),n=[...t];return n.length<=s?t:n.slice(0,s-3).join("")+"..."}function F(t,e){try{const s=JSON.parse(t);return e?e(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);X("LoadUtils");async function de(t){return await new Promise(function(e){const s=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("charset","utf-8"),n.onload=function(){s.removeChild(n),e(!0)},n.onerror=function(){s.removeChild(n),e(!1)},n.setAttribute("src",t),s.appendChild(n)})}function z(t){return Object.getOwnPropertyNames(t).forEach(function(e){delete t[e]}),t}function me(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function _e(t,e=""){return!e||x(t,!0)?V(t):(V(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function V(t){return x(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(/^\/+/,"")}function pe(t,e){const s={};return(t.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(n){const r=n.split("="),o=r[0],i=decodeURIComponent(r[1]||"");s[o]!==void 0?s[o]+=","+i:s[o]=i}),e!==!0?s[e]||"":s}function ge(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const s=t.split("#"),n=s[0].split("?"),r=n[0],o=n.length>1?n[1]:"",i=s.length>1?"#"+s[1]:"",u=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!u.length||!o?s[0]+i:(u.map(h=>h.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+o.replace(new RegExp("(?:^|&)(?:"+u.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+i)}function be(t,e,s=!1){const n=typeof e=="string"?e:Object.keys(e).map(i=>`${i}=${encodeURIComponent(e[i])}`).join("&");if(!n)return t;const r=t.split("#");s&&(r[0]=ge(r[0],(n.match(/([^=&#?]+)=[^&#]+/g)||[]).map(i=>i.replace(/=.+$/,""))));const o=r[0].indexOf("?")+1?"&":"?";return(r[0]+o+n+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}const p=X("Validator");function j(t){return t?`"${fe(t).replace(/"/g,'\\"')}"`:"empty string"}function S(t){return typeof t=="object"&&t&&"constructor"in t&&typeof t.constructor=="function"?t.constructor.name||"ClassInstance":Object.prototype.toString.call(t).replace(/(?:.+ |]$)/g,"")}function O(t){return typeof t=="bigint"}function a(t){return new Error(`${t?`${t}()`:"method"} is not allowed after locked`)}class M{_ps={};_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;pattern(e,s){if(this._locked)throw a("pattern");return this._ps[`#${e||"custom"}`]=s,this}url(e=!1){if(this._locked)throw a("url");return this._ps.url=e?/^(?:https?:)?\/\/.+$/i:/^https?:\/\/.+$/i,this}dataUri(){if(this._locked)throw a("dataUri");return this._ps.dataUri=/^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$/,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,ce)?(this._allow=e,z(this._ps)):y(s)&&(this._allow=Object.values(s).map(n=>`${n}`),z(this._ps)),this}disallow(...e){return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new M;return e._ps={...this._ps},e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=p.warn){if(e===void 0)return this._opt||(s("should be a string, but got undefined"),!1);if(e===null)return this._null||(s("should be a string, but got null"),!1);if(typeof e!="string")return s(`should be a string, but got ${typeof e}`),!1;if(this._allow.length>0)return this._allow.includes(e)||(s(`${j(e)} is not allowed, just support ${this._allow.map(j).join(", ")}`),!1);if(this._reject.length>0&&this._reject.some(r=>typeof r=="string"?r===e:r.test(e)))return s(`${j(e)} is not allowed`),!1;const n=Object.keys(this._ps);return n.length>0&&!n.some(r=>{const o=this._ps[r];return o instanceof RegExp?o.test(e):o(e)})?(s(`${j(e)} is not match pattern ${n.join(" | ")}`),!1):!0}}class C{_int=!1;_min=-1/0;_max=1/0;_allow=[];_reject=[];_infinite=!1;_unsafe=!1;_nan=!1;_locked=!1;_opt=!1;_null=!1;int(){if(this._locked)throw a("int");return this._int=!0,this}min(e){if(this._locked)throw a("min");return Number.isNaN(e)||(this._min=e),this}max(e){if(this._locked)throw a("max");return Number.isNaN(e)||(this._max=e),this}allowNaN(){if(this._locked)throw a("allowNaN");return this._nan=!0,this}allowInfinity(){if(this._locked)throw a("allowInfinity");return this._infinite=!0,this._unsafe=!0,this}unsafe(){if(this._locked)throw a("unsafe");return this._unsafe=!0,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,N)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>N(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new C;return e._int=this._int,e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._infinite=this._infinite,e._unsafe=this._unsafe,e._nan=this._nan,e._locked=!1,e}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a number, but got undefined"),!1):e===null?this._null||(s("should be a number, but got null"),!1):typeof e!="number"?(s(`should be a number, but got ${typeof e}`),!1):Number.isNaN(e)?this._nan||(s("should be a number, but got NaN"),!1):!Number.isFinite(e)&&!this._infinite?(s("should be a number, but got Infinity"),!1):this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):this._int&&Math.ceil(e)!==e?(s(`${e} is not an integer`),!1):!N(e)&&!this._unsafe?(s(`${e} is not a safe number`),!1):e>=this._min&&e<=this._max||(s(`${e} is not in range [${this._min}, ${this._max}]`),!1)}}class P{_min=null;_max=null;_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,O)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>O(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new P;return e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a bigint, but got undefined"),!1):e===null?this._null||(s("should be a bigint, but got null"),!1):O(e)?this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):(this._min!==null?e>=this._min:!0)&&(this._max!==null?e<=this._max:!0)||(s(`${e} is not in range [${this._min===null?-1/0:this._min}, ${this._max===null?1/0:this._max}]`),!1):(s(`should be a bigint, but got ${typeof e}`),!1)}}class q{_locked=!1;_opt=!1;_null=!1;optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new q}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a boolean, but got undefined"),!1):e===null?this._null||(s("should be a boolean, but got null"),!1):typeof e!="boolean"?(s(`should be a boolean, but got ${typeof e}`),!1):!0}}class v{_shape;_plain=!1;_locked=!1;_opt=!1;_null=!1;constructor(e){this._shape=e}plain(){if(this._locked)throw a("plain");return this._plain=!0,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}get shape(){return{...this._shape}}clone(){const e=new v(this._shape);return e._plain=this._plain,e._locked=!1,e}match(e,s){return e in this._shape?this._shape[e].validate(s,Q):!1}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a object, but got undefined"),!1):e===null?this._null||(s("should be a object, but got null"),!1):Z(e)?this._plain&&!y(e)?(s(`should be a plain object, but got ${S(e)}`),!1):Object.keys(this._shape).every(n=>this._shape[n].validate(e[n],(...r)=>{s(`[.${String(n)}]`,...r)})):(s(`should be a object, but got ${S(e)}`),!1)}}class I{_val;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new I(this._val)}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a record, but got undefined"),!1):e===null?this._null||(s("should be a record, but got null"),!1):y(e)?Object.keys(e).every(n=>this._val.validate(e[n],(...r)=>{s(`[:${n}]`,...r)})):(s(`should be a record, but got ${S(e)}`),!1)}}class L{_val;_min=0;_max=1/0;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new L(this._val);return e._min=this._min,e._max=this._max,e._locked=!1,e}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a array, but got undefined"),!1):e===null?this._null||(s("should be a array, but got null"),!1):Array.isArray(e)?e.length<this._min||e.length>this._max?(this._min===this._max?s(`should be a array with length ${this._min}`):s(`should be a array with length between ${this._min} and ${this._max}`),!1):e.every((n,r)=>this._val.validate(n,(...o)=>{s(`[${r}]`,...o)})):(s(`should be a array, but got ${typeof e}`),!1)}}class D{_vs;_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new D(...this._vs)}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a tuple, but got undefined"),!1):e===null?this._null||(s("should be a tuple, but got null"),!1):Array.isArray(e)?e.length!==this._vs.length?(s(`should be a tuple with length ${this._vs.length}, but got ${e.length}`),!1):this._vs.every((n,r)=>n.validate(e[r],(...o)=>{s(`[idx:${r}]`,...o)})):(s(`should be a tuple, but got ${typeof e}`),!1)}}class B{_vs;_key="";_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}key(e){if(this._locked)throw a("key");return this._vs.every(s=>s instanceof v)?this._key=e:p.warn("union type key can only be used when all validators are ObjectValidator"),this}satisfies(){return this}lock(){return this._locked=!0,this}get validators(){return[...this._vs]}clone(){const e=new B(...this._vs);return e._key=this._key,e._locked=!1,e}validate(e,s=p.warn){if(e===void 0)return this._opt||(s("should be a union, but got undefined"),!1);if(e===null)return this._null||(s("should be a union, but got null"),!1);if(this._key&&Z(e)&&e){const r=e[this._key];if(r===void 0)return s(`key field "${this._key}" is not found`,e),!1;const o=this._vs.find(i=>i instanceof v&&i.match(this._key,r));return o?o.validate(e,s):(s(`key field "${this._key}" value is match union definition`,r),!1)}const n=this._vs.some(r=>r.validate(e,Q));return n||s("value is not match union definition",e),n}}class E{_name="";_guard;_locked=!1;_opt=!1;_null=!1;constructor(e,s){this._name=e,this._guard=s}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new E(this._name,this._guard)}validate(e,s=p.warn){const n=this._name||"custom type";return e===void 0?this._opt||(s(`should be ${n}, but got undefined`),!1):e===null?this._null||(s(`should be ${n}, but got null`),!1):this._guard(e)||(s(`custom validation${this._name?`(${this._name})`:""} failed`),!1)}}function ye(t,e){if(typeof t=="string"){if(!e)throw new Error("custom type guard must be defined");return new E(t,e)}return new E("",t)}const we={shape(t){return t},define(t){return t},guard(t){return function(e){return t.validate(e)}},object(t){return new v(t)},record(t){return new I(t)},array(t){return new L(t)},tuple(...t){return new D(...t)},union(...t){return new B(...t)},string(){return new M},bool(){return new q},number(){return new C},bigint(){return new P},custom:ye,unknown(){return{validate(t){return!0}}},never(){return{validate(t){return!1}}}},ke=t=>y(t)&&Object.keys(t).length===0;we.custom("EmptyObject",ke);function ve(t){const e=t.match(/(?:\?|&)([^=]+)(?:&|$)/g);return e?e.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class $e{ttl;cache;timer=null;loopCheck(){if(Object.keys(this.cache).forEach(s=>{this.cache[s].ttl<Date.now()&&delete this.cache[s]}),Object.keys(this.cache).length===0){this.timer=null;return}this.timer=setTimeout(this.loopCheck,5e3)}constructor(e=500){this.cache={},this.ttl=Math.max(e,0),this.loopCheck=this.loopCheck.bind(this)}getKey(e,s,n,r){if(e.toLowerCase()!=="get"&&!r)return"";const o=e.toLowerCase(),i=s.replace(/#.+/,""),u=i.replace(/\?.+/g,"");if(r)try{const c=r()||"";return c?`${u}_${o}_${c}`:""}catch(c){return console.warn("[RequestCache] cacheResolve error",s,n,c),""}const h=Object.assign(pe(i,!0),n),m=ve(i),f=Object.keys(h).sort().map(c=>`${c}#${h[c]}`);return`${u}_${o}_${f.join(",")}_${m.join(",")}`}updateTTL(e){this.ttl=Math.max(e,0)}get(e,s){if(Math.max(s??this.ttl,0)===0)return null;const r=this.cache[e];return r?r.ttl<Date.now()?(delete this.cache[e],null):r.res:null}set(e,s,n){const r=Math.max(n??this.ttl,0);r!==0&&(this.cache[e]={ttl:Date.now()+r,res:s},this.timer===null&&(this.timer=setTimeout(this.loopCheck,5e3)))}del(e){this.cache[e]&&delete this.cache[e]}}class ee{config={baseURL:"/",maxRetry:0,retryInterval:100,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}};constructor(e){e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!x(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return _e(e,this.config.baseURL)}showMessage(e,s,n,r){this.config.messageHandler&&s&&this.config.messageHandler(e,s,n,r)}}const H={UnexpectResponse:"UnexpectResponse",Aborted:"Aborted",Unknown:"Unknown",NetworkError:"NetworkError",Timeout:"Timeout",NotSupport:"NotSupport",URLFormatError:"URLFormatError"};function je(t,e,s,n){if(e.ok&&!he(e.data)&&n){const r=me(n,s.get("defaultTypeGuardMessage"));return r.guard(e.data)||(e.code=H.UnexpectResponse,s.showMessage(!0,`${t} ${r.message}`,e.code,e.status),console.error(e.code,t,e.data),e.data=null,e.message=r.message),e}return e}class Re{agent;config;cache;constructor(e,s){this.config=new ee(s),this.agent=e,this.cache=new $e(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)}async request(e,s){const n=this.cache.getKey(s?.method||"GET",e,s?.params,s?.cacheResolve);if(n){const r=this.cache.get(n,s?.cacheTTL);if(r)return await r}try{const r=this.agent(e,this.config,s);n&&this.cache.set(n,r,s?.cacheTTL);const o=await r;return(!o.ok||o.status<0)&&this.cache.del(n),o}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:H.Unknown,message:r instanceof Error?`${r.message}
|
|
2
|
+
${r.stack||""}`:String(r),headers:{},data:null}}}async guard(e,s,n){return je(e,s,this.config,n)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,s){const n=Object.assign({},s||null);return n.method="HEAD",this.guard(e,await this.request(e,n),null)}async get(e,s,n){const r=Object.assign({},n||null);r.method="GET";const o=this.request(e,r);return this.guard(e,await o,s||null)}async post(e,s,n,r){const o=Object.assign({},r||null);return o.method="POST",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async del(e,s,n){const r=Object.assign({},n||null);return r.method="DELETE",this.guard(e,await this.request(e,r),s||null)}async put(e,s,n,r){const o=Object.assign({},r||null);return o.method="PUT",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async patch(e,s,n,r){const o=Object.assign({},r||null);return o.method="PATCH",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}}async function Ee(t,e,s){const n=Object.assign({method:"GET"},s),r=k.FormData?n.body instanceof FormData:!1,o=r&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,i=o==="GET"||o==="HEAD"||o==="DELETE";i&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const u=Object.assign(r||i?{}:{"Content-Type":k.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),h=n.params||{},m={};Object.keys(h).forEach(_=>{h[_]!==void 0&&(m[_]=xe(h[_]))});const f=e.getFullUrl(t),c=Ne(n.body),g=n.timeout||e.get("timeout"),b=await async function(){const _=e.get("requestTransformer");if(_)return await _({headers:u,params:m,method:o,url:f,body:c})}(),w=typeof b=="string"&&b?b:f;return e.get("logHandler")?.({type:"ready",url:w,method:o,headers:u,timeout:g,body:c}),{url:w,method:o,body:c,params:m,headers:u,timeout:g,abort:n.abort,credentials:n.credentials||e.get("credentials")}}function xe(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function Ne(t){if(t)return typeof t=="string"||k.URLSearchParams&&t instanceof URLSearchParams||t instanceof ArrayBuffer||k.Blob&&t instanceof Blob||k.FormData&&t instanceof FormData?t:JSON.stringify(t)}const te="data",$="message";function Oe(t,e,s,n,r){const o=r||n;return G(t)?Ce(o.ok||n.ok,t,e,s):Se(o.failed||n.failed,e,s)}const Fe=function(t){const e=[],s=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(s.messageField||$)+" 作为错误消息");break}const n=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(n.dataField||te)+" 作为响应数据,读取 "+(n.messageField||$)+" 作为提示消息"),n.statusField&&e.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&e.push(" 并忽略以下消息:"+n.ignoreMessage);break}return e.join(`
|
|
3
|
+
`)};function Se(t,e,s){const n=t||{resolve:"json",messageField:$},r={ok:!1,code:e,message:s,data:null};switch(n.resolve){case"body":r.message=W(s)||s;break;case"json":const{code:o,message:i}=Te(s,n.converter,n.statusField,n.messageField);r.code=o||e,r.message=W(s)||i;break}return r}function Te(t,e,s,n=$){if(!Y(t))return{message:""};const r=A(F(t),e);return!r||!y(r)?{message:t}:{code:s?T(r,s):"",message:T(r,n)||t}}function T(t,e){const s=Array.isArray(e)?e:[e];for(const n of s)if(n in t)return Ae(t[n]);return""}function Ae(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const Ue=/<title>([^<]+)<\/title>/i,Me=/<message>([^<]+)<\/message>/i;function W(t){const e=t.match(Ue);if(e)return e[1];const s=t.match(Me);return s?s[1]:""}function Ce(t,e,s,n){const r=t||{resolve:"body"},o={ok:!0,code:s,message:"",data:null};if(e===204||!n)return o;if(r.resolve==="body")return o.data=Y(n)?A(F(n),t.converter):n,o;const i=A(F(n),t.converter);if(!i||!y(i))return o.ok=!1,o.code="ResponseFormatError",o.message="响应内容无法格式化为 Object",o;const u=r.statusField,h=r.statusOKValue||"",m=r.dataField||te,f=r.messageField||$,c=r.ignoreMessage||"";if(u&&!(u in i))return o.ok=!1,o.code="ResponseFieldMissing",o.message="响应内容找不到状态字段 "+u,o;const g=u?i[u]+"":"";return o.ok=u?g===h:!0,o.code=g||s,o.data=m===!0?i:m in i?i[m]:null,o.message=T(i,f),c&&o.message&&(Array.isArray(c)&&c.includes(o.message)||typeof c=="string"&&o.message===c)&&(o.message=""),o}function G(t){return t>=200&&t<400}function A(t,e){return e?typeof e=="function"?e(t):(console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'),t):t}const Pe=oe("APIError");function qe(t){const e={};for(const r in t.headers)(r.startsWith("x-")||r.includes("trace")||r.includes("server")||/\b(?:id|uuid)\b/.test(r))&&(e[r]=t.headers[r]);const s=t.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),n=t.status<0?"unknown":t.status;return{sentryError:new Pe(`${s} | ${n}${t.code?` | ${t.code}`:""}`),sentryTags:{...e,status:n,method:t.method,code:t.code||"unknown",message:t.message||"empty"},sentryExtra:{url:t.url,responseBody:t.body||"empty",responseHeaders:t.headers,rawError:t.error}}}function se(t){return t.reduce((e,[s,n])=>(s&&(e[s]=n||""),e),{})}function Ie(t,e,s,n){const r=t.status,o=t.method,i=se(Object.entries(t.headers||{}).map(([b,w])=>[b.toLowerCase(),w])),{ok:u,code:h,data:m,message:f}=Oe(r,t.statusText,t.body,s.get("responseRule"),n?.responseRule);if(!G(r)){const b=qe({url:t.url,method:t.method,status:r,code:h,message:f,body:t.body,headers:i,error:t.rawError});(s.get("errorHandler")||Le)({url:e,method:o,status:r,code:h,message:f,headers:i,rawError:t.rawError,responseBody:t.body,...b})}if(r<0)return J({ok:!1,status:r,code:t.statusText,headers:{},message:"",data:null},`${o} ${e} ${t.statusText}`,o,e,s,n);const c={ok:u,data:m,code:h,message:f,status:r,headers:i};s.get("responseHandler")?.({...c},o,e);const g=u?f:f||t.statusText;return J(c,g,o,e,s,n)}function J(t,e,s,n,r,o){const i=r.get("message"),u=i===!1||o?.message===!1?!1:o?.message||i;if(u!==!1){const h=typeof u=="function"?u(t,s,n,e):e;h instanceof Error?r.showMessage(!0,h.message,t.code,t.status):h&&typeof h=="object"&&"message"in h?r.showMessage(!1,h.message,t.code,t.status):r.showMessage(!t.ok,h,t.code,t.status)}return t}function Le(t){const e={};for(const s in t)s.startsWith("sentry")||(e[s]=t[s]);console.error("RequestError",e)}async function ne(t,e,s,n,r){const o=r||0,i=Math.max(0,Math.min(10,n?.maxRetry??s.get("maxRetry")??0)),u=n?.retryResolve??s.get("retryResolve"),h=s.get("logHandler");h?.({type:"prepare",url:e,method:n?.method||"GET",retry:o,maxRetry:i,message:o===0?"start":`retry ${o}/${i} start`,headers:n?.headers,options:n});const m=Date.now(),f=await t(e,s,n),c=f.status,g=Date.now()-m,b=`[cost ${g}][${c}] ${c<0?f.body:""}`;h?.({type:"finished",url:e,method:f.method,retry:o,maxRetry:i,message:o===0?`finish ${b}`:`retry ${o}/${i} finish ${b}`,response:f,headers:f.headers,cost:g});const w=G(c);if(!i||o>=i||u==="network"&&c>0||u==="status"&&w||Array.isArray(u)&&!u.includes(c)||typeof u=="function"&&u(f,o)!==!0)return f;const _=n?.retryInterval??s.get("retryInterval")??100;return await re(Math.max(100,_==="2EB"?Math.pow(2,o)*100:typeof _=="function"?_(o+1,{url:e,status:c,method:f.method})||0:_)),await ne(t,e,s,n,o+1)}exports.At=x;exports.NetRequestHandler=Re;exports.RequestGlobalConfig=ee;exports.RequestInternalError=H;exports.St=k;exports.ce=de;exports.convertOptions=Ee;exports.fromEntries=se;exports.getResponseRulesDescription=Fe;exports.handleResponse=Ie;exports.pe=be;exports.retryRequest=ne;
|
package/dist/wx.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-D_7OkloZ.cjs"),l=async function(e,o,u){return t.handleResponse(await t.retryRequest(p,e,o,u),e,o,u)},p=async function(e,o,u){const s=await t.convertOptions(e,o,u),a=s.method==="PATCH"?"POST":s.method,c=t.pe(s.url,s.params);return t.St.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:t.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?"":f(n.data)})}})}):{url:c,method:a,status:-1,statusText:t.RequestInternalError.NotSupport,body:""}};function f(e){return typeof e=="string"?e:e instanceof ArrayBuffer&&t.St.TextDecoder?new TextDecoder().decode(e):JSON.stringify(e)}function i(e){return new t.NetRequestHandler(l,e)}const r=i(),R=r.setConfig,y=r.head,g=r.get,q=r.post,h=r.del,x=r.put;exports.RequestInternalError=t.RequestInternalError;exports.getResponseRulesDescription=t.getResponseRulesDescription;exports.NetRequest=i;exports.del=h;exports.get=g;exports.head=y;exports.post=q;exports.put=x;exports.setGlobalConfig=R;
|
package/dist/wx.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { h as p, r as f, c as l,
|
|
2
|
-
import { g as H } from "./retry-
|
|
3
|
-
const
|
|
1
|
+
import { h as p, r as f, c as l, p as h, S as i, a as d, N as x } from "./retry-BXoyQlSJ.js";
|
|
2
|
+
import { g as H } from "./retry-BXoyQlSJ.js";
|
|
3
|
+
const y = async function(t, n, r) {
|
|
4
4
|
return p(await f(g, t, n, r), t, n, r);
|
|
5
5
|
}, g = async function(t, n, r) {
|
|
6
|
-
const e = await l(t, n, r), a = e.method === "PATCH" ? "POST" : e.method, u =
|
|
6
|
+
const e = await l(t, n, r), a = e.method === "PATCH" ? "POST" : e.method, u = h(e.url, e.params);
|
|
7
7
|
return i.wx ? new Promise((c) => {
|
|
8
8
|
wx.request({
|
|
9
9
|
url: u,
|
|
@@ -44,17 +44,17 @@ function m(t) {
|
|
|
44
44
|
return typeof t == "string" ? t : t instanceof ArrayBuffer && i.TextDecoder ? new TextDecoder().decode(t) : JSON.stringify(t);
|
|
45
45
|
}
|
|
46
46
|
function R(t) {
|
|
47
|
-
return new
|
|
47
|
+
return new x(y, t);
|
|
48
48
|
}
|
|
49
|
-
const s = R(), T = s.setConfig, q = s.head,
|
|
49
|
+
const s = R(), T = s.setConfig, q = s.head, b = s.get, C = s.post, S = s.del, N = s.put;
|
|
50
50
|
export {
|
|
51
51
|
R as NetRequest,
|
|
52
52
|
d as RequestInternalError,
|
|
53
|
-
|
|
54
|
-
|
|
53
|
+
S as del,
|
|
54
|
+
b as get,
|
|
55
55
|
H as getResponseRulesDescription,
|
|
56
56
|
q as head,
|
|
57
|
-
|
|
58
|
-
|
|
57
|
+
C as post,
|
|
58
|
+
N as put,
|
|
59
59
|
T as setGlobalConfig
|
|
60
60
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seayoo-web/request",
|
|
3
|
-
"version": "3.3.
|
|
3
|
+
"version": "3.3.3",
|
|
4
4
|
"description": "request tools for seayoo web",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"source": "./src/index.ts",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"happy-dom": "^12.10.3",
|
|
61
61
|
"msw": "^2.7.0",
|
|
62
62
|
"vitest": "^3.0.5",
|
|
63
|
-
"@seayoo-web/utils": "^3.
|
|
63
|
+
"@seayoo-web/utils": "^3.8.0"
|
|
64
64
|
},
|
|
65
65
|
"scripts": {
|
|
66
66
|
"prebuild": "pnpm --F utils build",
|
package/types/inc/cache.d.ts
CHANGED
|
@@ -3,9 +3,12 @@ import { RequestCacheResolve } from "./type";
|
|
|
3
3
|
export declare class Cache<T = unknown> {
|
|
4
4
|
private ttl;
|
|
5
5
|
private cache;
|
|
6
|
+
private timer;
|
|
7
|
+
private loopCheck;
|
|
6
8
|
constructor(ttl?: number);
|
|
7
9
|
getKey(method: string, url: string, param?: Record<string, unknown>, resolve?: RequestCacheResolve): string;
|
|
8
10
|
updateTTL(ttl: number): void;
|
|
9
11
|
get(key: string, ttl?: number): Promise<T> | null;
|
|
10
12
|
set(key: string, action: Promise<T>, ttl?: number): void;
|
|
13
|
+
del(key: string): void;
|
|
11
14
|
}
|
package/dist/retry-sL4_1f7S.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
"use strict";const l=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),K="wx"in l&&R(l.wx)&&"getSystemInfo"in l.wx&&d(l.wx.getSystemInfo),k={wx:K,fetch:"fetch"in l&&d(l.fetch),window:"window"in l&&R(l.window)&&!K,requestAnimationFrame:"requestAnimationFrame"in l&&d(l.requestAnimationFrame),localStorage:"localStorage"in l&&R(l.localStorage)&&"getItem"in l.localStorage&&d(l.localStorage.getItem),sessionStorage:"sessionStorage"in l&&R(l.sessionStorage)&&"getItem"in l.sessionStorage&&d(l.sessionStorage.getItem),File:"File"in l&&d(l.File),Blob:"Blob"in l&&d(l.Blob),Proxy:"Proxy"in l&&d(l.Proxy),Request:"Request"in l&&d(l.Request),FormData:"FormData"in l&&d(l.FormData),TextDecoder:"TextDecoder"in l&&d(l.TextDecoder),ResizeObserver:"ResizeObserver"in l&&d(l.ResizeObserver),AbortController:"AbortController"in l&&d(l.AbortController),URLSearchParams:"URLSearchParams"in l&&d(l.URLSearchParams),EventSource:"EventSource"in l&&d(l.EventSource)};function d(t){return typeof t=="function"}function R(t){return typeof t=="object"&&t!==null}function re(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function X(){}function Y(t,e){const s={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)},n=`[${t}]`;return["log","error","warn"].forEach(r=>{const o=console[r];s[r]=(...i)=>{o.apply(console,[n,...i])}}),s}function oe(t){const e=t||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:e,enumerable:!1,configurable:!0}),"setPrototypeOf"in Object&&Object.setPrototypeOf(this,new.target.prototype),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,this.constructor)}}}const ie=/^(?:https?:)?\/\/.+$/i,ae=/^https?:\/\/.+$/i,le=/^\{[\d\D]*\}$/,ue=/^\[[\d\D]*\]$/;function ce(t){return typeof t=="string"}function N(t,e=!1){return e?ie.test(t):ae.test(t)}function he(t){return t==null}function Q(t,...e){return t!==null&&typeof t=="object"&&!(t instanceof Map)&&!(t instanceof Set)&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!Array.isArray(t)&&e.every(s=>s in t)}function y(t,...e){if(!t||typeof t!="object")return!1;const s=Object.getPrototypeOf(t);return s!==Object.prototype&&s!==null?!1:e.every(n=>n in t)}function U(t,e){return Array.isArray(t)&&t.every(s=>e(s))}function x(t){if(typeof t!="number"||Number.isNaN(t)||!Number.isFinite(t))return!1;if(Number.isInteger(t))return Number.isSafeInteger(t);if(t===0)return!0;const e=Math.abs(t);return e>=Number.EPSILON&&e<=Number.MAX_SAFE_INTEGER}function Z(t){return le.test(t)||ue.test(t)}function fe(t,e=20){const s=Math.max(e,10),n=[...t];return n.length<=s?t:n.slice(0,s-3).join("")+"..."}function F(t,e){try{const s=JSON.parse(t);return e?e(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);Y("LoadUtils");async function de(t){return await new Promise(function(e){const s=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("charset","utf-8"),n.onload=function(){s.removeChild(n),e(!0)},n.onerror=function(){s.removeChild(n),e(!1)},n.setAttribute("src",t),s.appendChild(n)})}function z(t){return Object.getOwnPropertyNames(t).forEach(function(e){delete t[e]}),t}const g=Y("Validator");function j(t){return t?`"${fe(t).replace(/"/g,'\\"')}"`:"empty string"}function T(t){return typeof t=="object"&&t&&"constructor"in t&&typeof t.constructor=="function"?t.constructor.name||"ClassInstance":Object.prototype.toString.call(t).replace(/(?:.+ |]$)/g,"")}function O(t){return typeof t=="bigint"}function a(t){return new Error(`${t?`${t}()`:"method"} is not allowed after locked`)}class M{_ps={};_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;pattern(e,s){if(this._locked)throw a("pattern");return this._ps[`#${e||"custom"}`]=s,this}url(e=!1){if(this._locked)throw a("url");return this._ps.url=e?/^(?:https?:)?\/\/.+$/i:/^https?:\/\/.+$/i,this}dataUri(){if(this._locked)throw a("dataUri");return this._ps.dataUri=/^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$/,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,ce)?(this._allow=e,z(this._ps)):y(s)&&(this._allow=Object.values(s).map(n=>`${n}`),z(this._ps)),this}disallow(...e){return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new M;return e._ps={...this._ps},e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=g.warn){if(e===void 0)return this._opt||(s("should be a string, but got undefined"),!1);if(e===null)return this._null||(s("should be a string, but got null"),!1);if(typeof e!="string")return s(`should be a string, but got ${typeof e}`),!1;if(this._allow.length>0)return this._allow.includes(e)||(s(`${j(e)} is not allowed, just support ${this._allow.map(j).join(", ")}`),!1);if(this._reject.length>0&&this._reject.some(r=>typeof r=="string"?r===e:r.test(e)))return s(`${j(e)} is not allowed`),!1;const n=Object.keys(this._ps);return n.length>0&&!n.some(r=>{const o=this._ps[r];return o instanceof RegExp?o.test(e):o(e)})?(s(`${j(e)} is not match pattern ${n.join(" | ")}`),!1):!0}}class L{_int=!1;_min=-1/0;_max=1/0;_allow=[];_reject=[];_infinite=!1;_unsafe=!1;_nan=!1;_locked=!1;_opt=!1;_null=!1;int(){if(this._locked)throw a("int");return this._int=!0,this}min(e){if(this._locked)throw a("min");return Number.isNaN(e)||(this._min=e),this}max(e){if(this._locked)throw a("max");return Number.isNaN(e)||(this._max=e),this}allowNaN(){if(this._locked)throw a("allowNaN");return this._nan=!0,this}allowInfinity(){if(this._locked)throw a("allowInfinity");return this._infinite=!0,this._unsafe=!0,this}unsafe(){if(this._locked)throw a("unsafe");return this._unsafe=!0,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,x)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>x(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new L;return e._int=this._int,e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._infinite=this._infinite,e._unsafe=this._unsafe,e._nan=this._nan,e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a number, but got undefined"),!1):e===null?this._null||(s("should be a number, but got null"),!1):typeof e!="number"?(s(`should be a number, but got ${typeof e}`),!1):Number.isNaN(e)?this._nan||(s("should be a number, but got NaN"),!1):!Number.isFinite(e)&&!this._infinite?(s("should be a number, but got Infinity"),!1):this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):this._int&&Math.ceil(e)!==e?(s(`${e} is not an integer`),!1):!x(e)&&!this._unsafe?(s(`${e} is not a safe number`),!1):e>=this._min&&e<=this._max||(s(`${e} is not in range [${this._min}, ${this._max}]`),!1)}}class P{_min=null;_max=null;_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,O)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>O(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new P;return e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a bigint, but got undefined"),!1):e===null?this._null||(s("should be a bigint, but got null"),!1):O(e)?this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):(this._min!==null?e>=this._min:!0)&&(this._max!==null?e<=this._max:!0)||(s(`${e} is not in range [${this._min===null?-1/0:this._min}, ${this._max===null?1/0:this._max}]`),!1):(s(`should be a bigint, but got ${typeof e}`),!1)}}class C{_locked=!1;_opt=!1;_null=!1;optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new C}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a boolean, but got undefined"),!1):e===null?this._null||(s("should be a boolean, but got null"),!1):typeof e!="boolean"?(s(`should be a boolean, but got ${typeof e}`),!1):!0}}class v{_shape;_plain=!1;_locked=!1;_opt=!1;_null=!1;constructor(e){this._shape=e}plain(){if(this._locked)throw a("plain");return this._plain=!0,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}get shape(){return{...this._shape}}clone(){const e=new v(this._shape);return e._plain=this._plain,e._locked=!1,e}match(e,s){return e in this._shape?this._shape[e].validate(s,X):!1}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a object, but got undefined"),!1):e===null?this._null||(s("should be a object, but got null"),!1):Q(e)?this._plain&&!y(e)?(s(`should be a plain object, but got ${T(e)}`),!1):Object.keys(this._shape).every(n=>this._shape[n].validate(e[n],(...r)=>{s(`[.${String(n)}]`,...r)})):(s(`should be a object, but got ${T(e)}`),!1)}}class I{_val;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new I(this._val)}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a record, but got undefined"),!1):e===null?this._null||(s("should be a record, but got null"),!1):y(e)?Object.keys(e).every(n=>this._val.validate(e[n],(...r)=>{s(`[:${n}]`,...r)})):(s(`should be a record, but got ${T(e)}`),!1)}}class q{_val;_min=0;_max=1/0;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new q(this._val);return e._min=this._min,e._max=this._max,e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a array, but got undefined"),!1):e===null?this._null||(s("should be a array, but got null"),!1):Array.isArray(e)?e.length<this._min||e.length>this._max?(this._min===this._max?s(`should be a array with length ${this._min}`):s(`should be a array with length between ${this._min} and ${this._max}`),!1):e.every((n,r)=>this._val.validate(n,(...o)=>{s(`[${r}]`,...o)})):(s(`should be a array, but got ${typeof e}`),!1)}}class D{_vs;_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new D(...this._vs)}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a tuple, but got undefined"),!1):e===null?this._null||(s("should be a tuple, but got null"),!1):Array.isArray(e)?e.length!==this._vs.length?(s(`should be a tuple with length ${this._vs.length}, but got ${e.length}`),!1):this._vs.every((n,r)=>n.validate(e[r],(...o)=>{s(`[idx:${r}]`,...o)})):(s(`should be a tuple, but got ${typeof e}`),!1)}}class B{_vs;_key="";_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}key(e){if(this._locked)throw a("key");return this._vs.every(s=>s instanceof v)?this._key=e:g.warn("union type key can only be used when all validators are ObjectValidator"),this}satisfies(){return this}lock(){return this._locked=!0,this}get validators(){return[...this._vs]}clone(){const e=new B(...this._vs);return e._key=this._key,e._locked=!1,e}validate(e,s=g.warn){if(e===void 0)return this._opt||(s("should be a union, but got undefined"),!1);if(e===null)return this._null||(s("should be a union, but got null"),!1);if(this._key&&Q(e)&&e){const r=e[this._key];if(r===void 0)return s(`key field "${this._key}" is not found`,e),!1;const o=this._vs.find(i=>i instanceof v&&i.match(this._key,r));return o?o.validate(e,s):(s(`key field "${this._key}" value is match union definition`,r),!1)}const n=this._vs.some(r=>r.validate(e,X));return n||s("value is not match union definition",e),n}}class E{_name="";_guard;_locked=!1;_opt=!1;_null=!1;constructor(e,s){this._name=e,this._guard=s}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new E(this._name,this._guard)}validate(e,s=g.warn){const n=this._name||"custom type";return e===void 0?this._opt||(s(`should be ${n}, but got undefined`),!1):e===null?this._null||(s(`should be ${n}, but got null`),!1):this._guard(e)||(s(`custom validation${this._name?`(${this._name})`:""} failed`),!1)}}function me(t,e){if(typeof t=="string"){if(!e)throw new Error("custom type guard must be defined");return new E(t,e)}return new E("",t)}const _e={shape(t){return t},define(t){return t},guard(t){return function(e){return t.validate(e)}},object(t){return new v(t)},record(t){return new I(t)},array(t){return new q(t)},tuple(...t){return new D(...t)},union(...t){return new B(...t)},string(){return new M},bool(){return new C},number(){return new L},bigint(){return new P},custom:me,unknown(){return{validate(t){return!0}}},never(){return{validate(t){return!1}}}},ge=t=>y(t)&&Object.keys(t).length===0;_e.custom("EmptyObject",ge);function pe(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function be(t,e=""){return!e||N(t,!0)?V(t):(V(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function V(t){return N(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(/^\/+/,"")}function ye(t,e){const s={};return(t.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(n){const r=n.split("="),o=r[0],i=decodeURIComponent(r[1]||"");s[o]!==void 0?s[o]+=","+i:s[o]=i}),e!==!0?s[e]||"":s}function we(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const s=t.split("#"),n=s[0].split("?"),r=n[0],o=n.length>1?n[1]:"",i=s.length>1?"#"+s[1]:"",u=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!u.length||!o?s[0]+i:(u.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+o.replace(new RegExp("(?:^|&)(?:"+u.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+i)}function ke(t,e,s=!1){const n=typeof e=="string"?e:Object.keys(e).map(i=>`${i}=${encodeURIComponent(e[i])}`).join("&");if(!n)return t;const r=t.split("#");s&&(r[0]=we(r[0],(n.match(/([^=&#?]+)=[^&#]+/g)||[]).map(i=>i.replace(/=.+$/,""))));const o=r[0].indexOf("?")+1?"&":"?";return(r[0]+o+n+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}function ve(t){const e=t.match(/(?:\?|&)([^=]+)(?:&|$)/g);return e?e.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class $e{ttl;cache;constructor(e=500){this.cache={},this.ttl=Math.max(e,0)}getKey(e,s,n,r){if(e.toLowerCase()!=="get"&&!r)return"";const o=e.toLowerCase(),i=s.replace(/#.+/,""),u=i.replace(/\?.+/g,"");if(r){const h=r()||"";return h?`${u}_${o}_${h}`:""}const c=Object.assign(ye(i,!0),n),m=ve(i),f=Object.keys(c).sort().map(h=>`${h}#${c[h]}`);return`${u}_${o}_${f.join(",")}_${m.join(",")}`}updateTTL(e){this.ttl=Math.max(e,0)}get(e,s){if(Math.max(s??this.ttl,0)===0)return null;const r=this.cache[e];return r?r.ttl<Date.now()?(delete this.cache[e],null):r.res:null}set(e,s,n){const r=Math.max(n??this.ttl,0);r!==0&&(this.cache[e]={ttl:Date.now()+r,res:s})}}class ee{config={baseURL:"/",maxRetry:0,retryInterval:100,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}};constructor(e){e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!N(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return be(e,this.config.baseURL)}showMessage(e,s,n,r){this.config.messageHandler&&s&&this.config.messageHandler(e,s,n,r)}}const H={UnexpectResponse:"UnexpectResponse",Aborted:"Aborted",Unknown:"Unknown",NetworkError:"NetworkError",Timeout:"Timeout",NotSupport:"NotSupport",URLFormatError:"URLFormatError"};function je(t,e,s,n){if(e.ok&&!he(e.data)&&n){const r=pe(n,s.get("defaultTypeGuardMessage"));return r.guard(e.data)||(e.code=H.UnexpectResponse,s.showMessage(!0,`${t} ${r.message}`,e.code,e.status),console.error(e.code,t,e.data),e.data=null,e.message=r.message),e}return e}class Re{agent;config;cache;constructor(e,s){this.config=new ee(s),this.agent=e,this.cache=new $e(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)}async request(e,s){const n=this.cache.getKey(s?.method||"GET",e,s?.params,s?.cacheResolve);if(n){const r=this.cache.get(n,s?.cacheTTL);if(r)return await r}try{const r=this.agent(e,this.config,s);return n&&this.cache.set(n,r,s?.cacheTTL),await r}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:H.Unknown,message:r instanceof Error?`${r.message}
|
|
2
|
-
${r.stack||""}`:String(r),headers:{},data:null}}}async guard(e,s,n){return je(e,s,this.config,n)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,s){const n=Object.assign({},s||null);return n.method="HEAD",this.guard(e,await this.request(e,n),null)}async get(e,s,n){const r=Object.assign({},n||null);r.method="GET";const o=this.request(e,r);return this.guard(e,await o,s||null)}async post(e,s,n,r){const o=Object.assign({},r||null);return o.method="POST",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async del(e,s,n){const r=Object.assign({},n||null);return r.method="DELETE",this.guard(e,await this.request(e,r),s||null)}async put(e,s,n,r){const o=Object.assign({},r||null);return o.method="PUT",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async patch(e,s,n,r){const o=Object.assign({},r||null);return o.method="PATCH",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}}async function Ee(t,e,s){const n=Object.assign({method:"GET"},s),r=k.FormData?n.body instanceof FormData:!1,o=r&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,i=o==="GET"||o==="HEAD"||o==="DELETE";i&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const u=Object.assign(r||i?{}:{"Content-Type":k.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),c=n.params||{},m={};Object.keys(c).forEach(_=>{c[_]!==void 0&&(m[_]=Ne(c[_]))});const f=e.getFullUrl(t),h=xe(n.body),p=n.timeout||e.get("timeout"),b=await async function(){const _=e.get("requestTransformer");if(_)return await _({headers:u,params:m,method:o,url:f,body:h})}(),w=typeof b=="string"&&b?b:f;return e.get("logHandler")?.({type:"ready",url:w,method:o,headers:u,timeout:p,body:h}),{url:w,method:o,body:h,params:m,headers:u,timeout:p,abort:n.abort,credentials:n.credentials||e.get("credentials")}}function Ne(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function xe(t){if(t)return typeof t=="string"||k.URLSearchParams&&t instanceof URLSearchParams||t instanceof ArrayBuffer||k.Blob&&t instanceof Blob||k.FormData&&t instanceof FormData?t:JSON.stringify(t)}const te="data",$="message";function Oe(t,e,s,n,r){const o=r||n;return G(t)?Le(o.ok||n.ok,t,e,s):Te(o.failed||n.failed,e,s)}const Fe=function(t){const e=[],s=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(s.messageField||$)+" 作为错误消息");break}const n=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(n.dataField||te)+" 作为响应数据,读取 "+(n.messageField||$)+" 作为提示消息"),n.statusField&&e.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&e.push(" 并忽略以下消息:"+n.ignoreMessage);break}return e.join(`
|
|
3
|
-
`)};function Te(t,e,s){const n=t||{resolve:"json",messageField:$},r={ok:!1,code:e,message:s,data:null};switch(n.resolve){case"body":r.message=W(s)||s;break;case"json":const{code:o,message:i}=Se(s,n.converter,n.statusField,n.messageField);r.code=o||e,r.message=W(s)||i;break}return r}function Se(t,e,s,n=$){if(!Z(t))return{message:""};const r=A(F(t),e);return!r||!y(r)?{message:t}:{code:s?S(r,s):"",message:S(r,n)||t}}function S(t,e){const s=Array.isArray(e)?e:[e];for(const n of s)if(n in t)return Ae(t[n]);return""}function Ae(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const Ue=/<title>([^<]+)<\/title>/i,Me=/<message>([^<]+)<\/message>/i;function W(t){const e=t.match(Ue);if(e)return e[1];const s=t.match(Me);return s?s[1]:""}function Le(t,e,s,n){const r=t||{resolve:"body"},o={ok:!0,code:s,message:"",data:null};if(e===204||!n)return o;if(r.resolve==="body")return o.data=Z(n)?A(F(n),t.converter):n,o;const i=A(F(n),t.converter);if(!i||!y(i))return o.ok=!1,o.code="ResponseFormatError",o.message="响应内容无法格式化为 Object",o;const u=r.statusField,c=r.statusOKValue||"",m=r.dataField||te,f=r.messageField||$,h=r.ignoreMessage||"";if(u&&!(u in i))return o.ok=!1,o.code="ResponseFieldMissing",o.message="响应内容找不到状态字段 "+u,o;const p=u?i[u]+"":"";return o.ok=u?p===c:!0,o.code=p||s,o.data=m===!0?i:m in i?i[m]:null,o.message=S(i,f),h&&o.message&&(Array.isArray(h)&&h.includes(o.message)||typeof h=="string"&&o.message===h)&&(o.message=""),o}function G(t){return t>=200&&t<400}function A(t,e){return e?typeof e=="function"?e(t):(console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'),t):t}const Pe=oe("APIError");function Ce(t){const e={};for(const r in t.headers)(r.startsWith("x-")||r.includes("trace")||r.includes("server")||/\b(?:id|uuid)\b/.test(r))&&(e[r]=t.headers[r]);const s=t.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),n=t.status<0?"unknown":t.status;return{sentryError:new Pe(`${s} | ${n}${t.code?` | ${t.code}`:""}`),sentryTags:{...e,status:n,method:t.method,code:t.code||"unknown",message:t.message||"empty"},sentryExtra:{url:t.url,responseBody:t.body||"empty",responseHeaders:t.headers,rawError:t.error}}}function se(t){return t.reduce((e,[s,n])=>(s&&(e[s]=n||""),e),{})}function Ie(t,e,s,n){const r=t.status,o=t.method,i=se(Object.entries(t.headers||{}).map(([b,w])=>[b.toLowerCase(),w])),{ok:u,code:c,data:m,message:f}=Oe(r,t.statusText,t.body,s.get("responseRule"),n?.responseRule);if(!G(r)){const b=Ce({url:t.url,method:t.method,status:r,code:c,message:f,body:t.body,headers:i,error:t.rawError});(s.get("errorHandler")||qe)({url:e,method:o,status:r,code:c,message:f,headers:i,rawError:t.rawError,responseBody:t.body,...b})}if(r<0)return J({ok:!1,status:r,code:t.statusText,headers:{},message:"",data:null},`${o} ${e} ${t.statusText}`,o,e,s,n);const h={ok:u,data:m,code:c,message:f,status:r,headers:i};s.get("responseHandler")?.({...h},o,e);const p=u?f:f||t.statusText;return J(h,p,o,e,s,n)}function J(t,e,s,n,r,o){const i=r.get("message"),u=i===!1||o?.message===!1?!1:o?.message||i;if(u!==!1){const c=typeof u=="function"?u(t,s,n,e):e;c instanceof Error?r.showMessage(!0,c.message,t.code,t.status):c&&typeof c=="object"&&"message"in c?r.showMessage(!1,c.message,t.code,t.status):r.showMessage(!t.ok,c,t.code,t.status)}return t}function qe(t){const e={};for(const s in t)s.startsWith("sentry")||(e[s]=t[s]);console.error("RequestError",e)}async function ne(t,e,s,n,r){const o=r||0,i=Math.max(0,Math.min(10,n?.maxRetry??s.get("maxRetry")??0)),u=n?.retryResolve??s.get("retryResolve"),c=s.get("logHandler");c?.({type:"prepare",url:e,method:n?.method||"GET",retry:o,maxRetry:i,message:o===0?"start":`retry ${o}/${i} start`,headers:n?.headers,options:n});const m=Date.now(),f=await t(e,s,n),h=f.status,p=Date.now()-m,b=`[cost ${p}][${h}] ${h<0?f.body:""}`;c?.({type:"finished",url:e,method:f.method,retry:o,maxRetry:i,message:o===0?`finish ${b}`:`retry ${o}/${i} finish ${b}`,response:f,headers:f.headers,cost:p});const w=G(h);if(!i||o>=i||u==="network"&&h>0||u==="status"&&w||Array.isArray(u)&&!u.includes(h)||typeof u=="function"&&u(f,o)!==!0)return f;const _=n?.retryInterval??s.get("retryInterval")??100;return await re(Math.max(100,_==="2EB"?Math.pow(2,o)*100:typeof _=="function"?_(o+1,{url:e,status:h,method:f.method})||0:_)),await ne(t,e,s,n,o+1)}exports.Ct=k;exports.Et=N;exports.NetRequestHandler=Re;exports.RequestGlobalConfig=ee;exports.RequestInternalError=H;exports.convertOptions=Ee;exports.fromEntries=se;exports.getResponseRulesDescription=Fe;exports.handleResponse=Ie;exports.retryRequest=ne;exports.ue=de;exports.ye=ke;
|