@seayoo-web/request 1.6.2 → 1.6.4

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.
@@ -7,3 +7,7 @@ export declare const Support: {
7
7
  TextDecoder: boolean;
8
8
  AbortController: boolean;
9
9
  };
10
+ /**
11
+ * 简版 Object.fromEntries 以处理某些低版本浏览器和 webview 的问题
12
+ */
13
+ export declare function fromEntries(kv: [string, string | undefined][]): Record<string, string>;
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./version-D6D6EXmg.cjs"),E=async function(n,s,t){const e=await c.convertOptions(n,s,t),r=new URL(e.url),i=e.params;i instanceof Object&&Object.keys(i).forEach(a=>r.searchParams.set(a,i[a]));const o=c.Support.AbortController?new AbortController:null;function l(){o&&!o.signal.aborted&&o.abort()}e.abort&&e.abort.addEventListener("abort",l);const b=e.timeout>0?setTimeout(l,e.timeout):null,h=new Request(r,{method:e.method,headers:new Headers(e.headers),body:e.body,credentials:e.credentials,signal:o==null?void 0:o.signal,redirect:"follow"});return await fetch(h).then(async a=>({url:r.toString(),method:e.method,status:a.status,statusText:a.statusText,headers:Object.fromEntries(a.headers.entries()),body:e.method==="HEAD"?"":await a.text()})).catch(a=>({url:r.toString(),method:e.method,status:-1,statusText:o!=null&&o.signal.aborted?"Aborted":"NetworkError",body:String(a)})).finally(()=>{b!==null&&clearTimeout(b),e.abort&&e.abort.removeEventListener("abort",l)})},m=async function(n,s,t){const e={...await c.convertOptions(n,s,t),onUploadProgress:t==null?void 0:t.onUploadProgress},r=e.method,i=e.onUploadProgress||c.Wt,o=c.Et(e.url,e.params);return await new Promise(l=>{let b=1;function h(w){b=w.total,i({total:w.total,loaded:w.loaded})}let a=null,f=!1;const g=function(){f||(d.abort(),f=!0)};function p(){a!==null&&clearTimeout(a),e.abort&&e.abort.removeEventListener("abort",g)}const d=new XMLHttpRequest;d.open(r,o,!0),d.upload.addEventListener("progress",h),d.addEventListener("load",()=>{p(),i({loaded:b,total:b}),l({url:o,method:r,status:d.status,statusText:d.statusText,headers:T(d),body:r==="HEAD"?"":d.responseText})}),d.addEventListener("error",()=>{p(),l({url:o,method:r,status:-1,statusText:"Failed",body:""})}),d.addEventListener("abort",()=>{p(),l({url:o,method:r,status:-1,statusText:"Aborted",body:""})}),Object.entries(e.headers).forEach(([w,R])=>{d.setRequestHeader(w,R)}),e.credentials==="include"&&(d.withCredentials=!0),d.send(e.body||void 0),e.abort&&e.abort.addEventListener("abort",g),e.timeout>0&&(a=setTimeout(g,e.timeout))})};function T(n){const s={};if(!n)return s;const t=n.getAllResponseHeaders();return t&&t!=="null"&&t.replace(/\r/g,"").split(`
2
- `).forEach(e=>{const r=e.trim();if(!r)return;const i=r.split(":"),o=i[0].trim();o&&(s[o]=(i[1]||"").trim())}),s}const q=async function(n,s,t){return c.handleResponse(await c.retryRequest(E,n,s,t),n,s,t)},H=async function(n,s,t){return c.handleResponse(await c.retryRequest(m,n,s,t),n,s,t)};async function S(n,s,t,e){const r=t==null?void 0:t.body,i=(t==null?void 0:t.method)==="PUT"?"PUT":"POST";if(s instanceof Blob){const a=new c.RequestGlobalConfig(e),f=await m(n,a,{...t,method:i,body:s});return c.handleResponse(f,n,a,t)}const o=new FormData,l={...s};r instanceof Object&&Object.entries(r).forEach(([a,f])=>{f instanceof Blob?l[a]=f:Array.isArray(f)?f.forEach((g,p)=>{o.append(`${a}[${p}]`,String(g))}):o.append(a,String(f))});for(const a in l)o.append(a,l[a]);const b=new c.RequestGlobalConfig(e),h=await m(n,b,{...t,method:i,body:o});return c.handleResponse(h,n,b,t)}async function x(n,s,t={}){const e=window;"callback"in t||(t.callback="jsonxData"+Math.random().toString(16).slice(2));const r=t.callback+"";if(!n)return null;const i=c.Et(n,t,!0);return new Promise(o=>{e[r]=function(l){if(r in window&&delete e[r],s(l))return l;console.warn("response type check faild",n,l),o(null)},c.he(i).catch(function(){o(null),delete e[r]})})}async function v(n,s,t={}){const e=window;return"var"in t||(t.var="jsonxData"+Math.random().toString(16).slice(2)),n?await c.he(c.Et(n,t,!0)).then(()=>{const r=e[t.var+""];return s(r)?r:(console.warn("response type check faild",n,r),null)}).catch(()=>null):null}const C=async function(n,s,t){return await S(n,s,t,{baseURL:u.getConfig("baseURL"),logHandler:u.getConfig("logHandler"),errorHandler:u.getConfig("errorHandler"),requestTransformer:u.getConfig("requestTransformer"),messageHandler:u.getConfig("messageHandler"),responseHandler:u.getConfig("responseHandler")})};function y(n){if(!c.Support.window)throw new Error("Default Module Only Support In Browser");return c.Support.fetch?new c.NetRequestHandler(q,n):new c.NetRequestHandler(H,n)}const u=y(),j=u.setConfig,L=u.head,U=u.get,O=u.post,P=u.del,A=u.put,D=u.patch;exports.getResponseRulesDescription=c.getResponseRulesDescription;exports.version=c.version;exports.NetRequest=y;exports.del=P;exports.get=U;exports.head=L;exports.jsonp=x;exports.jsonx=v;exports.patch=D;exports.post=O;exports.put=A;exports.setGlobalConfig=j;exports.upload=C;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./version-DUfwEwFz.cjs"),E=async function(n,a,t){const e=await s.convertOptions(n,a,t),r=new URL(e.url),i=e.params;i instanceof Object&&Object.keys(i).forEach(c=>r.searchParams.set(c,i[c]));const o=s.Support.AbortController?new AbortController:null;function l(){o&&!o.signal.aborted&&o.abort()}e.abort&&e.abort.addEventListener("abort",l);const b=e.timeout>0?setTimeout(l,e.timeout):null,h=new Request(r,{method:e.method,headers:new Headers(e.headers),body:e.body,credentials:e.credentials,signal:o==null?void 0:o.signal,redirect:"follow"});return await fetch(h).then(async c=>({url:r.toString(),method:e.method,status:c.status,statusText:c.statusText,headers:s.fromEntries([...c.headers.entries()]),body:e.method==="HEAD"?"":await c.text()})).catch(c=>({url:r.toString(),method:e.method,status:-1,statusText:o!=null&&o.signal.aborted?"Aborted":"NetworkError",body:String(c)})).finally(()=>{b!==null&&clearTimeout(b),e.abort&&e.abort.removeEventListener("abort",l)})},m=async function(n,a,t){const e={...await s.convertOptions(n,a,t),onUploadProgress:t==null?void 0:t.onUploadProgress},r=e.method,i=e.onUploadProgress||s.Wt,o=s.Et(e.url,e.params);return await new Promise(l=>{let b=1;function h(w){b=w.total,i({total:w.total,loaded:w.loaded})}let c=null,f=!1;const g=function(){f||(d.abort(),f=!0)};function p(){c!==null&&clearTimeout(c),e.abort&&e.abort.removeEventListener("abort",g)}const d=new XMLHttpRequest;d.open(r,o,!0),d.upload.addEventListener("progress",h),d.addEventListener("load",()=>{p(),i({loaded:b,total:b}),l({url:o,method:r,status:d.status,statusText:d.statusText,headers:T(d),body:r==="HEAD"?"":d.responseText})}),d.addEventListener("error",()=>{p(),l({url:o,method:r,status:-1,statusText:"Failed",body:""})}),d.addEventListener("abort",()=>{p(),l({url:o,method:r,status:-1,statusText:"Aborted",body:""})}),Object.entries(e.headers).forEach(([w,R])=>{d.setRequestHeader(w,R)}),e.credentials==="include"&&(d.withCredentials=!0),d.send(e.body||void 0),e.abort&&e.abort.addEventListener("abort",g),e.timeout>0&&(c=setTimeout(g,e.timeout))})};function T(n){const a={};if(!n)return a;const t=n.getAllResponseHeaders();return t&&t!=="null"&&t.replace(/\r/g,"").split(`
2
+ `).forEach(e=>{const r=e.trim();if(!r)return;const i=r.split(":"),o=i[0].trim();o&&(a[o]=(i[1]||"").trim())}),a}const q=async function(n,a,t){return s.handleResponse(await s.retryRequest(E,n,a,t),n,a,t)},H=async function(n,a,t){return s.handleResponse(await s.retryRequest(m,n,a,t),n,a,t)};async function S(n,a,t,e){const r=t==null?void 0:t.body,i=(t==null?void 0:t.method)==="PUT"?"PUT":"POST";if(a instanceof Blob){const c=new s.RequestGlobalConfig(e),f=await m(n,c,{...t,method:i,body:a});return s.handleResponse(f,n,c,t)}const o=new FormData,l={...a};r instanceof Object&&Object.entries(r).forEach(([c,f])=>{f instanceof Blob?l[c]=f:Array.isArray(f)?f.forEach((g,p)=>{o.append(`${c}[${p}]`,String(g))}):o.append(c,String(f))});for(const c in l)o.append(c,l[c]);const b=new s.RequestGlobalConfig(e),h=await m(n,b,{...t,method:i,body:o});return s.handleResponse(h,n,b,t)}async function x(n,a,t={}){const e=window;"callback"in t||(t.callback="jsonxData"+Math.random().toString(16).slice(2));const r=t.callback+"";if(!n)return null;const i=s.Et(n,t,!0);return new Promise(o=>{e[r]=function(l){if(r in window&&delete e[r],a(l))return l;console.warn("response type check faild",n,l),o(null)},s.he(i).catch(function(){o(null),delete e[r]})})}async function v(n,a,t={}){const e=window;return"var"in t||(t.var="jsonxData"+Math.random().toString(16).slice(2)),n?await s.he(s.Et(n,t,!0)).then(()=>{const r=e[t.var+""];return a(r)?r:(console.warn("response type check faild",n,r),null)}).catch(()=>null):null}const C=async function(n,a,t){return await S(n,a,t,{baseURL:u.getConfig("baseURL"),logHandler:u.getConfig("logHandler"),errorHandler:u.getConfig("errorHandler"),requestTransformer:u.getConfig("requestTransformer"),messageHandler:u.getConfig("messageHandler"),responseHandler:u.getConfig("responseHandler")})};function y(n){if(!s.Support.window)throw new Error("Default Module Only Support In Browser");return s.Support.fetch?new s.NetRequestHandler(q,n):new s.NetRequestHandler(H,n)}const u=y(),L=u.setConfig,j=u.head,U=u.get,O=u.post,P=u.del,A=u.put,D=u.patch;exports.getResponseRulesDescription=s.getResponseRulesDescription;exports.version=s.version;exports.NetRequest=y;exports.del=P;exports.get=U;exports.head=j;exports.jsonp=x;exports.jsonx=v;exports.patch=D;exports.post=O;exports.put=A;exports.setGlobalConfig=L;exports.upload=C;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { c as H, S as y, E as R, W as S, h as w, r as x, R as E, a as q, N as T } from "./version-D9usx_Q7.js";
2
- import { g as J, v as K } from "./version-D9usx_Q7.js";
3
- const C = async function(n, o, e) {
1
+ import { c as H, S as y, f as S, E as R, W as C, h as w, r as x, R as E, a as q, N as T } from "./version-BYvDLPww.js";
2
+ import { g as K, v as Q } from "./version-BYvDLPww.js";
3
+ const U = async function(n, o, e) {
4
4
  const t = await H(n, o, e), r = new URL(t.url), i = t.params;
5
5
  i instanceof Object && Object.keys(i).forEach((s) => r.searchParams.set(s, i[s]));
6
6
  const a = y.AbortController ? new AbortController() : null;
@@ -21,7 +21,7 @@ const C = async function(n, o, e) {
21
21
  method: t.method,
22
22
  status: s.status,
23
23
  statusText: s.statusText,
24
- headers: Object.fromEntries(s.headers.entries()),
24
+ headers: S([...s.headers.entries()]),
25
25
  body: t.method === "HEAD" ? "" : await s.text()
26
26
  })).catch((s) => ({
27
27
  url: r.toString(),
@@ -36,7 +36,7 @@ const C = async function(n, o, e) {
36
36
  const t = {
37
37
  ...await H(n, o, e),
38
38
  onUploadProgress: e == null ? void 0 : e.onUploadProgress
39
- }, r = t.method, i = t.onUploadProgress || S, a = R(t.url, t.params);
39
+ }, r = t.method, i = t.onUploadProgress || C, a = R(t.url, t.params);
40
40
  return await new Promise((c) => {
41
41
  let f = 1;
42
42
  function b(m) {
@@ -56,7 +56,7 @@ const C = async function(n, o, e) {
56
56
  method: r,
57
57
  status: d.status,
58
58
  statusText: d.statusText,
59
- headers: U(d),
59
+ headers: v(d),
60
60
  body: r === "HEAD" ? "" : d.responseText
61
61
  });
62
62
  }), d.addEventListener("error", () => {
@@ -80,7 +80,7 @@ const C = async function(n, o, e) {
80
80
  }), t.credentials === "include" && (d.withCredentials = !0), d.send(t.body || void 0), t.abort && t.abort.addEventListener("abort", h), t.timeout > 0 && (s = setTimeout(h, t.timeout));
81
81
  });
82
82
  };
83
- function U(n) {
83
+ function v(n) {
84
84
  const o = {};
85
85
  if (!n)
86
86
  return o;
@@ -94,12 +94,12 @@ function U(n) {
94
94
  a && (o[a] = (i[1] || "").trim());
95
95
  }), o;
96
96
  }
97
- const v = async function(n, o, e) {
98
- return w(await x(C, n, o, e), n, o, e);
99
- }, j = async function(n, o, e) {
97
+ const j = async function(n, o, e) {
98
+ return w(await x(U, n, o, e), n, o, e);
99
+ }, A = async function(n, o, e) {
100
100
  return w(await x(p, n, o, e), n, o, e);
101
101
  };
102
- async function A(n, o, e, t) {
102
+ async function P(n, o, e, t) {
103
103
  const r = e == null ? void 0 : e.body, i = (e == null ? void 0 : e.method) === "PUT" ? "PUT" : "POST";
104
104
  if (o instanceof Blob) {
105
105
  const s = new E(t), u = await p(n, s, {
@@ -124,7 +124,7 @@ async function A(n, o, e, t) {
124
124
  });
125
125
  return w(b, n, f, e);
126
126
  }
127
- async function k(n, o, e = {}) {
127
+ async function O(n, o, e = {}) {
128
128
  const t = window;
129
129
  "callback" in e || (e.callback = "jsonxData" + Math.random().toString(16).slice(2));
130
130
  const r = e.callback + "";
@@ -141,15 +141,15 @@ async function k(n, o, e = {}) {
141
141
  });
142
142
  });
143
143
  }
144
- async function D(n, o, e = {}) {
144
+ async function M(n, o, e = {}) {
145
145
  const t = window;
146
146
  return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), n ? await q(R(n, e, !0)).then(() => {
147
147
  const r = t[e.var + ""];
148
148
  return o(r) ? r : (console.warn("response type check faild", n, r), null);
149
149
  }).catch(() => null) : null;
150
150
  }
151
- const M = async function(n, o, e) {
152
- return await A(n, o, e, {
151
+ const N = async function(n, o, e) {
152
+ return await P(n, o, e, {
153
153
  baseURL: l.getConfig("baseURL"),
154
154
  logHandler: l.getConfig("logHandler"),
155
155
  errorHandler: l.getConfig("errorHandler"),
@@ -158,24 +158,24 @@ const M = async function(n, o, e) {
158
158
  responseHandler: l.getConfig("responseHandler")
159
159
  });
160
160
  };
161
- function O(n) {
161
+ function k(n) {
162
162
  if (!y.window)
163
163
  throw new Error("Default Module Only Support In Browser");
164
- return y.fetch ? new T(v, n) : new T(j, n);
164
+ return y.fetch ? new T(j, n) : new T(A, n);
165
165
  }
166
- const l = O(), N = l.setConfig, F = l.head, B = l.get, X = l.post, G = l.del, I = l.put, W = l.patch;
166
+ const l = k(), F = l.setConfig, B = l.head, X = l.get, G = l.post, I = l.del, W = l.put, $ = l.patch;
167
167
  export {
168
- O as NetRequest,
169
- G as del,
170
- B as get,
171
- J as getResponseRulesDescription,
172
- F as head,
173
- k as jsonp,
174
- D as jsonx,
175
- W as patch,
176
- X as post,
177
- I as put,
178
- N as setGlobalConfig,
179
- M as upload,
180
- K as version
168
+ k as NetRequest,
169
+ I as del,
170
+ X as get,
171
+ K as getResponseRulesDescription,
172
+ B as head,
173
+ O as jsonp,
174
+ M as jsonx,
175
+ $ as patch,
176
+ G as post,
177
+ W as put,
178
+ F as setGlobalConfig,
179
+ N as upload,
180
+ Q as version
181
181
  };
package/dist/node.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("node:http"),q=require("node:https"),r=require("./version-D6D6EXmg.cjs"),R=async function(s,u,c){return r.handleResponse(await r.retryRequest(w,s,u,c),s,u,c)},w=async function(s,u,c){const t=await r.convertOptions(s,u,c);if(!r.U(t.url))return{url:t.url,method:t.method,status:-1,statusText:"URLFormatError",headers:{},body:""};const b=/^https:\/\//i.test(t.url)?q: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=b.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(e){const p=[];e.on("data",h=>p.push(h)),e.on("end",()=>{const h=Object.fromEntries(Object.entries(e.headers).map(([g,m])=>[g.toLowerCase(),Array.isArray(m)?m.join(","):m]));n({url:a.toString(),method:t.method,status:e.statusCode||-1,statusText:e.statusMessage||"Unknown",headers:h,body:f?"":Buffer.concat(p).toString("utf-8")})})});d.on("error",e=>{n({url:a.toString(),method:t.method,status:-1,statusText:e.name||"Unknown",body:e.message})}),d.on("timeout",()=>{n({url:a.toString(),method:t.method,status:-1,statusText:"Timeout",body:""})}),t.body&&d.write(t.body),d.end()})};function l(s){return new r.NetRequestHandler(R,s)}const o=l(),j=o.setConfig,O=o.head,S=o.get,T=o.post,U=o.del,C=o.put,x=o.patch;exports.version=r.version;exports.NetRequest=l;exports.del=U;exports.get=S;exports.head=O;exports.patch=x;exports.post=T;exports.put=C;exports.setGlobalConfig=j;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("node:http"),q=require("node:https"),o=require("./version-DUfwEwFz.cjs"),R=async function(n,u,c){return o.handleResponse(await o.retryRequest(w,n,u,c),n,u,c)},w=async function(n,u,c){const t=await o.convertOptions(n,u,c);if(!o.U(t.url))return{url:t.url,method:t.method,status:-1,statusText:"URLFormatError",headers:{},body:""};const f=/^https:\/\//i.test(t.url)?q:y,a=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(r=>a.searchParams.set(r,i[r]));const b=t.method==="HEAD";return new Promise(r=>{const d=f.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(e){const p=[];e.on("data",h=>p.push(h)),e.on("end",()=>{const h=o.fromEntries(Object.entries(e.headers).map(([g,m])=>[g.toLowerCase(),Array.isArray(m)?m.join(","):m]));r({url:a.toString(),method:t.method,status:e.statusCode||-1,statusText:e.statusMessage||"Unknown",headers:h,body:b?"":Buffer.concat(p).toString("utf-8")})})});d.on("error",e=>{r({url:a.toString(),method:t.method,status:-1,statusText:e.name||"Unknown",body:e.message})}),d.on("timeout",()=>{r({url:a.toString(),method:t.method,status:-1,statusText:"Timeout",body:""})}),t.body&&d.write(t.body),d.end()})};function l(n){return new o.NetRequestHandler(R,n)}const s=l(),S=s.setConfig,T=s.head,U=s.get,j=s.post,C=s.del,O=s.put,x=s.patch;exports.version=o.version;exports.NetRequest=l;exports.del=C;exports.get=U;exports.head=T;exports.patch=x;exports.post=j;exports.put=O;exports.setGlobalConfig=S;
package/dist/node.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import l from "node:http";
2
2
  import y from "node:https";
3
- import { h as R, r as g, c as q, U as w, N as x } from "./version-D9usx_Q7.js";
4
- import { v as F } from "./version-D9usx_Q7.js";
5
- const U = async function(s, a, u) {
3
+ import { h as R, r as g, c as q, U as w, f as x, N as U } from "./version-BYvDLPww.js";
4
+ import { v as G } from "./version-BYvDLPww.js";
5
+ const T = async function(s, a, u) {
6
6
  return R(await g(j, s, a, u), s, a, u);
7
7
  }, j = async function(s, a, u) {
8
8
  const t = await q(s, a, u);
@@ -29,7 +29,7 @@ const U = async function(s, a, u) {
29
29
  function(e) {
30
30
  const h = [];
31
31
  e.on("data", (i) => h.push(i)), e.on("end", () => {
32
- const i = Object.fromEntries(
32
+ const i = x(
33
33
  Object.entries(e.headers).map(([b, m]) => [b.toLowerCase(), Array.isArray(m) ? m.join(",") : m])
34
34
  );
35
35
  n({
@@ -62,18 +62,18 @@ const U = async function(s, a, u) {
62
62
  }), t.body && c.write(t.body), c.end();
63
63
  });
64
64
  };
65
- function O(s) {
66
- return new x(U, s);
65
+ function C(s) {
66
+ return new U(T, s);
67
67
  }
68
- const o = O(), L = o.setConfig, N = o.head, S = o.get, A = o.post, H = o.del, k = o.put, P = o.patch;
68
+ const o = C(), O = o.setConfig, S = o.head, A = o.get, H = o.post, k = o.del, P = o.put, B = o.patch;
69
69
  export {
70
- O as NetRequest,
71
- H as del,
72
- S as get,
73
- N as head,
74
- P as patch,
75
- A as post,
76
- k as put,
77
- L as setGlobalConfig,
78
- F as version
70
+ C as NetRequest,
71
+ k as del,
72
+ A as get,
73
+ S as head,
74
+ B as patch,
75
+ H as post,
76
+ P as put,
77
+ O as setGlobalConfig,
78
+ G as version
79
79
  };
@@ -10,7 +10,13 @@ const m = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global :
10
10
  TextDecoder: "TextDecoder" in m,
11
11
  AbortController: "AbortController" in m
12
12
  };
13
- async function ne(t, e, n) {
13
+ function L(t) {
14
+ return t.reduce(
15
+ (e, [n, s]) => (n && (e[n] = s || ""), e),
16
+ {}
17
+ );
18
+ }
19
+ async function ae(t, e, n) {
14
20
  var p;
15
21
  const s = Object.assign({ method: "GET" }, n), r = w.FormData ? s.body instanceof FormData : !1, a = r && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method;
16
22
  (a === "GET" || a === "HEAD" || a === "DELETE") && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
@@ -21,12 +27,12 @@ async function ne(t, e, n) {
21
27
  s.headers
22
28
  ), i = s.params || {}, c = {};
23
29
  Object.keys(i).forEach((h) => {
24
- i[h] !== void 0 && (c[h] = L(i[h]));
30
+ i[h] !== void 0 && (c[h] = U(i[h]));
25
31
  });
26
- const d = e.getFullUrl(t), l = U(s.body), u = s.timeout || e.get("timeout"), g = await async function() {
27
- var O;
32
+ const d = e.getFullUrl(t), l = B(s.body), u = s.timeout || e.get("timeout"), g = await async function() {
33
+ var v;
28
34
  const h = e.get("requestTransformer");
29
- return h ? await h({ headers: o, params: c, method: a, url: d, body: l }) : await ((O = e.get("requestHandler")) == null ? void 0 : O(o, c, a, t));
35
+ return h ? await h({ headers: o, params: c, method: a, url: d, body: l }) : await ((v = e.get("requestHandler")) == null ? void 0 : v(o, c, a, t));
30
36
  }(), y = typeof g == "string" && g ? g : d;
31
37
  return (p = e.get("logHandler")) == null || p({ type: "ready", url: y, method: a, headers: o, timeout: u, body: l }), {
32
38
  url: y,
@@ -39,17 +45,17 @@ async function ne(t, e, n) {
39
45
  credentials: s.credentials || e.get("credentials")
40
46
  };
41
47
  }
42
- function L(t) {
48
+ function U(t) {
43
49
  return typeof t == "string" ? t : Array.isArray(t) ? t.join(",") : t + "";
44
50
  }
45
- function U(t) {
51
+ function B(t) {
46
52
  if (t)
47
53
  return typeof t == "string" || t instanceof URLSearchParams || t instanceof ArrayBuffer || w.Blob && t instanceof Blob || w.FormData && t instanceof FormData ? t : JSON.stringify(t);
48
54
  }
49
- function B(t) {
55
+ function P(t) {
50
56
  return new Promise((e) => setTimeout(e, Math.max(0, t)));
51
57
  }
52
- function P() {
58
+ function H() {
53
59
  }
54
60
  function R(t, e) {
55
61
  try {
@@ -60,11 +66,11 @@ function R(t, e) {
60
66
  }
61
67
  }
62
68
  "" + Math.random().toString(32).slice(2);
63
- const H = /^(?:https?:)?\/\/.+$/i, S = /^https?:\/\/.+$/i, K = /^\{[\d\D]*\}$/, I = /^\[[\d\D]*\]$/;
69
+ const S = /^(?:https?:)?\/\/.+$/i, K = /^https?:\/\/.+$/i, I = /^\{[\d\D]*\}$/, N = /^\[[\d\D]*\]$/;
64
70
  function $(t, e = !1) {
65
- return e ? H.test(t) : S.test(t);
71
+ return e ? S.test(t) : K.test(t);
66
72
  }
67
- function N(t) {
73
+ function q(t) {
68
74
  return t == null;
69
75
  }
70
76
  function M(t, ...e) {
@@ -74,9 +80,9 @@ function M(t, ...e) {
74
80
  return n !== Object.prototype && n !== null ? !1 : e.every((s) => s in t);
75
81
  }
76
82
  function D(t) {
77
- return K.test(t) || I.test(t);
83
+ return I.test(t) || N.test(t);
78
84
  }
79
- async function ae(t) {
85
+ async function re(t) {
80
86
  return await new Promise(function(e) {
81
87
  const n = document.getElementsByTagName("head")[0], s = document.createElement("script");
82
88
  s.setAttribute("type", "text/javascript"), s.setAttribute("charset", "utf-8"), s.onload = function() {
@@ -86,7 +92,7 @@ async function ae(t) {
86
92
  }, s.setAttribute("src", t), n.appendChild(s);
87
93
  });
88
94
  }
89
- function q(t, e = "数据未能正确识别") {
95
+ function W(t, e = "数据未能正确识别") {
90
96
  return typeof t == "function" ? {
91
97
  guard: t,
92
98
  message: e
@@ -95,13 +101,13 @@ function q(t, e = "数据未能正确识别") {
95
101
  message: t.message || e
96
102
  };
97
103
  }
98
- function v(t, e = "") {
104
+ function O(t, e = "") {
99
105
  return !e || $(t, !0) ? T(t) : (T(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
100
106
  }
101
107
  function T(t) {
102
108
  return $(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(/^\/+/, "");
103
109
  }
104
- function W(t, e) {
110
+ function G(t, e) {
105
111
  if (e) {
106
112
  if (e === !0)
107
113
  return t.replace(/\?[^#]*/, "");
@@ -110,12 +116,12 @@ function W(t, e) {
110
116
  const n = t.split("#"), s = n[0].split("?"), r = s[0], a = s.length > 1 ? s[1] : "", o = n.length > 1 ? "#" + n[1] : "", i = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
111
117
  return !i.length || !a ? n[0] + o : (i.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + a.replace(new RegExp("(?:^|&)(?:" + i.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
112
118
  }
113
- function re(t, e, n = !1) {
119
+ function oe(t, e, n = !1) {
114
120
  const s = typeof e == "string" ? e : Object.keys(e).map((o) => `${o}=${encodeURIComponent(e[o])}`).join("&");
115
121
  if (!s)
116
122
  return t;
117
123
  const r = t.split("#");
118
- n && (r[0] = W(
124
+ n && (r[0] = G(
119
125
  r[0],
120
126
  (s.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
121
127
  ));
@@ -123,11 +129,11 @@ function re(t, e, n = !1) {
123
129
  return (r[0] + a + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
124
130
  }
125
131
  const C = "data", b = "message";
126
- function G(t, e, n, s, r) {
132
+ function J(t, e, n, s, r) {
127
133
  const a = r || s;
128
- return F(t) ? X(a.ok || s.ok, t, e, n) : J(a.failed || s.failed, e, n);
134
+ return F(t) ? Y(a.ok || s.ok, t, e, n) : _(a.failed || s.failed, e, n);
129
135
  }
130
- const oe = function(t) {
136
+ const ie = function(t) {
131
137
  const e = [], n = t.failed || { resolve: "json" };
132
138
  switch (e.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
133
139
  case "body":
@@ -151,7 +157,7 @@ const oe = function(t) {
151
157
  return e.join(`
