@seayoo-web/request 2.0.9 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -138,6 +138,12 @@ setConfig({ timeout: 10000 })
138
138
 
139
139
  说明:用于控制 get 请求的缓冲时效,单位 ms,默认 500,设置为 0 则禁用缓冲
140
140
 
141
+ ### defaultTypeGuardMessage
142
+
143
+ 类型:string
144
+
145
+ 说明:默认的类型守卫错误提示,仅支持全局配置,默认 “响应数据未能正确识别“,单个 api 可通过传入完整的类型守卫({ guard, message })来定制提示消息。
146
+
141
147
  ### message
142
148
 
143
149
  类型:false | ((
@@ -288,7 +294,7 @@ status 表示网络错误或者http 状态码错误时重试;
288
294
 
289
295
  类型:null | ((isError: boolean, message: string, code: string, status:number) => void)
290
296
 
291
- 说明:全局默认提示函数,isError 表示需要提示的消息是否为错误消息,message 为提示内容,code 为状态描述码,status 为 http 状态码
297
+ 说明:全局默认提示函数,isError 表示需要提示的消息是否为错误消息,message 为提示内容,code 为状态描述码或内置错误码(可导出 RequestInteralError 进行对比),status 为 http 状态码
292
298
 
293
299
  ### logHandler
294
300
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./type-CzbYPhI4.cjs"),q=require("./request.fetch-ORK1-DKh.cjs"),y=async function(t,s,e){return o.handleResponse(await o.retryRequest(w,t,s,e),t,s,e)};async function m(t,s,e,n){const r=e==null?void 0:e.body,i=(e==null?void 0:e.method)==="PUT"?"PUT":"POST";if(s instanceof Blob){const u=new o.RequestGlobalConfig(n),f=await w(t,u,{...e,method:i,body:s});return o.handleResponse(f,t,u,e)}const c=new FormData,d={...s};r instanceof Object&&Object.entries(r).forEach(([u,f])=>{f instanceof Blob?d[u]=f:Array.isArray(f)?f.forEach((a,g)=>{c.append(`${u}[${g}]`,String(a))}):c.append(u,String(f))});for(const u in d)c.append(u,d[u]);const b=new o.RequestGlobalConfig(n),p=await w(t,b,{...e,method:i,body:c});return o.handleResponse(p,t,b,e)}const w=async function(t,s,e){const n=await o.convertOptions(t,s,e),r=n.method,i=e==null?void 0:e.onUploadProgress,c=o.Bt(n.url,n.params);return await new Promise(d=>{let b=null,p=!1;const u=function(){p||(a.abort(),p=!0)};function f(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",u)}const a=new XMLHttpRequest;if(a.open(r,c,!0),i){let g=1;a.upload.addEventListener("progress",h=>{g=h.total,i({total:h.total,loaded:h.loaded})}),a.addEventListener("load",()=>{i({loaded:g,total:g})})}a.addEventListener("load",()=>{f(),d({url:c,method:r,status:a.status,statusText:a.statusText,headers:E(a),body:r==="HEAD"?"":a.responseText})}),a.addEventListener("error",g=>{f(),d({url:c,method:r,status:-1,statusText:o.RequestInteralError.Unknown,body:"",rawError:g})},!0),a.addEventListener("abort",()=>{f(),d({url:c,method:r,status:-1,statusText:o.RequestInteralError.Aborted,body:""})}),Object.entries(n.headers).forEach(([g,h])=>{a.setRequestHeader(g,h)}),n.credentials==="include"&&(a.withCredentials=!0),a.send(n.body||void 0),n.abort&&n.abort.addEventListener("abort",u),n.timeout>0&&(b=setTimeout(u,n.timeout))})};function E(t){const s={};if(!t)return s;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
2
- `).forEach(n=>{const r=n.trim();if(!r)return;const i=r.split(":"),c=i[0].trim();c&&(s[c]=(i[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 r=e.callback+"";if(!t)return null;const i=o.Bt(t,e,!0);return new Promise(c=>{n[r]=function(d){if(r in window&&delete n[r],s(d))return d;console.warn("response type check faild",t,d),c(null)},o.je(i).catch(function(){c(null),delete n[r]})})}async function T(t,s,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await o.je(o.Bt(t,e,!0)).then(()=>{const r=n[e.var+""];return s(r)?r:(console.warn("response type check faild",t,r),null)}).catch(()=>null):null}const j=async function(t,s,e){return await m(t,s,e,{baseURL:l.getConfig("baseURL"),logHandler:l.getConfig("logHandler"),errorHandler:l.getConfig("errorHandler"),requestTransformer:l.getConfig("requestTransformer"),messageHandler:l.getConfig("messageHandler"),responseHandler:l.getConfig("responseHandler")})};function R(t){if(!o.Support.window)throw new Error("Default Module Only Support In Browser");return o.Support.fetch?new o.NetRequestHandler(q.fetchRequest,t):new o.NetRequestHandler(y,t)}const l=R(),C=l.setConfig,S=l.request,x=l.head,L=l.get,U=l.post,k=l.del,v=l.put,D=l.patch;exports.RequestInteralError=o.RequestInteralError;exports.getResponseRulesDescription=o.getResponseRulesDescription;exports.NetRequest=R;exports.del=k;exports.get=L;exports.head=x;exports.jsonp=H;exports.jsonx=T;exports.patch=D;exports.post=U;exports.put=v;exports.request=S;exports.setGlobalConfig=C;exports.upload=j;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./retry-CRrgnQtP.cjs"),q=require("./request.fetch-YPs3rgIZ.cjs"),y=async function(t,s,e){return o.handleResponse(await o.retryRequest(R,t,s,e),t,s,e)};async function m(t,s,e,n){const r=e==null?void 0:e.body,u=(e==null?void 0:e.method)==="PUT"?"PUT":"POST";if(s instanceof Blob){const i=new o.RequestGlobalConfig(n),f=await R(t,i,{...e,method:u,body:s});return o.handleResponse(f,t,i,e)}const c=new FormData,d={...s};r instanceof Object&&Object.entries(r).forEach(([i,f])=>{f instanceof Blob?d[i]=f:Array.isArray(f)?f.forEach((a,g)=>{c.append(`${i}[${g}]`,String(a))}):c.append(i,String(f))});for(const i in d)c.append(i,d[i]);const b=new o.RequestGlobalConfig(n),w=await R(t,b,{...e,method:u,body:c});return o.handleResponse(w,t,b,e)}const R=async function(t,s,e){const n=await o.convertOptions(t,s,e),r=n.method,u=e==null?void 0:e.onUploadProgress,c=o.Ht(n.url,n.params);return await new Promise(d=>{let b=null,w=!1;const i=function(){w||(a.abort(),w=!0)};function f(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",i)}const a=new XMLHttpRequest;if(a.open(r,c,!0),u){let g=1;a.upload.addEventListener("progress",h=>{g=h.total,u({total:h.total,loaded:h.loaded})}),a.addEventListener("load",()=>{u({loaded:g,total:g})})}a.addEventListener("load",()=>{f(),d({url:c,method:r,status:a.status,statusText:a.statusText,headers:H(a),body:r==="HEAD"?"":a.responseText})}),a.addEventListener("error",g=>{f(),d({url:c,method:r,status:-1,statusText:o.RequestInteralError.Unknown,body:"",rawError:g})},!0),a.addEventListener("abort",()=>{f(),d({url:c,method:r,status:-1,statusText:o.RequestInteralError.Aborted,body:""})}),Object.entries(n.headers).forEach(([g,h])=>{a.setRequestHeader(g,h)}),n.credentials==="include"&&(a.withCredentials=!0),a.send(n.body||void 0),n.abort&&n.abort.addEventListener("abort",i),n.timeout>0&&(b=setTimeout(i,n.timeout))})};function H(t){const s={};if(!t)return s;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
2
+ `).forEach(n=>{const r=n.trim();if(!r)return;const u=r.split(":"),c=u[0].trim();c&&(s[c]=(u[1]||"").trim())}),s}async function E(t,s,e={}){const n=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const r=e.callback+"";if(!t)return null;const u=o.Ht(t,e,!0);return new Promise(c=>{n[r]=function(d){if(r in window&&delete n[r],s(d))return d;console.warn("response type check faild",t,d),c(null)},o.Oe(u).catch(function(){c(null),delete n[r]})})}async function T(t,s,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await o.Oe(o.Ht(t,e,!0)).then(()=>{const r=n[e.var+""];return s(r)?r:(console.warn("response type check faild",t,r),null)}).catch(()=>null):null}const C=async function(t,s,e){return await m(t,s,e,{baseURL:l.getConfig("baseURL"),logHandler:l.getConfig("logHandler"),errorHandler:l.getConfig("errorHandler"),requestTransformer:l.getConfig("requestTransformer"),messageHandler:l.getConfig("messageHandler"),responseHandler:l.getConfig("responseHandler")})};function p(t){if(!o.ee.window)throw new Error("Default Module Only Support In Browser");return o.ee.fetch?new o.NetRequestHandler(q.fetchRequest,t):new o.NetRequestHandler(y,t)}const l=p(),x=l.setConfig,j=l.request,L=l.head,S=l.get,O=l.post,U=l.del,k=l.put,v=l.patch;exports.RequestInteralError=o.RequestInteralError;exports.getResponseRulesDescription=o.getResponseRulesDescription;exports.NetRequest=p;exports.del=U;exports.get=S;exports.head=L;exports.jsonp=E;exports.jsonx=T;exports.patch=v;exports.post=O;exports.put=k;exports.request=j;exports.setGlobalConfig=x;exports.upload=C;
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { h as w, r as T, R as y, c as x, B as p, a as R, j as E, S as H, N as q } from "./type-4NUOpogE.js";
2
- import { g as J } from "./type-4NUOpogE.js";
3
- import { f as C } from "./request.fetch-Bz5Ien15.js";
1
+ import { h as w, r as T, R as y, c as x, H as p, a as R, O as E, e as H, N as q } from "./retry-8Z8eLh90.js";
2
+ import { g as J } from "./retry-8Z8eLh90.js";
3
+ import { f as C } from "./request.fetch-idcpAgJt.js";
4
4
  const L = async function(t, a, e) {
5
5
  return w(await T(m, t, a, e), t, a, e);
6
6
  };
7
- async function S(t, a, e, n) {
7
+ async function U(t, a, e, n) {
8
8
  const r = e == null ? void 0 : e.body, i = (e == null ? void 0 : e.method) === "PUT" ? "PUT" : "POST";
9
9
  if (a instanceof Blob) {
10
10
  const l = new y(n), u = await m(t, l, {
@@ -54,7 +54,7 @@ const m = async function(t, a, e) {
54
54
  method: r,
55
55
  status: o.status,
56
56
  statusText: o.statusText,
57
- headers: j(o),
57
+ headers: k(o),
58
58
  body: r === "HEAD" ? "" : o.responseText
59
59
  });
60
60
  }), o.addEventListener(
@@ -83,7 +83,7 @@ const m = async function(t, a, e) {
83
83
  }), n.credentials === "include" && (o.withCredentials = !0), o.send(n.body || void 0), n.abort && n.abort.addEventListener("abort", l), n.timeout > 0 && (b = setTimeout(l, n.timeout));
84
84
  });
85
85
  };
86
- function j(t) {
86
+ function k(t) {
87
87
  const a = {};
88
88
  if (!t)
89
89
  return a;
@@ -97,7 +97,7 @@ function j(t) {
97
97
  s && (a[s] = (i[1] || "").trim());
98
98
  }), a;
99
99
  }
100
- async function D(t, a, e = {}) {
100
+ async function v(t, a, e = {}) {
101
101
  const n = window;
102
102
  "callback" in e || (e.callback = "jsonxData" + Math.random().toString(16).slice(2));
103
103
  const r = e.callback + "";
@@ -114,7 +114,7 @@ async function D(t, a, e = {}) {
114
114
  });
115
115
  });
116
116
  }
117
- async function O(t, a, e = {}) {
117
+ async function D(t, a, e = {}) {
118
118
  const n = window;
119
119
  return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), t ? await E(p(t, e, !0)).then(() => {
120
120
  const r = n[e.var + ""];
@@ -122,7 +122,7 @@ async function O(t, a, e = {}) {
122
122
  }).catch(() => null) : null;
123
123
  }
124
124
  const P = async function(t, a, e) {
125
- return await S(t, a, e, {
125
+ return await U(t, a, e, {
126
126
  baseURL: c.getConfig("baseURL"),
127
127
  logHandler: c.getConfig("logHandler"),
128
128
  errorHandler: c.getConfig("errorHandler"),
@@ -131,25 +131,25 @@ const P = async function(t, a, e) {
131
131
  responseHandler: c.getConfig("responseHandler")
132
132
  });
133
133
  };
134
- function U(t) {
134
+ function O(t) {
135
135
  if (!H.window)
136
136
  throw new Error("Default Module Only Support In Browser");
137
137
  return H.fetch ? new q(C, t) : new q(L, t);
138
138
  }
139
- const c = U(), A = c.setConfig, B = c.request, M = c.head, N = c.get, X = c.post, F = c.del, G = c.put, I = c.patch;
139
+ const c = O(), A = c.setConfig, M = c.request, N = c.head, B = c.get, X = c.post, F = c.del, G = c.put, I = c.patch;
140
140
  export {
141
- U as NetRequest,
141
+ O as NetRequest,
142
142
  R as RequestInteralError,
143
143
  F as del,
144
- N as get,
144
+ B as get,
145
145
  J as getResponseRulesDescription,
146
- M as head,
147
- D as jsonp,
148
- O as jsonx,
146
+ N as head,
147
+ v as jsonp,
148
+ D as jsonx,
149
149
  I as patch,
150
150
  X as post,
151
151
  G as put,
152
- B as request,
152
+ M as request,
153
153
  A as setGlobalConfig,
154
154
  P as upload
155
155
  };
package/dist/node.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./type-CzbYPhI4.cjs"),b=require("./request.fetch-ORK1-DKh.cjs"),y=require("node:http"),g=require("node:https"),w=async function(o,a,c){return e.handleResponse(await e.retryRequest(E,o,a,c),o,a,c)},E=async function(o,a,c){const t=await e.convertOptions(o,a,c);if(!e.X(t.url))return{url:t.url,method:t.method,status:-1,statusText:e.RequestInteralError.URLFormatError,headers:{},body:""};const q=/^https:\/\//i.test(t.url)?g:y,u=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>u.searchParams.set(n,i[n]));const f=t.method==="HEAD";return new Promise(n=>{const d=q.request(u,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(s){const l=[];s.on("data",h=>l.push(h)),s.on("end",()=>{const h=e.fromEntries(Object.entries(s.headers).map(([R,m])=>[R.toLowerCase(),Array.isArray(m)?m.join(","):m]));n({url:u.toString(),method:t.method,status:s.statusCode||-1,statusText:s.statusMessage||e.RequestInteralError.Unknown,headers:h,body:f?"":Buffer.concat(l).toString("utf-8")})})});d.on("error",s=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInteralError.Unknown,body:"",rawError:s})}),d.on("timeout",()=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInteralError.Timeout,body:""})}),t.body&&d.write(t.body),d.end()})};function p(o){return e.Support.fetch?new e.NetRequestHandler(b.fetchRequest,o):new e.NetRequestHandler(w,o)}const r=p(),S=r.setConfig,T=r.head,j=r.get,C=r.post,N=r.del,O=r.put,U=r.patch;exports.NetRequest=p;exports.del=N;exports.get=j;exports.head=T;exports.patch=U;exports.post=C;exports.put=O;exports.setGlobalConfig=S;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-CRrgnQtP.cjs"),b=require("./request.fetch-YPs3rgIZ.cjs"),y=require("node:http"),g=require("node:https"),w=async function(o,u,c){return e.handleResponse(await e.retryRequest(E,o,u,c),o,u,c)},E=async function(o,u,c){const t=await e.convertOptions(o,u,c);if(!e.Y(t.url))return{url:t.url,method:t.method,status:-1,statusText:e.RequestInteralError.URLFormatError,headers:{},body:""};const p=/^https:\/\//i.test(t.url)?g:y,a=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>a.searchParams.set(n,i[n]));const f=t.method==="HEAD";return new Promise(n=>{const d=p.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(s){const l=[];s.on("data",h=>l.push(h)),s.on("end",()=>{const h=e.fromEntries(Object.entries(s.headers).map(([R,m])=>[R.toLowerCase(),Array.isArray(m)?m.join(","):m]));n({url:a.toString(),method:t.method,status:s.statusCode||-1,statusText:s.statusMessage||e.RequestInteralError.Unknown,headers:h,body:f?"":Buffer.concat(l).toString("utf-8")})})});d.on("error",s=>{n({url:a.toString(),method:t.method,status:-1,statusText:e.RequestInteralError.Unknown,body:"",rawError:s})}),d.on("timeout",()=>{n({url:a.toString(),method:t.method,status:-1,statusText:e.RequestInteralError.Timeout,body:""})}),t.body&&d.write(t.body),d.end()})};function q(o){return e.ee.fetch?new e.NetRequestHandler(b.fetchRequest,o):new e.NetRequestHandler(w,o)}const r=q(),S=r.setConfig,T=r.head,j=r.get,C=r.post,N=r.del,O=r.put,U=r.patch;exports.NetRequest=q;exports.del=N;exports.get=j;exports.head=T;exports.patch=U;exports.post=C;exports.put=O;exports.setGlobalConfig=S;
package/dist/node.js CHANGED
@@ -1,10 +1,10 @@
1
- import { h as y, r as q, c as w, X as g, a as d, f as E, N as f, S } from "./type-4NUOpogE.js";
2
- import { f as x } from "./request.fetch-Bz5Ien15.js";
3
- import T from "node:http";
4
- import U from "node:https";
5
- const j = async function(e, a, u) {
6
- return y(await q(C, e, a, u), e, a, u);
7
- }, C = async function(e, a, u) {
1
+ import { h as y, r as q, c as w, Y as g, a as d, f as E, N as p, e as x } from "./retry-8Z8eLh90.js";
2
+ import { f as T } from "./request.fetch-idcpAgJt.js";
3
+ import U from "node:http";
4
+ import j from "node:https";
5
+ const C = async function(e, a, u) {
6
+ return y(await q(L, e, a, u), e, a, u);
7
+ }, L = async function(e, a, u) {
8
8
  const t = await w(e, a, u);
9
9
  if (!g(t.url))
10
10
  return {
@@ -15,7 +15,7 @@ const j = async function(e, a, u) {
15
15
  headers: {},
16
16
  body: ""
17
17
  };
18
- const l = /^https:\/\//i.test(t.url) ? U : T, n = new URL(t.url), i = t.params;
18
+ const l = /^https:\/\//i.test(t.url) ? j : U, n = new URL(t.url), i = t.params;
19
19
  i instanceof Object && Object.keys(i).forEach((r) => n.searchParams.set(r, i[r]));
20
20
  const R = t.method === "HEAD";
21
21
  return new Promise((r) => {
@@ -27,8 +27,8 @@ const j = async function(e, a, u) {
27
27
  timeout: t.timeout > 0 ? t.timeout : void 0
28
28
  },
29
29
  function(o) {
30
- const p = [];
31
- o.on("data", (m) => p.push(m)), o.on("end", () => {
30
+ const f = [];
31
+ o.on("data", (m) => f.push(m)), o.on("end", () => {
32
32
  const m = E(
33
33
  Object.entries(o.headers).map(([b, h]) => [b.toLowerCase(), Array.isArray(h) ? h.join(",") : h])
34
34
  );
@@ -38,7 +38,7 @@ const j = async function(e, a, u) {
38
38
  status: o.statusCode || -1,
39
39
  statusText: o.statusMessage || d.Unknown,
40
40
  headers: m,
41
- body: R ? "" : Buffer.concat(p).toString("utf-8")
41
+ body: R ? "" : Buffer.concat(f).toString("utf-8")
42
42
  });
43
43
  });
44
44
  }
@@ -63,12 +63,12 @@ const j = async function(e, a, u) {
63
63
  }), t.body && c.write(t.body), c.end();
64
64
  });
65
65
  };
66
- function L(e) {
67
- return S.fetch ? new f(x, e) : new f(j, e);
66
+ function N(e) {
67
+ return x.fetch ? new p(T, e) : new p(C, e);
68
68
  }
69
- const s = L(), k = s.setConfig, P = s.head, B = s.get, D = s.post, F = s.del, G = s.put, I = s.patch;
69
+ const s = N(), k = s.setConfig, P = s.head, B = s.get, D = s.post, F = s.del, G = s.put, I = s.patch;
70
70
  export {
71
- L as NetRequest,
71
+ N as NetRequest,
72
72
  F as del,
73
73
  B as get,
74
74
  P as head,
@@ -0,0 +1 @@
1
+ "use strict";const s=require("./retry-CRrgnQtP.cjs"),f=async function(o,n,i){return s.handleResponse(await s.retryRequest(w,o,n,i),o,n,i)},w=async function(o,n,i){const t=await s.convertOptions(o,n,i),a=new URL(t.url),u=t.params;u instanceof Object&&Object.keys(u).forEach(e=>a.searchParams.set(e,u[e]));const r=s.ee.AbortController?new AbortController:null;function c(){r&&!r.signal.aborted&&r.abort()}t.abort&&t.abort.addEventListener("abort",c);const h=t.timeout>0?setTimeout(c,t.timeout):null,b=t.method==="HEAD";return await fetch(a,{method:t.method,headers:Object.keys(t.headers).length>0?new Headers(t.headers):void 0,body:t.body,credentials:t.credentials,signal:r==null?void 0:r.signal,redirect:"follow"}).then(async e=>{const d=b?"":await e.text().catch(m=>m),l=s.fromEntries([...e.headers.entries()]);return d instanceof Error?{url:a.toString(),method:t.method,status:e.status,statusText:e.statusText||s.RequestInteralError.Unknown,body:"",headers:l,rawError:d}:{url:a.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:l,body:d}}).catch(e=>({url:a.toString(),method:t.method,status:-1,statusText:r!=null&&r.signal.aborted?s.RequestInteralError.Aborted:s.RequestInteralError.Unknown,body:"",rawError:e})).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",c)})};exports.fetchRequest=f;
@@ -1,16 +1,16 @@
1
- import { h as f, r as w, c as y, S as E, f as p, a as d } from "./type-4NUOpogE.js";
2
- const R = async function(s, o, n) {
3
- return f(await w(g, s, o, n), s, o, n);
4
- }, g = async function(s, o, n) {
5
- const t = await y(s, o, n), r = new URL(t.url), i = t.params;
6
- i instanceof Object && Object.keys(i).forEach((e) => r.searchParams.set(e, i[e]));
1
+ import { h as f, r as w, c as y, e as E, f as g, a as d } from "./retry-8Z8eLh90.js";
2
+ const T = async function(r, o, n) {
3
+ return f(await w(x, r, o, n), r, o, n);
4
+ }, x = async function(r, o, n) {
5
+ const t = await y(r, o, n), s = new URL(t.url), i = t.params;
6
+ i instanceof Object && Object.keys(i).forEach((e) => s.searchParams.set(e, i[e]));
7
7
  const a = E.AbortController ? new AbortController() : null;
8
- function u() {
8
+ function c() {
9
9
  a && !a.signal.aborted && a.abort();
10
10
  }
11
- t.abort && t.abort.addEventListener("abort", u);
12
- const h = t.timeout > 0 ? setTimeout(u, t.timeout) : null, l = t.method === "HEAD";
13
- return await fetch(r, {
11
+ t.abort && t.abort.addEventListener("abort", c);
12
+ const h = t.timeout > 0 ? setTimeout(c, t.timeout) : null, l = t.method === "HEAD";
13
+ return await fetch(s, {
14
14
  method: t.method,
15
15
  headers: Object.keys(t.headers).length > 0 ? new Headers(t.headers) : void 0,
16
16
  body: t.body,
@@ -18,34 +18,34 @@ const R = async function(s, o, n) {
18
18
  signal: a == null ? void 0 : a.signal,
19
19
  redirect: "follow"
20
20
  }).then(async (e) => {
21
- const c = l ? "" : await e.text().catch((m) => m), b = p([...e.headers.entries()]);
22
- return c instanceof Error ? {
23
- url: r.toString(),
21
+ const u = l ? "" : await e.text().catch((m) => m), b = g([...e.headers.entries()]);
22
+ return u instanceof Error ? {
23
+ url: s.toString(),
24
24
  method: t.method,
25
25
  status: e.status,
26
26
  statusText: e.statusText || d.Unknown,
27
27
  body: "",
28
28
  headers: b,
29
- rawError: c
29
+ rawError: u
30
30
  } : {
31
- url: r.toString(),
31
+ url: s.toString(),
32
32
  method: t.method,
33
33
  status: e.status,
34
34
  statusText: e.statusText,
35
35
  headers: b,
36
- body: c
36
+ body: u
37
37
  };
38
38
  }).catch((e) => ({
39
- url: r.toString(),
39
+ url: s.toString(),
40
40
  method: t.method,
41
41
  status: -1,
42
42
  statusText: a != null && a.signal.aborted ? d.Aborted : d.Unknown,
43
43
  body: "",
44
44
  rawError: e
45
45
  })).finally(() => {
46
- h !== null && clearTimeout(h), t.abort && t.abort.removeEventListener("abort", u);
46
+ h !== null && clearTimeout(h), t.abort && t.abort.removeEventListener("abort", c);
47
47
  });
48
48
  };
49
49
  export {
50
- R as f
50
+ T as f
51
51
  };
@@ -1,27 +1,27 @@
1
- var H = Object.defineProperty;
2
- var q = (e, t, s) => t in e ? H(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
- var y = (e, t, s) => q(e, typeof t != "symbol" ? t + "" : t, s);
4
- const p = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof window < "u" ? window : {}, O = {
5
- fetch: "fetch" in p,
6
- window: "window" in p,
7
- FormData: "FormData" in p,
8
- Blob: "Blob" in p,
9
- wx: "wx" in p,
10
- TextDecoder: "TextDecoder" in p,
11
- AbortController: "AbortController" in p
1
+ var N = Object.defineProperty;
2
+ var K = (e, t, s) => t in e ? N(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
+ var y = (e, t, s) => K(e, typeof t != "symbol" ? t + "" : t, s);
4
+ const h = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof self < "u" ? self : typeof window < "u" ? window : {}, k = {
5
+ wx: "wx" in h && U(h.wx),
6
+ fetch: "fetch" in h && w(h.fetch),
7
+ window: "window" in h && U(h.window),
8
+ Blob: "Blob" in h && w(h.Blob),
9
+ FormData: "FormData" in h && w(h.FormData),
10
+ TextDecoder: "TextDecoder" in h && w(h.TextDecoder),
11
+ AbortController: "AbortController" in h && w(h.AbortController)
12
12
  };
13
- function N(e) {
14
- return e.reduce(
15
- (t, [s, r]) => (s && (t[s] = r || ""), t),
16
- {}
17
- );
13
+ function w(e) {
14
+ return typeof e == "function";
18
15
  }
19
- function K(e) {
16
+ function U(e) {
17
+ return typeof e == "object" && e !== null;
18
+ }
19
+ function G(e) {
20
20
  return new Promise((t) => setTimeout(t, Math.max(0, e)));
21
21
  }
22
22
  function I() {
23
23
  }
24
- function G(e) {
24
+ function J(e) {
25
25
  const t = e || "CustomError";
26
26
  return class extends Error {
27
27
  constructor(s) {
@@ -33,33 +33,33 @@ function G(e) {
33
33
  }
34
34
  };
35
35
  }
36
- const J = /^(?:https?:)?\/\/.+$/i, V = /^https?:\/\/.+$/i, W = /^\{[\d\D]*\}$/, z = /^\[[\d\D]*\]$/;
37
- function T(e, t = !1) {
38
- return t ? J.test(e) : V.test(e);
36
+ const V = /^(?:https?:)?\/\/.+$/i, W = /^https?:\/\/.+$/i, z = /^\{[\d\D]*\}$/, Y = /^\[[\d\D]*\]$/;
37
+ function A(e, t = !1) {
38
+ return t ? V.test(e) : W.test(e);
39
39
  }
40
- function X(e) {
40
+ function Z(e) {
41
41
  return e == null;
42
42
  }
43
- function k(e, ...t) {
43
+ function E(e, ...t) {
44
44
  if (!e || typeof e != "object") return !1;
45
45
  const s = Object.getPrototypeOf(e);
46
46
  return s !== Object.prototype && s !== null ? !1 : t.every((r) => r in e);
47
47
  }
48
48
  function S(e) {
49
- return W.test(e) || z.test(e);
49
+ return z.test(e) || Y.test(e);
50
50
  }
51
- function j(e) {
51
+ function $(e) {
52
52
  return e ? e[0].toLowerCase() + e.slice(1) : "";
53
53
  }
54
- const x = /_\w*/, P = /-\w*/;
55
- function C(e) {
56
- const t = x.test(e) ? e.replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (s, r) => r.toUpperCase()) : P.test(e) ? e.replace(/(?:^-*|-*$)/g, "").replace(/-+(\w)/g, (s, r) => r.toUpperCase()) : e;
57
- return j(t);
54
+ const _ = /_\w*/, B = /-\w*/;
55
+ function D(e) {
56
+ const t = _.test(e) ? e.replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (s, r) => r.toUpperCase()) : B.test(e) ? e.replace(/(?:^-*|-*$)/g, "").replace(/-+(\w)/g, (s, r) => r.toUpperCase()) : e;
57
+ return $(t);
58
58
  }
59
- function U(e) {
60
- return x.test(e) ? j(e).replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (t, s) => "_" + s.toLowerCase()) : P.test(e) ? j(e.replace(/(?:^-*|-*$)/g, "")).replace(/-+(\w)/g, (t, s) => "_" + s.toLowerCase()) : j(e).replace(/[A-Z]/g, (t) => `_${t.toLowerCase()}`);
59
+ function M(e) {
60
+ return _.test(e) ? $(e).replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (t, s) => "_" + s.toLowerCase()) : B.test(e) ? $(e.replace(/(?:^-*|-*$)/g, "")).replace(/-+(\w)/g, (t, s) => "_" + s.toLowerCase()) : $(e).replace(/[A-Z]/g, (t) => `_${t.toLowerCase()}`);
61
61
  }
62
- function E(e, t) {
62
+ function v(e, t) {
63
63
  try {
64
64
  const s = JSON.parse(e);
65
65
  return t ? t(s) ? s : null : s;
@@ -68,25 +68,25 @@ function E(e, t) {
68
68
  }
69
69
  }
70
70
  "" + Math.random().toString(32).slice(2);
71
- function $(e, t = !1) {
72
- return typeof e == "string" ? C(e) : Array.isArray(e) ? e.map((s) => !t || typeof s == "string" ? $(s) : typeof s == "object" && s ? $(s, !0) : s) : k(e) ? Object.keys(e).reduce(
71
+ function R(e, t = !1) {
72
+ return typeof e == "string" ? D(e) : Array.isArray(e) ? e.map((s) => !t || typeof s == "string" ? R(s) : typeof s == "object" && s ? R(s, !0) : s) : E(e) ? Object.keys(e).reduce(
73
73
  (s, r) => {
74
- const a = C(String(r)), n = a.charAt(0).toLowerCase() + a.slice(1);
75
- return s[n] = t ? e[r] : $(e[r]), s;
74
+ const a = D(String(r)), n = a.charAt(0).toLowerCase() + a.slice(1);
75
+ return s[n] = t ? e[r] : R(e[r]), s;
76
76
  },
77
77
  {}
78
78
  ) : e;
79
79
  }
80
- function R(e, t = !1) {
81
- return typeof e == "string" ? U(e) : Array.isArray(e) ? e.map((s) => !t || typeof s == "string" ? R(s) : typeof s == "object" && s ? R(s, t) : s) : k(e) ? Object.keys(e).reduce(
80
+ function O(e, t = !1) {
81
+ return typeof e == "string" ? M(e) : Array.isArray(e) ? e.map((s) => !t || typeof s == "string" ? O(s) : typeof s == "object" && s ? O(s, t) : s) : E(e) ? Object.keys(e).reduce(
82
82
  (s, r) => {
83
- const a = U(String(r));
84
- return s[a] = t ? e[r] : R(e[r]), s;
83
+ const a = M(String(r));
84
+ return s[a] = t ? e[r] : O(e[r]), s;
85
85
  },
86
86
  {}
87
87
  ) : e;
88
88
  }
89
- async function je(e) {
89
+ async function $e(e) {
90
90
  return await new Promise(function(t) {
91
91
  const s = document.getElementsByTagName("head")[0], r = document.createElement("script");
92
92
  r.setAttribute("type", "text/javascript"), r.setAttribute("charset", "utf-8"), r.onload = function() {
@@ -96,7 +96,7 @@ async function je(e) {
96
96
  }, r.setAttribute("src", e), s.appendChild(r);
97
97
  });
98
98
  }
99
- function Z(e, t = "数据未能正确识别") {
99
+ function Q(e, t = "数据未能正确识别") {
100
100
  return typeof e == "function" ? {
101
101
  guard: e,
102
102
  message: t
@@ -105,20 +105,20 @@ function Z(e, t = "数据未能正确识别") {
105
105
  message: e.message || t
106
106
  };
107
107
  }
108
- function Q(e, t = "") {
109
- return !t || T(e, !0) ? L(e) : (L(t) + "/" + e).replace(/\/{2,}/g, "/").replace(/:\//, "://");
108
+ function X(e, t = "") {
109
+ return !t || A(e, !0) ? L(e) : (L(t) + "/" + e).replace(/\/{2,}/g, "/").replace(/:\//, "://");
110
110
  }
111
111
  function L(e) {
112
- return T(e, !0) ? e.startsWith("http") ? e : ("location" in globalThis ? location.protocol : "https:") + e : ("location" in globalThis ? location.origin : "http://127.0.0.1") + "/" + e.replace(/^\/+/, "");
112
+ return A(e, !0) ? e.startsWith("http") ? e : ("location" in globalThis ? location.protocol : "https:") + e : ("location" in globalThis ? location.origin : "http://127.0.0.1") + "/" + e.replace(/^\/+/, "");
113
113
  }
114
- function Y(e, t) {
114
+ function ee(e, t) {
115
115
  const s = {};
116
116
  return (e.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(r) {
117
117
  const a = r.split("="), n = a[0], o = decodeURIComponent(a[1] || "");
118
118
  s[n] !== void 0 ? s[n] += "," + o : s[n] = o;
119
119
  }), t !== !0 ? s[t] || "" : s;
120
120
  }
121
- function ee(e, t) {
121
+ function te(e, t) {
122
122
  if (t) {
123
123
  if (t === !0)
124
124
  return e.replace(/\?[^#]*/, "");
@@ -126,30 +126,30 @@ function ee(e, t) {
126
126
  const s = e.split("#"), r = s[0].split("?"), a = r[0], n = r.length > 1 ? r[1] : "", o = s.length > 1 ? "#" + s[1] : "", c = typeof t == "string" ? [t] : Array.isArray(t) ? t : [];
127
127
  return !c.length || !n ? s[0] + o : (c.map((i) => i.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (a + "?" + n.replace(new RegExp("(?:^|&)(?:" + c.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
128
128
  }
129
- function $e(e, t, s = !1) {
129
+ function Re(e, t, s = !1) {
130
130
  const r = typeof t == "string" ? t : Object.keys(t).map((o) => `${o}=${encodeURIComponent(t[o])}`).join("&");
131
131
  if (!r)
132
132
  return e;
133
133
  const a = e.split("#");
134
- s && (a[0] = ee(
134
+ s && (a[0] = te(
135
135
  a[0],
136
136
  (r.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
137
137
  ));
138
138
  const n = a[0].indexOf("?") + 1 ? "&" : "?";
139
139
  return (a[0] + n + r + (a.length > 1 ? "#" + a[1] : "")).replace(/\?&/, "?");
140
140
  }
141
- function te(e) {
141
+ function se(e) {
142
142
  const t = e.match(/(?:\?|&)([^=]+)(?:&|$)/g);
143
143
  return t ? t.join("").replace(/(?:\?|^&+|&+$)/g, "").replace(/&{2}/g, "&").split("&").sort() : [];
144
144
  }
145
- class se {
145
+ class re {
146
146
  constructor(t = 500) {
147
147
  y(this, "ttl");
148
148
  y(this, "cache");
149
149
  this.cache = {}, this.ttl = Math.max(t, 0);
150
150
  }
151
151
  getKey(t, s) {
152
- const r = t.replace(/#.+/, ""), a = r.replace(/\?.+/g, ""), n = Object.assign(Y(r, !0), s), o = te(r), c = Object.keys(n).sort().map((i) => `${i}#${n[i]}`);
152
+ const r = t.replace(/#.+/, ""), a = r.replace(/\?.+/g, ""), n = Object.assign(ee(r, !0), s), o = se(r), c = Object.keys(n).sort().map((i) => `${i}#${n[i]}`);
153
153
  return `${a}_${c.join(",")}_${o.join(",")}`;
154
154
  }
155
155
  updateTTL(t) {
@@ -168,7 +168,7 @@ class se {
168
168
  });
169
169
  }
170
170
  }
171
- class re {
171
+ class ne {
172
172
  constructor(t) {
173
173
  // 保存的配置需要部分字段强制设置默认值
174
174
  y(this, "config", {
@@ -179,6 +179,7 @@ class re {
179
179
  timeout: 1e4,
180
180
  cacheTTL: 500,
181
181
  credentials: "same-origin",
182
+ defaultTypeGuardMessage: "响应数据未能正确识别",
182
183
  responseRule: {
183
184
  ok: {
184
185
  resolve: "body"
@@ -192,7 +193,7 @@ class re {
192
193
  t && this.set(t);
193
194
  }
194
195
  set(t) {
195
- if (t.baseURL && !/^\/.+/.test(t.baseURL) && !T(t.baseURL))
196
+ if (t.baseURL && !/^\/.+/.test(t.baseURL) && !A(t.baseURL))
196
197
  throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
197
198
  Object.assign(this.config, t);
198
199
  }
@@ -201,27 +202,27 @@ class re {
201
202
  }
202
203
  /** 基于 baseURL 返回完整的 url 地址 */
203
204
  getFullUrl(t) {
204
- return Q(t, this.config.baseURL);
205
+ return X(t, this.config.baseURL);
205
206
  }
206
207
  /** 提示消息 */
207
208
  showMessage(t, s, r, a) {
208
209
  this.config.messageHandler && s && this.config.messageHandler(t, s, r, a);
209
210
  }
210
211
  }
211
- const M = "UnexpectResponse";
212
- function ne(e, t, s, r) {
213
- if (t.ok && !X(t.data) && r) {
214
- const a = Z(r, "响应数据未能正确识别");
215
- return a.guard(t.data) || (s.showMessage(!0, `${e} ${a.message}`, t.code, t.status), console.error(M, e, t.data), t.data = null, t.code = M, t.message = a.message), t;
212
+ var H = /* @__PURE__ */ ((e) => (e.UnexpectResponse = "UnexpectResponse", e.Aborted = "Aborted", e.Unknown = "Unknown", e.Timeout = "Timeout", e.NotSupport = "NotSupport", e.URLFormatError = "URLFormatError", e))(H || {});
213
+ function ae(e, t, s, r) {
214
+ if (t.ok && !Z(t.data) && r) {
215
+ const a = Q(r, s.get("defaultTypeGuardMessage"));
216
+ return a.guard(t.data) || (t.code = H.UnexpectResponse, s.showMessage(!0, `${e} ${a.message}`, t.code, t.status), console.error(t.code, e, t.data), t.data = null, t.message = a.message), t;
216
217
  }
217
218
  return t;
218
219
  }
219
- class Re {
220
+ class Oe {
220
221
  constructor(t, s) {
221
222
  y(this, "agent");
222
223
  y(this, "config");
223
224
  y(this, "cache");
224
- this.config = new re(s), this.agent = t, this.cache = new se(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);
225
+ this.config = new ne(s), this.agent = t, this.cache = new re(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);
225
226
  }
226
227
  /**
227
228
  * 执行网络请求
@@ -244,7 +245,7 @@ class Re {
244
245
  * 检查响应的数据类型
245
246
  */
246
247
  async guard(t, s, r) {
247
- return ne(t, s, this.config, r);
248
+ return ae(t, s, this.config, r);
248
249
  }
249
250
  /**
250
251
  * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
@@ -291,55 +292,55 @@ class Re {
291
292
  return n.method = "PATCH", n.body = s || {}, this.guard(t, await this.request(t, n), r || null);
292
293
  }
293
294
  }
294
- async function Oe(e, t, s) {
295
- var g;
296
- const r = Object.assign({ method: "GET" }, s), a = O.FormData ? r.body instanceof FormData : !1, n = a && r.method !== "POST" && r.method !== "PUT" ? "POST" : r.method, o = n === "GET" || n === "HEAD" || n === "DELETE";
295
+ async function ke(e, t, s) {
296
+ var m;
297
+ const r = Object.assign({ method: "GET" }, s), a = k.FormData ? r.body instanceof FormData : !1, n = a && r.method !== "POST" && r.method !== "PUT" ? "POST" : r.method, o = n === "GET" || n === "HEAD" || n === "DELETE";
297
298
  o && r.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete r.body);
298
299
  const c = Object.assign(
299
300
  a || o ? {} : {
300
- "Content-Type": O.Blob && r.body instanceof Blob ? r.body.type || "application/octet-stream" : "application/json;charset=utf-8"
301
+ "Content-Type": k.Blob && r.body instanceof Blob ? r.body.type || "application/octet-stream" : "application/json;charset=utf-8"
301
302
  },
302
303
  r.headers
303
- ), i = r.params || {}, h = {};
304
+ ), i = r.params || {}, d = {};
304
305
  Object.keys(i).forEach((b) => {
305
- i[b] !== void 0 && (h[b] = ae(i[b]));
306
+ i[b] !== void 0 && (d[b] = oe(i[b]));
306
307
  });
307
- const u = t.getFullUrl(e), l = oe(r.body), d = r.timeout || t.get("timeout"), f = await async function() {
308
+ const u = t.getFullUrl(e), l = ce(r.body), f = r.timeout || t.get("timeout"), g = await async function() {
308
309
  const b = t.get("requestTransformer");
309
310
  if (b)
310
- return await b({ headers: c, params: h, method: n, url: u, body: l });
311
- }(), m = typeof f == "string" && f ? f : u;
312
- return (g = t.get("logHandler")) == null || g({ type: "ready", url: m, method: n, headers: c, timeout: d, body: l }), {
313
- url: m,
311
+ return await b({ headers: c, params: d, method: n, url: u, body: l });
312
+ }(), p = typeof g == "string" && g ? g : u;
313
+ return (m = t.get("logHandler")) == null || m({ type: "ready", url: p, method: n, headers: c, timeout: f, body: l }), {
314
+ url: p,
314
315
  method: n,
315
316
  body: l,
316
- params: h,
317
+ params: d,
317
318
  headers: c,
318
- timeout: d,
319
+ timeout: f,
319
320
  abort: r.abort,
320
321
  credentials: r.credentials || t.get("credentials")
321
322
  };
322
323
  }
323
- function ae(e) {
324
+ function oe(e) {
324
325
  return typeof e == "string" ? e : Array.isArray(e) ? e.join(",") : e + "";
325
326
  }
326
- function oe(e) {
327
+ function ce(e) {
327
328
  if (e)
328
- return typeof e == "string" || e instanceof URLSearchParams || e instanceof ArrayBuffer || O.Blob && e instanceof Blob || O.FormData && e instanceof FormData ? e : JSON.stringify(e);
329
+ return typeof e == "string" || e instanceof URLSearchParams || e instanceof ArrayBuffer || k.Blob && e instanceof Blob || k.FormData && e instanceof FormData ? e : JSON.stringify(e);
329
330
  }
330
- const _ = "data", w = "message";
331
- function ce(e, t, s, r, a) {
331
+ const q = "data", j = "message";
332
+ function ie(e, t, s, r, a) {
332
333
  const n = a || r;
333
- return A(e) ? fe(n.ok || r.ok, e, t, s) : ie(n.failed || r.failed, t, s);
334
+ return C(e) ? ge(n.ok || r.ok, e, t, s) : ue(n.failed || r.failed, t, s);
334
335
  }
335
- const ke = function(e) {
336
+ const Ee = function(e) {
336
337
  const t = [], s = e.failed || { resolve: "json" };
337
338
  switch (t.push("- 当http状态码 <200 或者 >=400 时"), s.resolve) {
338
339
  case "body":
339
340
  t.push(" 将响应内容格式化为字符串并作为错误消息");
340
341
  break;
341
342
  case "json":
342
- t.push(" 将响应解析为json,并读取 " + (s.messageField || w) + " 作为错误消息");
343
+ t.push(" 将响应解析为json,并读取 " + (s.messageField || j) + " 作为错误消息");
343
344
  break;
344
345
  }
345
346
  const r = e.ok || { resolve: "body" };
@@ -349,7 +350,7 @@ const ke = function(e) {
349
350
  break;
350
351
  case "json":
351
352
  t.push(
352
- " 将响应解析为 json,读取 " + (r.dataField || _) + " 作为响应数据,读取 " + (r.messageField || w) + " 作为提示消息"
353
+ " 将响应解析为 json,读取 " + (r.dataField || q) + " 作为响应数据,读取 " + (r.messageField || j) + " 作为提示消息"
353
354
  ), r.statusField && t.push(
354
355
  " 当 " + r.statusField + " 为 " + (r.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"
355
356
  ), r.ignoreMessage && t.push(" 并忽略以下消息:" + r.ignoreMessage);
@@ -358,8 +359,8 @@ const ke = function(e) {
358
359
  return t.join(`
359
360
  `);
360
361
  };
361
- function ie(e, t, s) {
362
- const r = e || { resolve: "json", messageField: w }, a = {
362
+ function ue(e, t, s) {
363
+ const r = e || { resolve: "json", messageField: j }, a = {
363
364
  ok: !1,
364
365
  code: t,
365
366
  message: s,
@@ -367,43 +368,43 @@ function ie(e, t, s) {
367
368
  };
368
369
  switch (r.resolve) {
369
370
  case "body":
370
- a.message = D(s) || s;
371
+ a.message = x(s) || s;
371
372
  break;
372
373
  case "json":
373
- const { code: n, message: o } = ue(s, r.converter, r.statusField, r.messageField);
374
- a.code = n || t, a.message = D(s) || o;
374
+ const { code: n, message: o } = le(s, r.converter, r.statusField, r.messageField);
375
+ a.code = n || t, a.message = x(s) || o;
375
376
  break;
376
377
  }
377
378
  return a;
378
379
  }
379
- function ue(e, t, s, r = w) {
380
+ function le(e, t, s, r = j) {
380
381
  if (!S(e))
381
382
  return { message: "" };
382
- const a = F(E(e), t);
383
- return !a || !k(a) ? { message: e } : {
384
- code: s ? v(a, s) : "",
385
- message: v(a, r) || e
383
+ const a = F(v(e), t);
384
+ return !a || !E(a) ? { message: e } : {
385
+ code: s ? T(a, s) : "",
386
+ message: T(a, r) || e
386
387
  };
387
388
  }
388
- function v(e, t) {
389
+ function T(e, t) {
389
390
  const s = Array.isArray(t) ? t : [t];
390
391
  for (const r of s)
391
392
  if (r in e)
392
- return le(e[r]);
393
+ return he(e[r]);
393
394
  return "";
394
395
  }
395
- function le(e) {
396
+ function he(e) {
396
397
  return e ? typeof e == "string" ? e : JSON.stringify(e) : "";
397
398
  }
398
- const he = /<title>([^<]+)<\/title>/i, de = /<message>([^<]+)<\/message>/i;
399
- function D(e) {
400
- const t = e.match(he);
399
+ const de = /<title>([^<]+)<\/title>/i, fe = /<message>([^<]+)<\/message>/i;
400
+ function x(e) {
401
+ const t = e.match(de);
401
402
  if (t)
402
403
  return t[1];
403
- const s = e.match(de);
404
+ const s = e.match(fe);
404
405
  return s ? s[1] : "";
405
406
  }
406
- function fe(e, t, s, r) {
407
+ function ge(e, t, s, r) {
407
408
  const a = e || { resolve: "body" }, n = {
408
409
  ok: !0,
409
410
  code: s,
@@ -413,30 +414,30 @@ function fe(e, t, s, r) {
413
414
  if (t === 204 || !r)
414
415
  return n;
415
416
  if (a.resolve === "body")
416
- return n.data = S(r) ? F(E(r), e.converter) : r, n;
417
- const o = F(E(r), e.converter);
418
- if (!o || !k(o))
417
+ return n.data = S(r) ? F(v(r), e.converter) : r, n;
418
+ const o = F(v(r), e.converter);
419
+ if (!o || !E(o))
419
420
  return n.ok = !1, n.code = "ResponseFormatError", n.message = "响应内容无法格式化为 Object", n;
420
- const c = a.statusField, i = a.statusOKValue || "", h = a.dataField || _, u = a.messageField || w, l = a.ignoreMessage || "";
421
+ const c = a.statusField, i = a.statusOKValue || "", d = a.dataField || q, u = a.messageField || j, l = a.ignoreMessage || "";
421
422
  if (c && !(c in o))
422
423
  return n.ok = !1, n.code = "ResponseFieldMissing", n.message = "响应内容找不到状态字段 " + c, n;
423
- const d = c ? o[c] + "" : "";
424
- return n.ok = c ? d === i : !0, n.code = d || s, n.data = h === !0 ? o : h in o ? o[h] : null, n.message = v(o, u), l && n.message && (Array.isArray(l) && l.includes(n.message) || typeof l == "string" && n.message === l) && (n.message = ""), n;
424
+ const f = c ? o[c] + "" : "";
425
+ return n.ok = c ? f === i : !0, n.code = f || s, n.data = d === !0 ? o : d in o ? o[d] : null, n.message = T(o, u), l && n.message && (Array.isArray(l) && l.includes(n.message) || typeof l == "string" && n.message === l) && (n.message = ""), n;
425
426
  }
426
- function A(e) {
427
+ function C(e) {
427
428
  return e >= 200 && e < 400;
428
429
  }
429
430
  function F(e, t) {
430
- return t === "camelize" ? $(e) : t === "snakify" ? R(e) : e;
431
+ return t === "camelize" ? R(e) : t === "snakify" ? O(e) : e;
431
432
  }
432
- const ge = G("APIError");
433
- function me(e) {
433
+ const me = J("APIError");
434
+ function pe(e) {
434
435
  const t = {};
435
436
  for (const a in e.headers)
436
437
  (a.startsWith("x-") || a.includes("trace") || a.includes("server") || /\b(?:id|uuid)\b/.test(a)) && (t[a] = e.headers[a]);
437
438
  const s = e.url.replace(/^(?:https?:)?\/*/i, "").replace(/\?.+/, ""), r = e.status < 0 ? "unknown" : e.status;
438
439
  return {
439
- sentryError: new ge(`${s} | ${r}${e.code ? ` | ${e.code}` : ""}`),
440
+ sentryError: new me(`${s} | ${r}${e.code ? ` | ${e.code}` : ""}`),
440
441
  sentryTags: {
441
442
  ...t,
442
443
  status: r,
@@ -452,19 +453,25 @@ function me(e) {
452
453
  }
453
454
  };
454
455
  }
455
- function Ee(e, t, s, r) {
456
- var f;
457
- const a = e.status, n = e.method, o = N(
458
- Object.entries(e.headers || {}).map(([m, g]) => [m.toLowerCase(), g])
459
- ), { ok: c, code: i, data: h, message: u } = ce(
456
+ function ye(e) {
457
+ return e.reduce(
458
+ (t, [s, r]) => (s && (t[s] = r || ""), t),
459
+ {}
460
+ );
461
+ }
462
+ function ve(e, t, s, r) {
463
+ var g;
464
+ const a = e.status, n = e.method, o = ye(
465
+ Object.entries(e.headers || {}).map(([p, m]) => [p.toLowerCase(), m])
466
+ ), { ok: c, code: i, data: d, message: u } = ie(
460
467
  a,
461
468
  e.statusText,
462
469
  e.body,
463
470
  s.get("responseRule"),
464
471
  r == null ? void 0 : r.responseRule
465
472
  );
466
- if (!A(a)) {
467
- const m = me({
473
+ if (!C(a)) {
474
+ const p = pe({
468
475
  url: e.url,
469
476
  method: e.method,
470
477
  status: a,
@@ -474,7 +481,7 @@ function Ee(e, t, s, r) {
474
481
  headers: o,
475
482
  error: e.rawError
476
483
  });
477
- (s.get("errorHandler") || ye)({
484
+ (s.get("errorHandler") || be)({
478
485
  url: t,
479
486
  method: n,
480
487
  status: a,
@@ -483,11 +490,11 @@ function Ee(e, t, s, r) {
483
490
  headers: o,
484
491
  rawError: e.rawError,
485
492
  responseBody: e.body,
486
- ...m
493
+ ...p
487
494
  });
488
495
  }
489
496
  if (a < 0)
490
- return B(
497
+ return P(
491
498
  { ok: !1, status: a, code: e.statusText, headers: {}, message: "", data: null },
492
499
  `${n} ${t} ${e.statusText}`,
493
500
  n,
@@ -495,12 +502,12 @@ function Ee(e, t, s, r) {
495
502
  s,
496
503
  r
497
504
  );
498
- const l = { ok: c, data: h, code: i, message: u, status: a, headers: o };
499
- (f = s.get("responseHandler")) == null || f({ ...l }, n, t);
500
- const d = c ? u : u || e.statusText;
501
- return B(l, d, n, t, s, r);
505
+ const l = { ok: c, data: d, code: i, message: u, status: a, headers: o };
506
+ (g = s.get("responseHandler")) == null || g({ ...l }, n, t);
507
+ const f = c ? u : u || e.statusText;
508
+ return P(l, f, n, t, s, r);
502
509
  }
503
- function B(e, t, s, r, a, n) {
510
+ function P(e, t, s, r, a, n) {
504
511
  const o = a.get("message"), c = o === !1 || (n == null ? void 0 : n.message) === !1 ? !1 : (n == null ? void 0 : n.message) || o;
505
512
  if (c !== !1) {
506
513
  const i = typeof c == "function" ? c(e, s, r, t) : t;
@@ -508,13 +515,13 @@ function B(e, t, s, r, a, n) {
508
515
  }
509
516
  return e;
510
517
  }
511
- function ye(e) {
518
+ function be(e) {
512
519
  const t = {};
513
520
  for (const s in e)
514
521
  s.startsWith("sentry") || (t[s] = e[s]);
515
522
  console.error("RequestError", t);
516
523
  }
517
- async function pe(e, t, s, r, a) {
524
+ async function we(e, t, s, r, a) {
518
525
  const n = a || 0, o = Math.max(0, Math.min(10, (r == null ? void 0 : r.maxRetry) ?? s.get("maxRetry") ?? 0)), c = (r == null ? void 0 : r.retryResolve) ?? s.get("retryResolve"), i = s.get("logHandler") || I;
519
526
  i({
520
527
  type: "prepear",
@@ -526,41 +533,40 @@ async function pe(e, t, s, r, a) {
526
533
  headers: r == null ? void 0 : r.headers,
527
534
  options: r
528
535
  });
529
- const h = Date.now(), u = await e(t, s, r), l = u.status, d = Date.now() - h, f = `[cost ${d}][${l}] ${l < 0 ? u.body : ""}`;
536
+ const d = Date.now(), u = await e(t, s, r), l = u.status, f = Date.now() - d, g = `[cost ${f}][${l}] ${l < 0 ? u.body : ""}`;
530
537
  i({
531
538
  type: "finished",
532
539
  url: t,
533
540
  method: u.method,
534
541
  retry: n,
535
542
  maxRetry: o,
536
- message: n === 0 ? `finish ${f}` : `retry ${n}/${o} finish ${f}`,
543
+ message: n === 0 ? `finish ${g}` : `retry ${n}/${o} finish ${g}`,
537
544
  response: u,
538
545
  headers: u.headers,
539
- cost: d
546
+ cost: f
540
547
  });
541
- const m = A(l);
542
- if (!o || c === "network" && l > 0 || c === "status" && m || Array.isArray(c) && !c.includes(l) || typeof c == "function" && c(u, n) !== !0 || n >= o)
548
+ const p = C(l);
549
+ if (!o || c === "network" && l > 0 || c === "status" && p || Array.isArray(c) && !c.includes(l) || typeof c == "function" && c(u, n) !== !0 || n >= o)
543
550
  return u;
544
- const g = (r == null ? void 0 : r.retryInterval) ?? s.get("retryInterval") ?? 1e3;
545
- return await K(
551
+ const m = (r == null ? void 0 : r.retryInterval) ?? s.get("retryInterval") ?? 1e3;
552
+ return await G(
546
553
  Math.max(
547
554
  100,
548
- g === "2EB" ? Math.pow(2, n) * 1e3 : typeof g == "function" ? g(n + 1) || 0 : g
555
+ m === "2EB" ? Math.pow(2, n) * 1e3 : typeof m == "function" ? m(n + 1) || 0 : m
549
556
  )
550
- ), await pe(e, t, s, r, n + 1);
557
+ ), await we(e, t, s, r, n + 1);
551
558
  }
552
- var be = /* @__PURE__ */ ((e) => (e.Aborted = "Aborted", e.Unknown = "Unknown", e.Timeout = "Timeout", e.NotSupport = "NotSupport", e.URLFormatError = "URLFormatError", e))(be || {});
553
559
  export {
554
- $e as B,
555
- Re as N,
556
- re as R,
557
- O as S,
558
- T as X,
559
- be as a,
560
- Oe as c,
561
- N as f,
562
- ke as g,
563
- Ee as h,
564
- je as j,
565
- pe as r
560
+ Re as H,
561
+ Oe as N,
562
+ $e as O,
563
+ ne as R,
564
+ A as Y,
565
+ H as a,
566
+ ke as c,
567
+ k as e,
568
+ ye as f,
569
+ Ee as g,
570
+ ve as h,
571
+ we as r
566
572
  };
@@ -0,0 +1,2 @@
1
+ "use strict";var I=Object.defineProperty;var J=(e,t,s)=>t in e?I(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var y=(e,t,s)=>J(e,typeof t!="symbol"?t+"":t,s);const h=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},R={wx:"wx"in h&&D(h.wx),fetch:"fetch"in h&&w(h.fetch),window:"window"in h&&D(h.window),Blob:"Blob"in h&&w(h.Blob),FormData:"FormData"in h&&w(h.FormData),TextDecoder:"TextDecoder"in h&&w(h.TextDecoder),AbortController:"AbortController"in h&&w(h.AbortController)};function w(e){return typeof e=="function"}function D(e){return typeof e=="object"&&e!==null}function V(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}function W(){}function z(e){const t=e||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:t,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 Y=/^(?:https?:)?\/\/.+$/i,Z=/^https?:\/\/.+$/i,Q=/^\{[\d\D]*\}$/,X=/^\[[\d\D]*\]$/;function k(e,t=!1){return t?Y.test(e):Z.test(e)}function ee(e){return e==null}function v(e,...t){if(!e||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s!==Object.prototype&&s!==null?!1:t.every(r=>r in e)}function _(e){return Q.test(e)||X.test(e)}function $(e){return e?e[0].toLowerCase()+e.slice(1):""}const B=/_\w*/,H=/-\w*/;function M(e){const t=B.test(e)?e.replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(s,r)=>r.toUpperCase()):H.test(e)?e.replace(/(?:^-*|-*$)/g,"").replace(/-+(\w)/g,(s,r)=>r.toUpperCase()):e;return $(t)}function L(e){return B.test(e)?$(e).replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(t,s)=>"_"+s.toLowerCase()):H.test(e)?$(e.replace(/(?:^-*|-*$)/g,"")).replace(/-+(\w)/g,(t,s)=>"_"+s.toLowerCase()):$(e).replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function T(e,t){try{const s=JSON.parse(e);return t?t(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);function O(e,t=!1){return typeof e=="string"?M(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?O(s):typeof s=="object"&&s?O(s,!0):s):v(e)?Object.keys(e).reduce((s,r)=>{const o=M(String(r)),n=o.charAt(0).toLowerCase()+o.slice(1);return s[n]=t?e[r]:O(e[r]),s},{}):e}function E(e,t=!1){return typeof e=="string"?L(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?E(s):typeof s=="object"&&s?E(s,t):s):v(e)?Object.keys(e).reduce((s,r)=>{const o=L(String(r));return s[o]=t?e[r]:E(e[r]),s},{}):e}async function te(e){return await new Promise(function(t){const s=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("charset","utf-8"),r.onload=function(){s.removeChild(r),t(!0)},r.onerror=function(){s.removeChild(r),t(!1)},r.setAttribute("src",e),s.appendChild(r)})}function se(e,t="数据未能正确识别"){return typeof e=="function"?{guard:e,message:t}:{guard:e.guard,message:e.message||t}}function re(e,t=""){return!t||k(e,!0)?x(e):(x(t)+"/"+e).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function x(e){return k(e,!0)?e.startsWith("http")?e:("location"in globalThis?location.protocol:"https:")+e:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+e.replace(/^\/+/,"")}function ne(e,t){const s={};return(e.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(r){const o=r.split("="),n=o[0],a=decodeURIComponent(o[1]||"");s[n]!==void 0?s[n]+=","+a:s[n]=a}),t!==!0?s[t]||"":s}function oe(e,t){if(t){if(t===!0)return e.replace(/\?[^#]*/,"")}else return e;const s=e.split("#"),r=s[0].split("?"),o=r[0],n=r.length>1?r[1]:"",a=s.length>1?"#"+s[1]:"",c=typeof t=="string"?[t]:Array.isArray(t)?t:[];return!c.length||!n?s[0]+a:(c.map(i=>i.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(o+"?"+n.replace(new RegExp("(?:^|&)(?:"+c.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+a)}function ae(e,t,s=!1){const r=typeof t=="string"?t:Object.keys(t).map(a=>`${a}=${encodeURIComponent(t[a])}`).join("&");if(!r)return e;const o=e.split("#");s&&(o[0]=oe(o[0],(r.match(/([^=&#?]+)=[^&#]+/g)||[]).map(a=>a.replace(/=.+$/,""))));const n=o[0].indexOf("?")+1?"&":"?";return(o[0]+n+r+(o.length>1?"#"+o[1]:"")).replace(/\?&/,"?")}function ce(e){const t=e.match(/(?:\?|&)([^=]+)(?:&|$)/g);return t?t.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class ie{constructor(t=500){y(this,"ttl");y(this,"cache");this.cache={},this.ttl=Math.max(t,0)}getKey(t,s){const r=t.replace(/#.+/,""),o=r.replace(/\?.+/g,""),n=Object.assign(ne(r,!0),s),a=ce(r),c=Object.keys(n).sort().map(i=>`${i}#${n[i]}`);return`${o}_${c.join(",")}_${a.join(",")}`}updateTTL(t){this.ttl=Math.max(t,0)}get(t){if(this.ttl===0)return null;const s=this.cache[t];return s?s.ttl<Date.now()?(delete this.cache[t],null):s.res:null}set(t,s){this.ttl!==0&&(this.cache[t]={ttl:Date.now()+this.ttl,res:s})}}class q{constructor(t){y(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});t&&this.set(t)}set(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!k(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)}get(t){return this.config[t]}getFullUrl(t){return re(t,this.config.baseURL)}showMessage(t,s,r,o){this.config.messageHandler&&s&&this.config.messageHandler(t,s,r,o)}}var C=(e=>(e.UnexpectResponse="UnexpectResponse",e.Aborted="Aborted",e.Unknown="Unknown",e.Timeout="Timeout",e.NotSupport="NotSupport",e.URLFormatError="URLFormatError",e))(C||{});function ue(e,t,s,r){if(t.ok&&!ee(t.data)&&r){const o=se(r,s.get("defaultTypeGuardMessage"));return o.guard(t.data)||(t.code=C.UnexpectResponse,s.showMessage(!0,`${e} ${o.message}`,t.code,t.status),console.error(t.code,e,t.data),t.data=null,t.message=o.message),t}return t}class le{constructor(t,s){y(this,"agent");y(this,"config");y(this,"cache");this.config=new q(s),this.agent=t,this.cache=new ie(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(t,s){try{return await this.agent(t,this.config,s)}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:"Unkonwn",message:String(r),headers:{},data:null}}}async guard(t,s,r){return ue(t,s,this.config,r)}setConfig(t){this.config.set(t),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(t){return this.config.get(t)}async head(t,s){const r=Object.assign({},s||null);return r.method="HEAD",this.guard(t,await this.request(t,r),null)}async get(t,s,r){const o=Object.assign({},r||null);o.method="GET";const n=this.cache.getKey(t,o.params),a=this.cache.get(n);if(a)return this.guard(t,await a,s||null);const c=this.request(t,o);return this.cache.set(n,c),this.guard(t,await c,s||null)}async post(t,s,r,o){const n=Object.assign({},o||null);return n.method="POST",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async del(t,s,r){const o=Object.assign({},r||null);return o.method="DELETE",this.guard(t,await this.request(t,o),s||null)}async put(t,s,r,o){const n=Object.assign({},o||null);return n.method="PUT",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async patch(t,s,r,o){const n=Object.assign({},o||null);return n.method="PATCH",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}}async function he(e,t,s){var m;const r=Object.assign({method:"GET"},s),o=R.FormData?r.body instanceof FormData:!1,n=o&&r.method!=="POST"&&r.method!=="PUT"?"POST":r.method,a=n==="GET"||n==="HEAD"||n==="DELETE";a&&r.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete r.body);const c=Object.assign(o||a?{}:{"Content-Type":R.Blob&&r.body instanceof Blob?r.body.type||"application/octet-stream":"application/json;charset=utf-8"},r.headers),i=r.params||{},d={};Object.keys(i).forEach(b=>{i[b]!==void 0&&(d[b]=de(i[b]))});const u=t.getFullUrl(e),l=fe(r.body),f=r.timeout||t.get("timeout"),g=await async function(){const b=t.get("requestTransformer");if(b)return await b({headers:c,params:d,method:n,url:u,body:l})}(),p=typeof g=="string"&&g?g:u;return(m=t.get("logHandler"))==null||m({type:"ready",url:p,method:n,headers:c,timeout:f,body:l}),{url:p,method:n,body:l,params:d,headers:c,timeout:f,abort:r.abort,credentials:r.credentials||t.get("credentials")}}function de(e){return typeof e=="string"?e:Array.isArray(e)?e.join(","):e+""}function fe(e){if(e)return typeof e=="string"||e instanceof URLSearchParams||e instanceof ArrayBuffer||R.Blob&&e instanceof Blob||R.FormData&&e instanceof FormData?e:JSON.stringify(e)}const N="data",j="message";function ge(e,t,s,r,o){const n=o||r;return U(e)?je(n.ok||r.ok,e,t,s):pe(n.failed||r.failed,t,s)}const me=function(e){const t=[],s=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(s.messageField||j)+" 作为错误消息");break}const r=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),r.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(r.dataField||N)+" 作为响应数据,读取 "+(r.messageField||j)+" 作为提示消息"),r.statusField&&t.push(" 当 "+r.statusField+" 为 "+(r.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),r.ignoreMessage&&t.push(" 并忽略以下消息:"+r.ignoreMessage);break}return t.join(`
2
+ `)};function pe(e,t,s){const r=e||{resolve:"json",messageField:j},o={ok:!1,code:t,message:s,data:null};switch(r.resolve){case"body":o.message=P(s)||s;break;case"json":const{code:n,message:a}=ye(s,r.converter,r.statusField,r.messageField);o.code=n||t,o.message=P(s)||a;break}return o}function ye(e,t,s,r=j){if(!_(e))return{message:""};const o=A(T(e),t);return!o||!v(o)?{message:e}:{code:s?F(o,s):"",message:F(o,r)||e}}function F(e,t){const s=Array.isArray(t)?t:[t];for(const r of s)if(r in e)return be(e[r]);return""}function be(e){return e?typeof e=="string"?e:JSON.stringify(e):""}const we=/<title>([^<]+)<\/title>/i,Re=/<message>([^<]+)<\/message>/i;function P(e){const t=e.match(we);if(t)return t[1];const s=e.match(Re);return s?s[1]:""}function je(e,t,s,r){const o=e||{resolve:"body"},n={ok:!0,code:s,message:"",data:null};if(t===204||!r)return n;if(o.resolve==="body")return n.data=_(r)?A(T(r),e.converter):r,n;const a=A(T(r),e.converter);if(!a||!v(a))return n.ok=!1,n.code="ResponseFormatError",n.message="响应内容无法格式化为 Object",n;const c=o.statusField,i=o.statusOKValue||"",d=o.dataField||N,u=o.messageField||j,l=o.ignoreMessage||"";if(c&&!(c in a))return n.ok=!1,n.code="ResponseFieldMissing",n.message="响应内容找不到状态字段 "+c,n;const f=c?a[c]+"":"";return n.ok=c?f===i:!0,n.code=f||s,n.data=d===!0?a:d in a?a[d]:null,n.message=F(a,u),l&&n.message&&(Array.isArray(l)&&l.includes(n.message)||typeof l=="string"&&n.message===l)&&(n.message=""),n}function U(e){return e>=200&&e<400}function A(e,t){return t==="camelize"?O(e):t==="snakify"?E(e):e}const $e=z("APIError");function Oe(e){const t={};for(const o in e.headers)(o.startsWith("x-")||o.includes("trace")||o.includes("server")||/\b(?:id|uuid)\b/.test(o))&&(t[o]=e.headers[o]);const s=e.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),r=e.status<0?"unknown":e.status;return{sentryError:new $e(`${s} | ${r}${e.code?` | ${e.code}`:""}`),sentryTags:{...t,status:r,method:e.method,code:e.code||"unknown",message:e.message||"empty"},sentryExtra:{url:e.url,responseBody:e.body||"empty",responseHeaders:e.headers,rawError:e.error}}}function K(e){return e.reduce((t,[s,r])=>(s&&(t[s]=r||""),t),{})}function Ee(e,t,s,r){var g;const o=e.status,n=e.method,a=K(Object.entries(e.headers||{}).map(([p,m])=>[p.toLowerCase(),m])),{ok:c,code:i,data:d,message:u}=ge(o,e.statusText,e.body,s.get("responseRule"),r==null?void 0:r.responseRule);if(!U(o)){const p=Oe({url:e.url,method:e.method,status:o,code:i,message:u,body:e.body,headers:a,error:e.rawError});(s.get("errorHandler")||ke)({url:t,method:n,status:o,code:i,message:u,headers:a,rawError:e.rawError,responseBody:e.body,...p})}if(o<0)return S({ok:!1,status:o,code:e.statusText,headers:{},message:"",data:null},`${n} ${t} ${e.statusText}`,n,t,s,r);const l={ok:c,data:d,code:i,message:u,status:o,headers:a};(g=s.get("responseHandler"))==null||g({...l},n,t);const f=c?u:u||e.statusText;return S(l,f,n,t,s,r)}function S(e,t,s,r,o,n){const a=o.get("message"),c=a===!1||(n==null?void 0:n.message)===!1?!1:(n==null?void 0:n.message)||a;if(c!==!1){const i=typeof c=="function"?c(e,s,r,t):t;i instanceof Error?o.showMessage(!0,i.message,e.code,e.status):i&&typeof i=="object"&&"message"in i?o.showMessage(!1,i.message,e.code,e.status):o.showMessage(!e.ok,i,e.code,e.status)}return e}function ke(e){const t={};for(const s in e)s.startsWith("sentry")||(t[s]=e[s]);console.error("RequestError",t)}async function G(e,t,s,r,o){const n=o||0,a=Math.max(0,Math.min(10,(r==null?void 0:r.maxRetry)??s.get("maxRetry")??0)),c=(r==null?void 0:r.retryResolve)??s.get("retryResolve"),i=s.get("logHandler")||W;i({type:"prepear",url:t,method:(r==null?void 0:r.method)||"GET",retry:n,maxRetry:a,message:n===0?"start":`retry ${n}/${a} start`,headers:r==null?void 0:r.headers,options:r});const d=Date.now(),u=await e(t,s,r),l=u.status,f=Date.now()-d,g=`[cost ${f}][${l}] ${l<0?u.body:""}`;i({type:"finished",url:t,method:u.method,retry:n,maxRetry:a,message:n===0?`finish ${g}`:`retry ${n}/${a} finish ${g}`,response:u,headers:u.headers,cost:f});const p=U(l);if(!a||c==="network"&&l>0||c==="status"&&p||Array.isArray(c)&&!c.includes(l)||typeof c=="function"&&c(u,n)!==!0||n>=a)return u;const m=(r==null?void 0:r.retryInterval)??s.get("retryInterval")??1e3;return await V(Math.max(100,m==="2EB"?Math.pow(2,n)*1e3:typeof m=="function"?m(n+1)||0:m)),await G(e,t,s,r,n+1)}exports.Ht=ae;exports.NetRequestHandler=le;exports.Oe=te;exports.RequestGlobalConfig=q;exports.RequestInteralError=C;exports.Y=k;exports.convertOptions=he;exports.ee=R;exports.fromEntries=K;exports.getResponseRulesDescription=me;exports.handleResponse=Ee;exports.retryRequest=G;
package/dist/wx.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./type-CzbYPhI4.cjs"),l=async function(t,r,n){return e.handleResponse(await e.retryRequest(p,t,r,n),t,r,n)},p=async function(t,r,n){const s=await e.convertOptions(t,r,n),u=s.method==="PATCH"?"POST":s.method,a=e.Bt(s.url,s.params);return e.Support.wx?new Promise(d=>{wx.request({url:a,data:s.body,header:s.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:e.RequestInteralError.Unknown,body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:s.method==="HEAD"?"":f(c.data)})}})}):{url:a,method:u,status:-1,statusText:e.RequestInteralError.NotSupport,body:""}};function f(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.Support.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(l,t)}const o=i(),y=o.setConfig,g=o.head,h=o.get,q=o.post,x=o.del,R=o.put;exports.NetRequest=i;exports.del=x;exports.get=h;exports.head=g;exports.post=q;exports.put=R;exports.setGlobalConfig=y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-CRrgnQtP.cjs"),l=async function(e,r,n){return t.handleResponse(await t.retryRequest(f,e,r,n),e,r,n)},f=async function(e,r,n){const s=await t.convertOptions(e,r,n),u=s.method==="PATCH"?"POST":s.method,a=t.Ht(s.url,s.params);return t.ee.wx?new Promise(d=>{wx.request({url:a,data:s.body,header:s.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:t.RequestInteralError.Unknown,body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:s.method==="HEAD"?"":p(c.data)})}})}):{url:a,method:u,status:-1,statusText:t.RequestInteralError.NotSupport,body:""}};function p(e){return typeof e=="string"?e:e instanceof ArrayBuffer&&t.ee.TextDecoder?new TextDecoder().decode(e):JSON.stringify(e)}function i(e){return new t.NetRequestHandler(l,e)}const o=i(),y=o.setConfig,g=o.head,h=o.get,q=o.post,x=o.del,R=o.put;exports.NetRequest=i;exports.del=x;exports.get=h;exports.head=g;exports.post=q;exports.put=R;exports.setGlobalConfig=y;
package/dist/wx.js CHANGED
@@ -1,6 +1,6 @@
1
- import { h as p, r as f, c as l, B as h, S as i, a as d, N as y } from "./type-4NUOpogE.js";
1
+ import { h as f, r as p, c as l, H as h, e as i, a as d, N as y } from "./retry-8Z8eLh90.js";
2
2
  const x = async function(t, o, n) {
3
- return p(await f(m, t, o, n), t, o, n);
3
+ return f(await p(m, t, o, n), t, o, n);
4
4
  }, m = async function(t, o, n) {
5
5
  const e = await l(t, o, n), r = e.method === "PATCH" ? "POST" : e.method, a = h(e.url, e.params);
6
6
  return i.wx ? new Promise((c) => {
@@ -45,13 +45,13 @@ function w(t) {
45
45
  function T(t) {
46
46
  return new y(x, t);
47
47
  }
48
- const s = T(), q = s.setConfig, R = s.head, b = s.get, S = s.post, C = s.del, N = s.put;
48
+ const s = T(), q = s.setConfig, R = s.head, b = s.get, C = s.post, H = s.del, N = s.put;
49
49
  export {
50
50
  T as NetRequest,
51
- C as del,
51
+ H as del,
52
52
  b as get,
53
53
  R as head,
54
- S as post,
54
+ C as post,
55
55
  N as put,
56
56
  q as setGlobalConfig
57
57
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "2.0.9",
3
+ "version": "2.1.0",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "source": "./src/index.ts",
@@ -59,7 +59,7 @@
59
59
  "happy-dom": "^12.10.3",
60
60
  "msw": "^2.7.0",
61
61
  "vitest": "^3.0.5",
62
- "@seayoo-web/utils": "^2.1.0"
62
+ "@seayoo-web/utils": "^3.0.4"
63
63
  },
64
64
  "scripts": {
65
65
  "build": "vite build && tsc --emitDeclarationOnly",
@@ -4,7 +4,7 @@ export declare class RequestGlobalConfig {
4
4
  private config;
5
5
  constructor(config?: IRequestGlobalConfig);
6
6
  set(config: Partial<IRequestGlobalConfig>): void;
7
- get<T extends keyof IRequestGlobalConfig>(key: T): SomeRequired<IRequestGlobalConfig, "timeout" | "credentials" | "baseURL" | "maxRetry" | "cacheTTL" | "responseRule" | "retryInterval" | "retryResolve">[T];
7
+ get<T extends keyof IRequestGlobalConfig>(key: T): SomeRequired<IRequestGlobalConfig, "timeout" | "credentials" | "baseURL" | "maxRetry" | "cacheTTL" | "responseRule" | "retryInterval" | "retryResolve" | "defaultTypeGuardMessage">[T];
8
8
  /** 基于 baseURL 返回完整的 url 地址 */
9
9
  getFullUrl(url: string): string;
10
10
  /** 提示消息 */
@@ -1,3 +1,3 @@
1
+ import { type IResponseResult, type TypeGuardParam } from "./type";
1
2
  import type { RequestGlobalConfig } from "./config";
2
- import type { IResponseResult, TypeGuardParam } from "./type";
3
3
  export declare function checkTypedDataResult<T>(url: string, result: IResponseResult, config: RequestGlobalConfig, typeGard: TypeGuardParam<T> | null): IResponseResult<T | null | unknown>;
@@ -21,7 +21,7 @@ export declare class NetRequestHandler {
21
21
  /**
22
22
  * 读取默认的请求配置
23
23
  */
24
- getConfig<T extends keyof IRequestGlobalConfig>(key: T): import("@seayoo-web/utils").SomeRequired<IRequestGlobalConfig, "timeout" | "credentials" | "baseURL" | "maxRetry" | "cacheTTL" | "responseRule" | "retryInterval" | "retryResolve">[T];
24
+ getConfig<T extends keyof IRequestGlobalConfig>(key: T): import("@seayoo-web/utils").SomeRequired<IRequestGlobalConfig, "timeout" | "credentials" | "baseURL" | "maxRetry" | "cacheTTL" | "responseRule" | "retryInterval" | "retryResolve" | "defaultTypeGuardMessage">[T];
25
25
  /**
26
26
  * 发送一个 HEAD 请求,并且不处理响应 body
27
27
  */
@@ -2,6 +2,8 @@ import type { RequestGlobalConfig } from "./config";
2
2
  import type { MaybePromise, TypeGuard, TypeGuardFn } from "@seayoo-web/utils";
3
3
  export type IBaseRequestBody = Blob | ArrayBuffer | FormData | URLSearchParams | string;
4
4
  export declare const enum RequestInteralError {
5
+ /** 响应数据校验失败 */
6
+ UnexpectResponse = "UnexpectResponse",
5
7
  /** 请求被取消 */
6
8
  Aborted = "Aborted",
7
9
  /** 未知错误,通常是网络错误 */
@@ -83,6 +85,8 @@ export type IRequestGlobalConfig = {
83
85
  baseURL?: string;
84
86
  /** 用于 get 请求的缓存时长,单位 ms,建议不小于 100 */
85
87
  cacheTTL?: number;
88
+ /** 接口响应错误时的默认提示消息 */
89
+ defaultTypeGuardMessage?: string;
86
90
  /**
87
91
  * 全局 request 转化函数,headers 和 params 为引用型数据可直接修改,如果返回字符串,则替换原来的 url 进行请求
88
92
  */
@@ -0,0 +1,4 @@
1
+ /**
2
+ * 简版 Object.fromEntries 以处理某些低版本浏览器和 webview 的问题
3
+ */
4
+ export declare function fromEntries(kv: [string, string | undefined][]): Record<string, string>;
@@ -1 +0,0 @@
1
- "use strict";const s=require("./type-CzbYPhI4.cjs"),f=async function(a,n,i){return s.handleResponse(await s.retryRequest(w,a,n,i),a,n,i)},w=async function(a,n,i){const t=await s.convertOptions(a,n,i),o=new URL(t.url),u=t.params;u instanceof Object&&Object.keys(u).forEach(e=>o.searchParams.set(e,u[e]));const r=s.Support.AbortController?new AbortController:null;function c(){r&&!r.signal.aborted&&r.abort()}t.abort&&t.abort.addEventListener("abort",c);const h=t.timeout>0?setTimeout(c,t.timeout):null,b=t.method==="HEAD";return await fetch(o,{method:t.method,headers:Object.keys(t.headers).length>0?new Headers(t.headers):void 0,body:t.body,credentials:t.credentials,signal:r==null?void 0:r.signal,redirect:"follow"}).then(async e=>{const d=b?"":await e.text().catch(m=>m),l=s.fromEntries([...e.headers.entries()]);return d instanceof Error?{url:o.toString(),method:t.method,status:e.status,statusText:e.statusText||s.RequestInteralError.Unknown,body:"",headers:l,rawError:d}:{url:o.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:l,body:d}}).catch(e=>({url:o.toString(),method:t.method,status:-1,statusText:r!=null&&r.signal.aborted?s.RequestInteralError.Aborted:s.RequestInteralError.Unknown,body:"",rawError:e})).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",c)})};exports.fetchRequest=f;
@@ -1,2 +0,0 @@
1
- "use strict";var K=Object.defineProperty;var G=(e,t,s)=>t in e?K(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var p=(e,t,s)=>G(e,typeof t!="symbol"?t+"":t,s);const y=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},w={fetch:"fetch"in y,window:"window"in y,FormData:"FormData"in y,Blob:"Blob"in y,wx:"wx"in y,TextDecoder:"TextDecoder"in y,AbortController:"AbortController"in y};function S(e){return e.reduce((t,[s,r])=>(s&&(t[s]=r||""),t),{})}function J(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}function V(){}function W(e){const t=e||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:t,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 X=/^(?:https?:)?\/\/.+$/i,z=/^https?:\/\/.+$/i,Z=/^\{[\d\D]*\}$/,Q=/^\[[\d\D]*\]$/;function O(e,t=!1){return t?X.test(e):z.test(e)}function Y(e){return e==null}function k(e,...t){if(!e||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s!==Object.prototype&&s!==null?!1:t.every(r=>r in e)}function P(e){return Z.test(e)||Q.test(e)}function R(e){return e?e[0].toLowerCase()+e.slice(1):""}const _=/_\w*/,x=/-\w*/;function A(e){const t=_.test(e)?e.replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(s,r)=>r.toUpperCase()):x.test(e)?e.replace(/(?:^-*|-*$)/g,"").replace(/-+(\w)/g,(s,r)=>r.toUpperCase()):e;return R(t)}function U(e){return _.test(e)?R(e).replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(t,s)=>"_"+s.toLowerCase()):x.test(e)?R(e.replace(/(?:^-*|-*$)/g,"")).replace(/-+(\w)/g,(t,s)=>"_"+s.toLowerCase()):R(e).replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function v(e,t){try{const s=JSON.parse(e);return t?t(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);function $(e,t=!1){return typeof e=="string"?A(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?$(s):typeof s=="object"&&s?$(s,!0):s):k(e)?Object.keys(e).reduce((s,r)=>{const a=A(String(r)),n=a.charAt(0).toLowerCase()+a.slice(1);return s[n]=t?e[r]:$(e[r]),s},{}):e}function E(e,t=!1){return typeof e=="string"?U(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?E(s):typeof s=="object"&&s?E(s,t):s):k(e)?Object.keys(e).reduce((s,r)=>{const a=U(String(r));return s[a]=t?e[r]:E(e[r]),s},{}):e}async function ee(e){return await new Promise(function(t){const s=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("charset","utf-8"),r.onload=function(){s.removeChild(r),t(!0)},r.onerror=function(){s.removeChild(r),t(!1)},r.setAttribute("src",e),s.appendChild(r)})}function te(e,t="数据未能正确识别"){return typeof e=="function"?{guard:e,message:t}:{guard:e.guard,message:e.message||t}}function se(e,t=""){return!t||O(e,!0)?L(e):(L(t)+"/"+e).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function L(e){return O(e,!0)?e.startsWith("http")?e:("location"in globalThis?location.protocol:"https:")+e:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+e.replace(/^\/+/,"")}function re(e,t){const s={};return(e.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(r){const a=r.split("="),n=a[0],o=decodeURIComponent(a[1]||"");s[n]!==void 0?s[n]+=","+o:s[n]=o}),t!==!0?s[t]||"":s}function ne(e,t){if(t){if(t===!0)return e.replace(/\?[^#]*/,"")}else return e;const s=e.split("#"),r=s[0].split("?"),a=r[0],n=r.length>1?r[1]:"",o=s.length>1?"#"+s[1]:"",c=typeof t=="string"?[t]:Array.isArray(t)?t:[];return!c.length||!n?s[0]+o:(c.map(i=>i.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(a+"?"+n.replace(new RegExp("(?:^|&)(?:"+c.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function ae(e,t,s=!1){const r=typeof t=="string"?t:Object.keys(t).map(o=>`${o}=${encodeURIComponent(t[o])}`).join("&");if(!r)return e;const a=e.split("#");s&&(a[0]=ne(a[0],(r.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const n=a[0].indexOf("?")+1?"&":"?";return(a[0]+n+r+(a.length>1?"#"+a[1]:"")).replace(/\?&/,"?")}function oe(e){const t=e.match(/(?:\?|&)([^=]+)(?:&|$)/g);return t?t.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class ce{constructor(t=500){p(this,"ttl");p(this,"cache");this.cache={},this.ttl=Math.max(t,0)}getKey(t,s){const r=t.replace(/#.+/,""),a=r.replace(/\?.+/g,""),n=Object.assign(re(r,!0),s),o=oe(r),c=Object.keys(n).sort().map(i=>`${i}#${n[i]}`);return`${a}_${c.join(",")}_${o.join(",")}`}updateTTL(t){this.ttl=Math.max(t,0)}get(t){if(this.ttl===0)return null;const s=this.cache[t];return s?s.ttl<Date.now()?(delete this.cache[t],null):s.res:null}set(t,s){this.ttl!==0&&(this.cache[t]={ttl:Date.now()+this.ttl,res:s})}}class q{constructor(t){p(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});t&&this.set(t)}set(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!O(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)}get(t){return this.config[t]}getFullUrl(t){return se(t,this.config.baseURL)}showMessage(t,s,r,a){this.config.messageHandler&&s&&this.config.messageHandler(t,s,r,a)}}const D="UnexpectResponse";function ie(e,t,s,r){if(t.ok&&!Y(t.data)&&r){const a=te(r,"响应数据未能正确识别");return a.guard(t.data)||(s.showMessage(!0,`${e} ${a.message}`,t.code,t.status),console.error(D,e,t.data),t.data=null,t.code=D,t.message=a.message),t}return t}class ue{constructor(t,s){p(this,"agent");p(this,"config");p(this,"cache");this.config=new q(s),this.agent=t,this.cache=new ce(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(t,s){try{return await this.agent(t,this.config,s)}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:"Unkonwn",message:String(r),headers:{},data:null}}}async guard(t,s,r){return ie(t,s,this.config,r)}setConfig(t){this.config.set(t),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(t){return this.config.get(t)}async head(t,s){const r=Object.assign({},s||null);return r.method="HEAD",this.guard(t,await this.request(t,r),null)}async get(t,s,r){const a=Object.assign({},r||null);a.method="GET";const n=this.cache.getKey(t,a.params),o=this.cache.get(n);if(o)return this.guard(t,await o,s||null);const c=this.request(t,a);return this.cache.set(n,c),this.guard(t,await c,s||null)}async post(t,s,r,a){const n=Object.assign({},a||null);return n.method="POST",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async del(t,s,r){const a=Object.assign({},r||null);return a.method="DELETE",this.guard(t,await this.request(t,a),s||null)}async put(t,s,r,a){const n=Object.assign({},a||null);return n.method="PUT",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async patch(t,s,r,a){const n=Object.assign({},a||null);return n.method="PATCH",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}}async function le(e,t,s){var g;const r=Object.assign({method:"GET"},s),a=w.FormData?r.body instanceof FormData:!1,n=a&&r.method!=="POST"&&r.method!=="PUT"?"POST":r.method,o=n==="GET"||n==="HEAD"||n==="DELETE";o&&r.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete r.body);const c=Object.assign(a||o?{}:{"Content-Type":w.Blob&&r.body instanceof Blob?r.body.type||"application/octet-stream":"application/json;charset=utf-8"},r.headers),i=r.params||{},h={};Object.keys(i).forEach(b=>{i[b]!==void 0&&(h[b]=he(i[b]))});const u=t.getFullUrl(e),l=de(r.body),d=r.timeout||t.get("timeout"),f=await async function(){const b=t.get("requestTransformer");if(b)return await b({headers:c,params:h,method:n,url:u,body:l})}(),m=typeof f=="string"&&f?f:u;return(g=t.get("logHandler"))==null||g({type:"ready",url:m,method:n,headers:c,timeout:d,body:l}),{url:m,method:n,body:l,params:h,headers:c,timeout:d,abort:r.abort,credentials:r.credentials||t.get("credentials")}}function he(e){return typeof e=="string"?e:Array.isArray(e)?e.join(","):e+""}function de(e){if(e)return typeof e=="string"||e instanceof URLSearchParams||e instanceof ArrayBuffer||w.Blob&&e instanceof Blob||w.FormData&&e instanceof FormData?e:JSON.stringify(e)}const H="data",j="message";function fe(e,t,s,r,a){const n=a||r;return T(e)?je(n.ok||r.ok,e,t,s):me(n.failed||r.failed,t,s)}const ge=function(e){const t=[],s=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(s.messageField||j)+" 作为错误消息");break}const r=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),r.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(r.dataField||H)+" 作为响应数据,读取 "+(r.messageField||j)+" 作为提示消息"),r.statusField&&t.push(" 当 "+r.statusField+" 为 "+(r.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),r.ignoreMessage&&t.push(" 并忽略以下消息:"+r.ignoreMessage);break}return t.join(`
2
- `)};function me(e,t,s){const r=e||{resolve:"json",messageField:j},a={ok:!1,code:t,message:s,data:null};switch(r.resolve){case"body":a.message=M(s)||s;break;case"json":const{code:n,message:o}=pe(s,r.converter,r.statusField,r.messageField);a.code=n||t,a.message=M(s)||o;break}return a}function pe(e,t,s,r=j){if(!P(e))return{message:""};const a=C(v(e),t);return!a||!k(a)?{message:e}:{code:s?F(a,s):"",message:F(a,r)||e}}function F(e,t){const s=Array.isArray(t)?t:[t];for(const r of s)if(r in e)return ye(e[r]);return""}function ye(e){return e?typeof e=="string"?e:JSON.stringify(e):""}const be=/<title>([^<]+)<\/title>/i,we=/<message>([^<]+)<\/message>/i;function M(e){const t=e.match(be);if(t)return t[1];const s=e.match(we);return s?s[1]:""}function je(e,t,s,r){const a=e||{resolve:"body"},n={ok:!0,code:s,message:"",data:null};if(t===204||!r)return n;if(a.resolve==="body")return n.data=P(r)?C(v(r),e.converter):r,n;const o=C(v(r),e.converter);if(!o||!k(o))return n.ok=!1,n.code="ResponseFormatError",n.message="响应内容无法格式化为 Object",n;const c=a.statusField,i=a.statusOKValue||"",h=a.dataField||H,u=a.messageField||j,l=a.ignoreMessage||"";if(c&&!(c in o))return n.ok=!1,n.code="ResponseFieldMissing",n.message="响应内容找不到状态字段 "+c,n;const d=c?o[c]+"":"";return n.ok=c?d===i:!0,n.code=d||s,n.data=h===!0?o:h in o?o[h]:null,n.message=F(o,u),l&&n.message&&(Array.isArray(l)&&l.includes(n.message)||typeof l=="string"&&n.message===l)&&(n.message=""),n}function T(e){return e>=200&&e<400}function C(e,t){return t==="camelize"?$(e):t==="snakify"?E(e):e}const Re=W("APIError");function $e(e){const t={};for(const a in e.headers)(a.startsWith("x-")||a.includes("trace")||a.includes("server")||/\b(?:id|uuid)\b/.test(a))&&(t[a]=e.headers[a]);const s=e.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),r=e.status<0?"unknown":e.status;return{sentryError:new Re(`${s} | ${r}${e.code?` | ${e.code}`:""}`),sentryTags:{...t,status:r,method:e.method,code:e.code||"unknown",message:e.message||"empty"},sentryExtra:{url:e.url,responseBody:e.body||"empty",responseHeaders:e.headers,rawError:e.error}}}function Ee(e,t,s,r){var f;const a=e.status,n=e.method,o=S(Object.entries(e.headers||{}).map(([m,g])=>[m.toLowerCase(),g])),{ok:c,code:i,data:h,message:u}=fe(a,e.statusText,e.body,s.get("responseRule"),r==null?void 0:r.responseRule);if(!T(a)){const m=$e({url:e.url,method:e.method,status:a,code:i,message:u,body:e.body,headers:o,error:e.rawError});(s.get("errorHandler")||Oe)({url:t,method:n,status:a,code:i,message:u,headers:o,rawError:e.rawError,responseBody:e.body,...m})}if(a<0)return B({ok:!1,status:a,code:e.statusText,headers:{},message:"",data:null},`${n} ${t} ${e.statusText}`,n,t,s,r);const l={ok:c,data:h,code:i,message:u,status:a,headers:o};(f=s.get("responseHandler"))==null||f({...l},n,t);const d=c?u:u||e.statusText;return B(l,d,n,t,s,r)}function B(e,t,s,r,a,n){const o=a.get("message"),c=o===!1||(n==null?void 0:n.message)===!1?!1:(n==null?void 0:n.message)||o;if(c!==!1){const i=typeof c=="function"?c(e,s,r,t):t;i instanceof Error?a.showMessage(!0,i.message,e.code,e.status):i&&typeof i=="object"&&"message"in i?a.showMessage(!1,i.message,e.code,e.status):a.showMessage(!e.ok,i,e.code,e.status)}return e}function Oe(e){const t={};for(const s in e)s.startsWith("sentry")||(t[s]=e[s]);console.error("RequestError",t)}async function N(e,t,s,r,a){const n=a||0,o=Math.max(0,Math.min(10,(r==null?void 0:r.maxRetry)??s.get("maxRetry")??0)),c=(r==null?void 0:r.retryResolve)??s.get("retryResolve"),i=s.get("logHandler")||V;i({type:"prepear",url:t,method:(r==null?void 0:r.method)||"GET",retry:n,maxRetry:o,message:n===0?"start":`retry ${n}/${o} start`,headers:r==null?void 0:r.headers,options:r});const h=Date.now(),u=await e(t,s,r),l=u.status,d=Date.now()-h,f=`[cost ${d}][${l}] ${l<0?u.body:""}`;i({type:"finished",url:t,method:u.method,retry:n,maxRetry:o,message:n===0?`finish ${f}`:`retry ${n}/${o} finish ${f}`,response:u,headers:u.headers,cost:d});const m=T(l);if(!o||c==="network"&&l>0||c==="status"&&m||Array.isArray(c)&&!c.includes(l)||typeof c=="function"&&c(u,n)!==!0||n>=o)return u;const g=(r==null?void 0:r.retryInterval)??s.get("retryInterval")??1e3;return await J(Math.max(100,g==="2EB"?Math.pow(2,n)*1e3:typeof g=="function"?g(n+1)||0:g)),await N(e,t,s,r,n+1)}var I=(e=>(e.Aborted="Aborted",e.Unknown="Unknown",e.Timeout="Timeout",e.NotSupport="NotSupport",e.URLFormatError="URLFormatError",e))(I||{});exports.Bt=ae;exports.NetRequestHandler=ue;exports.RequestGlobalConfig=q;exports.RequestInteralError=I;exports.Support=w;exports.X=O;exports.convertOptions=le;exports.fromEntries=S;exports.getResponseRulesDescription=ge;exports.handleResponse=Ee;exports.je=ee;exports.retryRequest=N;
@@ -1,13 +0,0 @@
1
- export declare const Support: {
2
- fetch: boolean;
3
- window: boolean;
4
- FormData: boolean;
5
- Blob: boolean;
6
- wx: boolean;
7
- TextDecoder: boolean;
8
- AbortController: boolean;
9
- };
10
- /**
11
- * 简版 Object.fromEntries 以处理某些低版本浏览器和 webview 的问题
12
- */
13
- export declare function fromEntries(kv: [string, string | undefined][]): Record<string, string>;
@@ -1 +0,0 @@
1
- export declare const version = "2.0.7";