152
158
  `);
153
159
  };
154
- function J(t, e, n) {
160
+ function _(t, e, n) {
155
161
  const s = t || { resolve: "json", messageField: b }, r = {
156
162
  ok: !1,
157
163
  code: e,
@@ -163,13 +169,13 @@ function J(t, e, n) {
163
169
  r.message = k(n) || n;
164
170
  break;
165
171
  case "json":
166
- const { code: a, message: o } = _(n, s.statusField, s.messageField);
172
+ const { code: a, message: o } = V(n, s.statusField, s.messageField);
167
173
  r.code = a || e, r.message = k(n) || o;
168
174
  break;
169
175
  }
170
176
  return r;
171
177
  }
172
- function _(t, e, n = b) {
178
+ function V(t, e, n = b) {
173
179
  if (!D(t))
174
180
  return { message: "" };
175
181
  const s = R(t);
@@ -182,21 +188,21 @@ function j(t, e) {
182
188
  const n = Array.isArray(e) ? e : [e];
183
189
  for (const s of n)
184
190
  if (s in t)
185
- return V(t[s]);
191
+ return z(t[s]);
186
192
  return "";
187
193
  }
188
- function V(t) {
194
+ function z(t) {
189
195
  return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
190
196
  }
191
- const z = /<title>([^<]+)<\/title>/i, Q = /<message>([^<]+)<\/message>/i;
197
+ const Q = /<title>([^<]+)<\/title>/i, X = /<message>([^<]+)<\/message>/i;
192
198
  function k(t) {
193
- const e = t.match(z);
199
+ const e = t.match(Q);
194
200
  if (e)
195
201
  return e[1];
196
- const n = t.match(Q);
202
+ const n = t.match(X);
197
203
  return n ? n[1] : "";
198
204
  }
199
- function X(t, e, n, s) {
205
+ function Y(t, e, n, s) {
200
206
  const r = t || { resolve: "body" }, a = {
201
207
  ok: !0,
202
208
  code: n,
@@ -219,8 +225,8 @@ function X(t, e, n, s) {
219
225
  function F(t) {
220
226
  return t >= 200 && t < 400;
221
227
  }
222
- async function Y(t, e, n, s, r) {
223
- const a = r || 0, o = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? n.get("maxRetry") ?? 0)), i = (s == null ? void 0 : s.retryResolve) ?? n.get("retryResolve"), c = n.get("logHandler") || P;
228
+ async function Z(t, e, n, s, r) {
229
+ const a = r || 0, o = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? n.get("maxRetry") ?? 0)), i = (s == null ? void 0 : s.retryResolve) ?? n.get("retryResolve"), c = n.get("logHandler") || H;
224
230
  c({
225
231
  type: "prepear",
226
232
  url: e,
@@ -247,14 +253,14 @@ async function Y(t, e, n, s, r) {
247
253
  if (!o || i === "network" && u > 0 || i === "status" && p || Array.isArray(i) && !i.includes(u) || typeof i == "function" && i(l, a) !== !0 || a >= o)
248
254
  return l;
249
255
  const h = (s == null ? void 0 : s.retryInterval) ?? n.get("retryInterval") ?? 1e3;
250
- return await B(
256
+ return await P(
251
257
  Math.max(
252
258
  100,
253
259
  h === "2EB" ? Math.pow(2, a) * 1e3 : typeof h == "function" ? h(a + 1) || 0 : h
254
260
  )
255
- ), await Y(t, e, n, s, a + 1);
261
+ ), await Z(t, e, n, s, a + 1);
256
262
  }
257
- function ie(t, e, n, s) {
263
+ function ce(t, e, n, s) {
258
264
  var o, i;
259
265
  if (t.status < 0)
260
266
  return E(
@@ -267,9 +273,9 @@ function ie(t, e, n, s) {
267
273
  );
268
274
  F(t.status) || (o = n.get("errorHandler")) == null || o(t.status, t.method, e);
269
275
  const r = {
270
- ...G(t.status, t.statusText, t.body, n.get("responseRule"), s == null ? void 0 : s.responseRule),
276
+ ...J(t.status, t.statusText, t.body, n.get("responseRule"), s == null ? void 0 : s.responseRule),
271
277
  status: t.status,
272
- headers: Object.fromEntries(Object.entries(t.headers || {}).map(([c, d]) => [c.toLowerCase(), d]))
278
+ headers: L(Object.entries(t.headers || {}).map(([c, d]) => [c.toLowerCase(), d]))
273
279
  };
274
280
  (i = n.get("responseHandler")) == null || i({ ...r }, t.method, e);
275
281
  const a = r.ok ? r.message : `${t.method} ${e} [${r.code || t.statusText}] ${r.message || t.statusText}`;
@@ -283,7 +289,7 @@ function E(t, e, n, s, r, a) {
283
289
  }
284
290
  return t;
285
291
  }
286
- class Z {
292
+ class ee {
287
293
  constructor(e) {
288
294
  // 保存的配置需要部分字段强制设置默认值
289
295
  f(this, "config", {
@@ -316,14 +322,14 @@ class Z {
316
322
  }
317
323
  /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
318
324
  getFullUrl(e) {
319
- return e.startsWith("/") ? v(e) : v(e, this.config.baseURL);
325
+ return e.startsWith("/") ? O(e) : O(e, this.config.baseURL);
320
326
  }
321
327
  /** 提示消息 */
322
328
  showMessage(e, n) {
323
329
  this.config.messageHandler && n && this.config.messageHandler(e, n);
324
330
  }
325
331
  }
326
- class ee {
332
+ class te {
327
333
  constructor(e = 500) {
328
334
  f(this, "ttl");
329
335
  f(this, "cache");
@@ -349,19 +355,19 @@ class ee {
349
355
  });
350
356
  }
351
357
  }
352
- function te(t, e, n, s) {
353
- if (e.ok && !N(e.data) && s) {
354
- const r = q(s, "响应数据未能正确识别");
358
+ function se(t, e, n, s) {
359
+ if (e.ok && !q(e.data) && s) {
360
+ const r = W(s, "响应数据未能正确识别");
355
361
  return r.guard(e.data) || (console.error("ResponseCheckFaild", t, e.data), n.showMessage(!0, `${t} ${r.message}`), e.data = null), e;
356
362
  }
357
363
  return e;
358
364
  }
359
- class ce {
365
+ class ue {
360
366
  constructor(e, n) {
361
367
  f(this, "agent");
362
368
  f(this, "config");
363
369
  f(this, "cache");
364
- this.config = new Z(n), this.agent = e, this.cache = new ee(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.bind(this), this.get = this.get.bind(this), this.post = this.post.bind(this), this.del = this.del.bind(this), this.patch = this.patch.bind(this), this.put = this.put.bind(this), this.head = this.head.bind(this);
370
+ this.config = new ee(n), this.agent = e, this.cache = new te(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.bind(this), this.get = this.get.bind(this), this.post = this.post.bind(this), this.del = this.del.bind(this), this.patch = this.patch.bind(this), this.put = this.put.bind(this), this.head = this.head.bind(this);
365
371
  }
366
372
  /**
367
373
  * 执行网络请求
@@ -373,7 +379,7 @@ class ce {
373
379
  * 检查响应的数据类型
374
380
  */
375
381
  async guard(e, n, s) {
376
- return te(e, n, this.config, s);
382
+ return se(e, n, this.config, s);
377
383
  }
378
384
  /**
379
385
  * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
@@ -420,18 +426,19 @@ class ce {
420
426
  return a.method = "PATCH", a.body = n, this.guard(e, await this.exec(e, a), s || null);
421
427
  }
422
428
  }
423
- const ue = "1.6.2";
429
+ const le = "1.6.4";
424
430
  export {
425
- re as E,
426
- ce as N,
427
- Z as R,
431
+ oe as E,
432
+ ue as N,
433
+ ee as R,
428
434
  w as S,
429
435
  $ as U,
430
- P as W,
431
- ae as a,
432
- ne as c,
433
- oe as g,
434
- ie as h,
435
- Y as r,
436
- ue as v
436
+ H as W,
437
+ re as a,
438
+ ae as c,
439
+ L as f,
440
+ ie as g,
441
+ ce as h,
442
+ Z as r,
443
+ le as v
437
444
  };
@@ -0,0 +1,2 @@
1
+ "use strict";var B=Object.defineProperty;var H=(t,e,n)=>e in t?B(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var f=(t,e,n)=>(H(t,typeof e!="symbol"?e+"":e,n),n);const m=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},b={fetch:"fetch"in m,window:"window"in m,FormData:"FormData"in m,Blob:"Blob"in m,wx:"wx"in m,TextDecoder:"TextDecoder"in m,AbortController:"AbortController"in m};function M(t){return t.reduce((e,[n,s])=>(n&&(e[n]=s||""),e),{})}async function P(t,e,n){var w;const s=Object.assign({method:"GET"},n),r=b.FormData?s.body instanceof FormData:!1,a=r&&s.method!=="POST"&&s.method!=="PUT"?"POST":s.method;(a==="GET"||a==="HEAD"||a==="DELETE")&&s.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);const o=Object.assign(r?{}:{"Content-Type":b.Blob&&s.body instanceof Blob?s.body.type||"application/octet-stream":"application/json;charset=utf-8"},s.headers),i=s.params||{},c={};Object.keys(i).forEach(h=>{i[h]!==void 0&&(c[h]=S(i[h]))});const d=e.getFullUrl(t),l=q(s.body),u=s.timeout||e.get("timeout"),g=await async function(){var F;const h=e.get("requestTransformer");return h?await h({headers:o,params:c,method:a,url:d,body:l}):await((F=e.get("requestHandler"))==null?void 0:F(o,c,a,t))}(),y=typeof g=="string"&&g?g:d;return(w=e.get("logHandler"))==null||w({type:"ready",url:y,method:a,headers:o,timeout:u,body:l}),{url:y,method:a,body:l,params:c,headers:o,timeout:u,abort:s.abort,credentials:s.credentials||e.get("credentials")}}function S(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function q(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||b.Blob&&t instanceof Blob||b.FormData&&t instanceof FormData?t:JSON.stringify(t)}function K(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function D(){}function j(t,e){try{const n=JSON.parse(t);return e?e(n)?n:null:n}catch{return null}}""+Math.random().toString(32).slice(2);const I=/^(?:https?:)?\/\/.+$/i,N=/^https?:\/\/.+$/i,G=/^\{[\d\D]*\}$/,W=/^\[[\d\D]*\]$/;function R(t,e=!1){return e?I.test(t):N.test(t)}function J(t){return t==null}function C(t,...e){if(!t||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n!==Object.prototype&&n!==null?!1:e.every(s=>s in t)}function A(t){return G.test(t)||W.test(t)}async function _(t){return await new Promise(function(e){const n=document.getElementsByTagName("head")[0],s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("charset","utf-8"),s.onload=function(){n.removeChild(s),e(!0)},s.onerror=function(){n.removeChild(s),e(!1)},s.setAttribute("src",t),n.appendChild(s)})}function V(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function O(t,e=""){return!e||R(t,!0)?T(t):(T(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function T(t){return R(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 z(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const n=t.split("#"),s=n[0].split("?"),r=s[0],a=s.length>1?s[1]:"",o=n.length>1?"#"+n[1]:"",i=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!i.length||!a?n[0]+o:(i.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+a.replace(new RegExp("(?:^|&)(?:"+i.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function Q(t,e,n=!1){const s=typeof e=="string"?e:Object.keys(e).map(o=>`${o}=${encodeURIComponent(e[o])}`).join("&");if(!s)return t;const r=t.split("#");n&&(r[0]=z(r[0],(s.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const a=r[0].indexOf("?")+1?"&":"?";return(r[0]+a+s+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}const x="data",p="message";function X(t,e,n,s,r){const a=r||s;return v(t)?ae(a.ok||s.ok,t,e,n):Z(a.failed||s.failed,e,n)}const Y=function(t){const e=[],n=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),n.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(n.messageField||p)+" 作为错误消息");break}const s=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),s.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(s.dataField||x)+" 作为响应数据,读取 "+(s.messageField||p)+" 作为提示消息"),s.statusField&&e.push(" 当 "+s.statusField+" 为 "+(s.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),s.ignoreMessage&&e.push(" 并忽略以下消息:"+s.ignoreMessage);break}return e.join(`
2
+ `)};function Z(t,e,n){const s=t||{resolve:"json",messageField:p},r={ok:!1,code:e,message:n,data:null};switch(s.resolve){case"body":r.message=E(n)||n;break;case"json":const{code:a,message:o}=ee(n,s.statusField,s.messageField);r.code=a||e,r.message=E(n)||o;break}return r}function ee(t,e,n=p){if(!A(t))return{message:""};const s=j(t);return!s||!C(s)?{message:t}:{code:e?$(s,e):"",message:$(s,n)||t}}function $(t,e){const n=Array.isArray(e)?e:[e];for(const s of n)if(s in t)return te(t[s]);return""}function te(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const se=/<title>([^<]+)<\/title>/i,ne=/<message>([^<]+)<\/message>/i;function E(t){const e=t.match(se);if(e)return e[1];const n=t.match(ne);return n?n[1]:""}function ae(t,e,n,s){const r=t||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(e===202||e===204||!s)return a;if(r.resolve==="body")return a.data=A(s)?j(s):s,a;const o=j(s);if(!o||!C(o))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;const i=r.statusField,c=r.statusOKValue||"",d=r.dataField||x,l=r.messageField||p,u=r.ignoreMessage||"";if(i&&!(i in o))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+i,a;const g=i?o[i]+"":"";return a.ok=i?g===c:!0,a.code=g||n,a.data=d===!0?o:d in o?o[d]:null,a.message=$(o,l),u&&a.message&&(Array.isArray(u)&&u.includes(a.message)||typeof u=="string"&&a.message===u)&&(a.message=""),a}function v(t){return t>=200&&t<400}async function U(t,e,n,s,r){const a=r||0,o=Math.max(0,Math.min(10,(s==null?void 0:s.maxRetry)??n.get("maxRetry")??0)),i=(s==null?void 0:s.retryResolve)??n.get("retryResolve"),c=n.get("logHandler")||D;c({type:"prepear",url:e,method:(s==null?void 0:s.method)||"GET",retry:a,maxRetry:o,message:a===0?"start":`retry ${a}/${o} start`,headers:s==null?void 0:s.headers,options:s});const d=Date.now(),l=await t(e,n,s),u=l.status,g=Date.now()-d,y=`[cost ${g}][${u}] ${u<0?l.body:""}`;c({type:"finished",url:e,method:l.method,retry:a,maxRetry:o,message:a===0?`finish ${y}`:`retry ${a}/${o} finish ${y}`,response:l,headers:l.headers,cost:g});const w=v(u);if(!o||i==="network"&&u>0||i==="status"&&w||Array.isArray(i)&&!i.includes(u)||typeof i=="function"&&i(l,a)!==!0||a>=o)return l;const h=(s==null?void 0:s.retryInterval)??n.get("retryInterval")??1e3;return await K(Math.max(100,h==="2EB"?Math.pow(2,a)*1e3:typeof h=="function"?h(a+1)||0:h)),await U(t,e,n,s,a+1)}function re(t,e,n,s){var o,i;if(t.status<0)return k({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,n,s);v(t.status)||(o=n.get("errorHandler"))==null||o(t.status,t.method,e);const r={...X(t.status,t.statusText,t.body,n.get("responseRule"),s==null?void 0:s.responseRule),status:t.status,headers:M(Object.entries(t.headers||{}).map(([c,d])=>[c.toLowerCase(),d]))};(i=n.get("responseHandler"))==null||i({...r},t.method,e);const a=r.ok?r.message:`${t.method} ${e} [${r.code||t.statusText}] ${r.message||t.statusText}`;return k(r,a,t.method,e,n,s)}function k(t,e,n,s,r,a){const o=r.get("message"),i=o===!1||(a==null?void 0:a.message)===!1?!1:(a==null?void 0:a.message)||o;if(i!==!1){const c=typeof i=="function"?i(t,n,s,e):e;c instanceof Error?r.showMessage(!0,c.message):c&&typeof c=="object"&&"message"in c?r.showMessage(!1,c.message):r.showMessage(!t.ok,c)}return t}class L{constructor(e){f(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!R(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.startsWith("/")?O(e):O(e,this.config.baseURL)}showMessage(e,n){this.config.messageHandler&&n&&this.config.messageHandler(e,n)}}class oe{constructor(e=500){f(this,"ttl");f(this,"cache");this.cache={},this.ttl=Math.max(e,0)}getKey(e,n){const s=Object.keys(n||{}).sort().map(r=>`${r}#${n==null?void 0:n[r]}`);return e+s.join(",")}updateTTL(e){this.ttl=Math.max(e,0)}get(e){if(this.ttl===0)return null;const n=this.cache[e];return n?n.ttl<Date.now()?(delete this.cache[e],null):n.res:null}set(e,n){this.ttl!==0&&(this.cache[e]={ttl:Date.now()+this.ttl,res:n})}}function ie(t,e,n,s){if(e.ok&&!J(e.data)&&s){const r=V(s,"响应数据未能正确识别");return r.guard(e.data)||(console.error("ResponseCheckFaild",t,e.data),n.showMessage(!0,`${t} ${r.message}`),e.data=null),e}return e}class ce{constructor(e,n){f(this,"agent");f(this,"config");f(this,"cache");this.config=new L(n),this.agent=e,this.cache=new oe(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async exec(e,n){return await this.agent(e,this.config,n)}async guard(e,n,s){return ie(e,n,this.config,s)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,n){const s=Object.assign({},n||null);return s.method="HEAD",this.guard(e,await this.exec(e,s),null)}async get(e,n,s){const r=Object.assign({},s||null);r.method="GET";const a=this.cache.getKey(e,r.params),o=this.cache.get(a);if(o)return this.guard(e,await o,n||null);const i=this.exec(e,r);return this.cache.set(a,i),this.guard(e,await i,n||null)}async post(e,n,s,r){const a=Object.assign({},r||null);return a.method="POST",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async del(e,n,s){const r=Object.assign({},s||null);return r.method="DELETE",this.guard(e,await this.exec(e,r),n||null)}async put(e,n,s,r){const a=Object.assign({},r||null);return a.method="PUT",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async patch(e,n,s,r){const a=Object.assign({},r||null);return a.method="PATCH",a.body=n,this.guard(e,await this.exec(e,a),s||null)}}const ue="1.6.4";exports.Et=Q;exports.NetRequestHandler=ce;exports.RequestGlobalConfig=L;exports.Support=b;exports.U=R;exports.Wt=D;exports.convertOptions=P;exports.fromEntries=M;exports.getResponseRulesDescription=Y;exports.handleResponse=re;exports.he=_;exports.retryRequest=U;exports.version=ue;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "1.6.2";
1
+ export declare const version = "1.6.4";
package/dist/wx.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./version-D6D6EXmg.cjs"),p=async function(t,r,n){return e.handleResponse(await e.retryRequest(l,t,r,n),t,r,n)},l=async function(t,r,n){const o=await e.convertOptions(t,r,n),u=o.method==="PATCH"?"POST":o.method,a=e.Et(o.url,o.params);return e.Support.wx?new Promise(d=>{wx.request({url:a,data:o.body,header:o.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:o.method==="HEAD"?"":f(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};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(p,t)}const s=i(),y=s.setConfig,g=s.head,h=s.get,x=s.post,w=s.del,T=s.put;exports.version=e.version;exports.NetRequest=i;exports.del=w;exports.get=h;exports.head=g;exports.post=x;exports.put=T;exports.setGlobalConfig=y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./version-DUfwEwFz.cjs"),p=async function(t,r,n){return e.handleResponse(await e.retryRequest(l,t,r,n),t,r,n)},l=async function(t,r,n){const o=await e.convertOptions(t,r,n),u=o.method==="PATCH"?"POST":o.method,a=e.Et(o.url,o.params);return e.Support.wx?new Promise(d=>{wx.request({url:a,data:o.body,header:o.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:o.method==="HEAD"?"":f(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};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(p,t)}const s=i(),y=s.setConfig,g=s.head,h=s.get,x=s.post,w=s.del,T=s.put;exports.version=e.version;exports.NetRequest=i;exports.del=w;exports.get=h;exports.head=g;exports.post=x;exports.put=T;exports.setGlobalConfig=y;
package/dist/wx.js CHANGED
@@ -1,5 +1,5 @@
1
- import { h as i, r as p, c as f, E as l, S as d, N as x } from "./version-D9usx_Q7.js";
2
- import { v as A } from "./version-D9usx_Q7.js";
1
+ import { h as i, r as p, c as f, E as l, S as d, N as x } from "./version-BYvDLPww.js";
2
+ import { v as A } from "./version-BYvDLPww.js";
3
3
  const h = async function(t, o, r) {
4
4
  return i(await p(y, t, o, r), t, o, r);
5
5
  }, y = async function(t, o, r) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "1.6.2",
3
+ "version": "1.6.4",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -1,2 +0,0 @@
1
- "use strict";var L=Object.defineProperty;var B=(t,e,n)=>e in t?L(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var f=(t,e,n)=>(B(t,typeof e!="symbol"?e+"":e,n),n);const m=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},b={fetch:"fetch"in m,window:"window"in m,FormData:"FormData"in m,Blob:"Blob"in m,wx:"wx"in m,TextDecoder:"TextDecoder"in m,AbortController:"AbortController"in m};async function H(t,e,n){var w;const s=Object.assign({method:"GET"},n),r=b.FormData?s.body instanceof FormData:!1,a=r&&s.method!=="POST"&&s.method!=="PUT"?"POST":s.method;(a==="GET"||a==="HEAD"||a==="DELETE")&&s.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);const o=Object.assign(r?{}:{"Content-Type":b.Blob&&s.body instanceof Blob?s.body.type||"application/octet-stream":"application/json;charset=utf-8"},s.headers),i=s.params||{},c={};Object.keys(i).forEach(h=>{i[h]!==void 0&&(c[h]=P(i[h]))});const d=e.getFullUrl(t),l=S(s.body),u=s.timeout||e.get("timeout"),g=await async function(){var v;const h=e.get("requestTransformer");return h?await h({headers:o,params:c,method:a,url:d,body:l}):await((v=e.get("requestHandler"))==null?void 0:v(o,c,a,t))}(),y=typeof g=="string"&&g?g:d;return(w=e.get("logHandler"))==null||w({type:"ready",url:y,method:a,headers:o,timeout:u,body:l}),{url:y,method:a,body:l,params:c,headers:o,timeout:u,abort:s.abort,credentials:s.credentials||e.get("credentials")}}function P(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function S(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||b.Blob&&t instanceof Blob||b.FormData&&t instanceof FormData?t:JSON.stringify(t)}function q(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function M(){}function j(t,e){try{const n=JSON.parse(t);return e?e(n)?n:null:n}catch{return null}}""+Math.random().toString(32).slice(2);const K=/^(?:https?:)?\/\/.+$/i,I=/^https?:\/\/.+$/i,N=/^\{[\d\D]*\}$/,G=/^\[[\d\D]*\]$/;function R(t,e=!1){return e?K.test(t):I.test(t)}function W(t){return t==null}function D(t,...e){if(!t||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n!==Object.prototype&&n!==null?!1:e.every(s=>s in t)}function C(t){return N.test(t)||G.test(t)}async function J(t){return await new Promise(function(e){const n=document.getElementsByTagName("head")[0],s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("charset","utf-8"),s.onload=function(){n.removeChild(s),e(!0)},s.onerror=function(){n.removeChild(s),e(!1)},s.setAttribute("src",t),n.appendChild(s)})}function _(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function F(t,e=""){return!e||R(t,!0)?T(t):(T(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function T(t){return R(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 V(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const n=t.split("#"),s=n[0].split("?"),r=s[0],a=s.length>1?s[1]:"",o=n.length>1?"#"+n[1]:"",i=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!i.length||!a?n[0]+o:(i.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+a.replace(new RegExp("(?:^|&)(?:"+i.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function z(t,e,n=!1){const s=typeof e=="string"?e:Object.keys(e).map(o=>`${o}=${encodeURIComponent(e[o])}`).join("&");if(!s)return t;const r=t.split("#");n&&(r[0]=V(r[0],(s.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const a=r[0].indexOf("?")+1?"&":"?";return(r[0]+a+s+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}const A="data",p="message";function Q(t,e,n,s,r){const a=r||s;return $(t)?ne(a.ok||s.ok,t,e,n):Y(a.failed||s.failed,e,n)}const X=function(t){const e=[],n=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),n.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(n.messageField||p)+" 作为错误消息");break}const s=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),s.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(s.dataField||A)+" 作为响应数据,读取 "+(s.messageField||p)+" 作为提示消息"),s.statusField&&e.push(" 当 "+s.statusField+" 为 "+(s.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),s.ignoreMessage&&e.push(" 并忽略以下消息:"+s.ignoreMessage);break}return e.join(`
2
- `)};function Y(t,e,n){const s=t||{resolve:"json",messageField:p},r={ok:!1,code:e,message:n,data:null};switch(s.resolve){case"body":r.message=k(n)||n;break;case"json":const{code:a,message:o}=Z(n,s.statusField,s.messageField);r.code=a||e,r.message=k(n)||o;break}return r}function Z(t,e,n=p){if(!C(t))return{message:""};const s=j(t);return!s||!D(s)?{message:t}:{code:e?O(s,e):"",message:O(s,n)||t}}function O(t,e){const n=Array.isArray(e)?e:[e];for(const s of n)if(s in t)return ee(t[s]);return""}function ee(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const te=/<title>([^<]+)<\/title>/i,se=/<message>([^<]+)<\/message>/i;function k(t){const e=t.match(te);if(e)return e[1];const n=t.match(se);return n?n[1]:""}function ne(t,e,n,s){const r=t||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(e===202||e===204||!s)return a;if(r.resolve==="body")return a.data=C(s)?j(s):s,a;const o=j(s);if(!o||!D(o))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;const i=r.statusField,c=r.statusOKValue||"",d=r.dataField||A,l=r.messageField||p,u=r.ignoreMessage||"";if(i&&!(i in o))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+i,a;const g=i?o[i]+"":"";return a.ok=i?g===c:!0,a.code=g||n,a.data=d===!0?o:d in o?o[d]:null,a.message=O(o,l),u&&a.message&&(Array.isArray(u)&&u.includes(a.message)||typeof u=="string"&&a.message===u)&&(a.message=""),a}function $(t){return t>=200&&t<400}async function x(t,e,n,s,r){const a=r||0,o=Math.max(0,Math.min(10,(s==null?void 0:s.maxRetry)??n.get("maxRetry")??0)),i=(s==null?void 0:s.retryResolve)??n.get("retryResolve"),c=n.get("logHandler")||M;c({type:"prepear",url:e,method:(s==null?void 0:s.method)||"GET",retry:a,maxRetry:o,message:a===0?"start":`retry ${a}/${o} start`,headers:s==null?void 0:s.headers,options:s});const d=Date.now(),l=await t(e,n,s),u=l.status,g=Date.now()-d,y=`[cost ${g}][${u}] ${u<0?l.body:""}`;c({type:"finished",url:e,method:l.method,retry:a,maxRetry:o,message:a===0?`finish ${y}`:`retry ${a}/${o} finish ${y}`,response:l,headers:l.headers,cost:g});const w=$(u);if(!o||i==="network"&&u>0||i==="status"&&w||Array.isArray(i)&&!i.includes(u)||typeof i=="function"&&i(l,a)!==!0||a>=o)return l;const h=(s==null?void 0:s.retryInterval)??n.get("retryInterval")??1e3;return await q(Math.max(100,h==="2EB"?Math.pow(2,a)*1e3:typeof h=="function"?h(a+1)||0:h)),await x(t,e,n,s,a+1)}function ae(t,e,n,s){var o,i;if(t.status<0)return E({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,n,s);$(t.status)||(o=n.get("errorHandler"))==null||o(t.status,t.method,e);const r={...Q(t.status,t.statusText,t.body,n.get("responseRule"),s==null?void 0:s.responseRule),status:t.status,headers:Object.fromEntries(Object.entries(t.headers||{}).map(([c,d])=>[c.toLowerCase(),d]))};(i=n.get("responseHandler"))==null||i({...r},t.method,e);const a=r.ok?r.message:`${t.method} ${e} [${r.code||t.statusText}] ${r.message||t.statusText}`;return E(r,a,t.method,e,n,s)}function E(t,e,n,s,r,a){const o=r.get("message"),i=o===!1||(a==null?void 0:a.message)===!1?!1:(a==null?void 0:a.message)||o;if(i!==!1){const c=typeof i=="function"?i(t,n,s,e):e;c instanceof Error?r.showMessage(!0,c.message):c&&typeof c=="object"&&"message"in c?r.showMessage(!1,c.message):r.showMessage(!t.ok,c)}return t}class U{constructor(e){f(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!R(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.startsWith("/")?F(e):F(e,this.config.baseURL)}showMessage(e,n){this.config.messageHandler&&n&&this.config.messageHandler(e,n)}}class re{constructor(e=500){f(this,"ttl");f(this,"cache");this.cache={},this.ttl=Math.max(e,0)}getKey(e,n){const s=Object.keys(n||{}).sort().map(r=>`${r}#${n==null?void 0:n[r]}`);return e+s.join(",")}updateTTL(e){this.ttl=Math.max(e,0)}get(e){if(this.ttl===0)return null;const n=this.cache[e];return n?n.ttl<Date.now()?(delete this.cache[e],null):n.res:null}set(e,n){this.ttl!==0&&(this.cache[e]={ttl:Date.now()+this.ttl,res:n})}}function oe(t,e,n,s){if(e.ok&&!W(e.data)&&s){const r=_(s,"响应数据未能正确识别");return r.guard(e.data)||(console.error("ResponseCheckFaild",t,e.data),n.showMessage(!0,`${t} ${r.message}`),e.data=null),e}return e}class ie{constructor(e,n){f(this,"agent");f(this,"config");f(this,"cache");this.config=new U(n),this.agent=e,this.cache=new re(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async exec(e,n){return await this.agent(e,this.config,n)}async guard(e,n,s){return oe(e,n,this.config,s)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,n){const s=Object.assign({},n||null);return s.method="HEAD",this.guard(e,await this.exec(e,s),null)}async get(e,n,s){const r=Object.assign({},s||null);r.method="GET";const a=this.cache.getKey(e,r.params),o=this.cache.get(a);if(o)return this.guard(e,await o,n||null);const i=this.exec(e,r);return this.cache.set(a,i),this.guard(e,await i,n||null)}async post(e,n,s,r){const a=Object.assign({},r||null);return a.method="POST",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async del(e,n,s){const r=Object.assign({},s||null);return r.method="DELETE",this.guard(e,await this.exec(e,r),n||null)}async put(e,n,s,r){const a=Object.assign({},r||null);return a.method="PUT",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async patch(e,n,s,r){const a=Object.assign({},r||null);return a.method="PATCH",a.body=n,this.guard(e,await this.exec(e,a),s||null)}}const ce="1.6.2";exports.Et=z;exports.NetRequestHandler=ie;exports.RequestGlobalConfig=U;exports.Support=b;exports.U=R;exports.Wt=M;exports.convertOptions=H;exports.getResponseRulesDescription=X;exports.handleResponse=ae;exports.he=J;exports.retryRequest=x;exports.version=ce;