@seayoo-web/request 3.2.0 → 3.3.1

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
@@ -121,7 +121,7 @@ setConfig({ timeout: 10000 });
121
121
 
122
122
  类型:"omit" | "same-origin" | "include"
123
123
 
124
- 说明:是否携带用户认证信息(cookie, basic http auth 等),默认 "same-orgin",当需要跨域发送 cookie 时可以设置为 include;当需要明确忽略 cookie(比如认证信息已经放入自定义 header 头)时,可以设置为 omit;
124
+ 说明:是否携带用户认证信息(cookie, basic http auth 等),默认 "same-origin",当需要跨域发送 cookie 时可以设置为 include;当需要明确忽略 cookie(比如认证信息已经放入自定义 header 头)时,可以设置为 omit;
125
125
 
126
126
  仅浏览器环境有效;如果运行环境不支持 fetch 则 omit 无效;
127
127
 
@@ -135,7 +135,7 @@ setConfig({ timeout: 10000 });
135
135
 
136
136
  类型:number
137
137
 
138
- 说明:用于控制 get 请求的缓冲时效,单位 ms,默认 500,设置为 0 则禁用缓冲
138
+ 说明:用于控制全局请求的缓冲时长,单位 ms,默认 500,设置为 0 则全局禁用缓冲。默认仅仅对 get 请求做缓冲处理。
139
139
 
140
140
  ### defaultTypeGuardMessage
141
141
 
@@ -361,6 +361,16 @@ sentryExtra: Record<string, unknown>
361
361
 
362
362
  同全局配置,仅本次请求有效,默认跟随全局设置
363
363
 
364
+ ### cacheTTL
365
+
366
+ 同全局配置,仅本次请求有效,默认跟随全局设置
367
+
368
+ ### cacheResolve
369
+
370
+ 类型:() => string | false
371
+
372
+ 说明:用于返回请求缓冲的 key,返回 false 或空字符串则不缓冲,返回非空字符串则作为缓冲 key,默认仅仅对 get 请求做缓冲处理
373
+
364
374
  ## 响应内容
365
375
 
366
376
  所有请求均返回同样的结构(包括网络错误或状态码错误时)其结构字段如下
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./retry-CsPcCrZK.cjs"),m=require("./request.fetch-Clr0F0uQ.cjs"),y=async function(t,s,e){return r.handleResponse(await r.retryRequest(p,t,s,e),t,s,e)};async function E(t,s,e,n){const o=e==null?void 0:e.body,i=(e==null?void 0:e.method)==="PUT"?"PUT":"POST";if(s instanceof Blob){const u=new r.RequestGlobalConfig(n),f=await p(t,u,{...e,method:i,body:s});return r.handleResponse(f,t,u,e)}const c=new FormData,d={...s};o instanceof Object&&Object.entries(o).forEach(([u,f])=>{f instanceof Blob?d[u]=f:Array.isArray(f)?f.forEach((a,h)=>{c.append(`${u}[${h}]`,String(a))}):c.append(u,String(f))});for(const u in d)c.append(u,d[u]);const b=new r.RequestGlobalConfig(n),R=await p(t,b,{...e,method:i,body:c});return r.handleResponse(R,t,b,e)}const p=async function(t,s,e){const n=await r.convertOptions(t,s,e),o=n.method,i=e==null?void 0:e.onUploadProgress,c=r.ge(n.url,n.params);return await new Promise(d=>{let b=null,R=!1;const u=function(){R||(a.abort(),R=!0)};function f(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",u)}const a=new XMLHttpRequest;let h=!1;if(a.open(o,c,!0),i){let g=1;a.upload.addEventListener("progress",w=>{g=w.total,i({total:w.total,loaded:w.loaded})}),a.addEventListener("load",()=>{i({loaded:g,total:g})})}a.addEventListener("load",()=>{const g=a.status;f(),d({url:c,method:o,status:g,statusText:a.statusText,headers:T(a),body:o==="HEAD"||g===204?"":a.responseText})}),a.addEventListener("error",g=>{f(),d({url:c,method:o,status:a.status||-1,statusText:a.statusText||r.RequestInternalError.NetworkError,body:"",rawError:g})},!0),a.addEventListener("abort",()=>{f(),d({url:c,method:o,status:h?-1:0,statusText:h?r.RequestInternalError.Timeout:r.RequestInternalError.Aborted,body:""})}),Object.entries(n.headers).forEach(([g,w])=>{a.setRequestHeader(g,w)}),n.credentials==="include"&&(a.withCredentials=!0),a.send(n.body||void 0),n.abort&&n.abort.addEventListener("abort",u),n.timeout>0&&(b=setTimeout(function(){h=!0,u()},n.timeout))})};function T(t){const s={};if(!t)return s;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
2
- `).forEach(n=>{const o=n.trim();if(!o)return;const i=o.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 o=e.callback+"";if(!t)return null;const i=r.ge(t,e,!0);return new Promise(c=>{n[o]=function(d){if(o in window&&delete n[o],s(d))return d;console.warn("response type check failed",t,d),c(null)},r.ce(i).catch(function(){c(null),delete n[o]})})}async function j(t,s,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await r.ce(r.ge(t,e,!0)).then(()=>{const o=n[e.var+""];return s(o)?o:(console.warn("response type check failed",t,o),null)}).catch(()=>null):null}const x=async function(t,s,e){return await E(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 q(t){if(!r.jt.window)throw new Error("Default Module Only Support In Browser");return r.jt.fetch?new r.NetRequestHandler(m.fetchRequest,t):new r.NetRequestHandler(y,t)}const l=q(),C=l.setConfig,L=l.request,S=l.head,k=l.get,v=l.post,D=l.del,U=l.put,O=l.patch;exports.RequestInternalError=r.RequestInternalError;exports.getResponseRulesDescription=r.getResponseRulesDescription;exports.NetRequest=q;exports.del=D;exports.get=k;exports.head=S;exports.jsonp=H;exports.jsonx=j;exports.patch=O;exports.post=v;exports.put=U;exports.request=L;exports.setGlobalConfig=C;exports.upload=x;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./retry-sL4_1f7S.cjs"),y=require("./request.fetch-0OA7qu9S.cjs"),m=async function(t,s,e){return r.handleResponse(await r.retryRequest(R,t,s,e),t,s,e)};async function E(t,s,e,n){const o=e?.body,u=e?.method==="PUT"?"PUT":"POST";if(s instanceof Blob){const l=new r.RequestGlobalConfig(n),f=await R(t,l,{...e,method:u,body:s});return r.handleResponse(f,t,l,e)}const c=new FormData,d={...s};o instanceof Object&&Object.entries(o).forEach(([l,f])=>{f instanceof Blob?d[l]=f:Array.isArray(f)?f.forEach((a,p)=>{c.append(`${l}[${p}]`,String(a))}):c.append(l,String(f))});for(const l in d)c.append(l,d[l]);const b=new r.RequestGlobalConfig(n),w=await R(t,b,{...e,method:u,body:c});return r.handleResponse(w,t,b,e)}const R=async function(t,s,e){const n=await r.convertOptions(t,s,e),o=n.method,u=e?.onUploadProgress,c=r.ye(n.url,n.params);return await new Promise(d=>{let b=null,w=!1;const l=function(){w||(a.abort(),w=!0)};function f(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",l)}const a=new XMLHttpRequest;let p=!1;if(a.open(o,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",()=>{const g=a.status;f(),d({url:c,method:o,status:g,statusText:a.statusText,headers:T(a),body:o==="HEAD"||g===204?"":a.responseText})}),a.addEventListener("error",g=>{f(),d({url:c,method:o,status:a.status||-1,statusText:a.statusText||r.RequestInternalError.NetworkError,body:"",rawError:g})},!0),a.addEventListener("abort",()=>{f(),d({url:c,method:o,status:p?-1:0,statusText:p?r.RequestInternalError.Timeout:r.RequestInternalError.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",l),n.timeout>0&&(b=setTimeout(function(){p=!0,l()},n.timeout))})};function T(t){const s={};if(!t)return s;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
2
+ `).forEach(n=>{const o=n.trim();if(!o)return;const u=o.split(":"),c=u[0].trim();c&&(s[c]=(u[1]||"").trim())}),s}async function H(t,s,e={}){const n=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const o=e.callback+"";if(!t)return null;const u=r.ye(t,e,!0);return new Promise(c=>{n[o]=function(d){if(o in window&&delete n[o],s(d))return d;console.warn("response type check failed",t,d),c(null)},r.ue(u).catch(function(){c(null),delete n[o]})})}async function C(t,s,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await r.ue(r.ye(t,e,!0)).then(()=>{const o=n[e.var+""];return s(o)?o:(console.warn("response type check failed",t,o),null)}).catch(()=>null):null}const x=async function(t,s,e){return await E(t,s,e,{baseURL:i.getConfig("baseURL"),logHandler:i.getConfig("logHandler"),errorHandler:i.getConfig("errorHandler"),requestTransformer:i.getConfig("requestTransformer"),messageHandler:i.getConfig("messageHandler"),responseHandler:i.getConfig("responseHandler")})};function q(t){if(!r.Ct.window)throw new Error("Default Module Only Support In Browser");return r.Ct.fetch?new r.NetRequestHandler(y.fetchRequest,t):new r.NetRequestHandler(m,t)}const i=q(),j=i.setConfig,L=i.request,S=i.head,k=i.get,v=i.post,D=i.del,U=i.put,O=i.patch;exports.RequestInternalError=r.RequestInternalError;exports.getResponseRulesDescription=r.getResponseRulesDescription;exports.NetRequest=q;exports.del=D;exports.get=k;exports.head=S;exports.jsonp=H;exports.jsonx=C;exports.patch=O;exports.post=v;exports.put=U;exports.request=L;exports.setGlobalConfig=j;exports.upload=x;
package/dist/index.js CHANGED
@@ -1,133 +1,133 @@
1
- import { h as p, r as x, R as T, c as C, g as R, a as m, b as q, j as E, N as H } from "./retry-DQlh3z7q.js";
2
- import { d as K } from "./retry-DQlh3z7q.js";
3
- import { f as L } from "./request.fetch-D8zNsNGx.js";
4
- const j = async function(t, a, e) {
5
- return p(await x(y, t, a, e), t, a, e);
1
+ import { h as m, r as x, R as T, c as C, y as R, a as w, u as q, C as E, N as H } from "./retry-vMhW20_a.js";
2
+ import { g as K } from "./retry-vMhW20_a.js";
3
+ import { f as L } from "./request.fetch-BJaP3VPV.js";
4
+ const k = async function(t, o, e) {
5
+ return m(await x(y, t, o, e), t, o, e);
6
6
  };
7
- async function k(t, a, e, n) {
8
- const r = e == null ? void 0 : e.body, i = (e == null ? void 0 : e.method) === "PUT" ? "PUT" : "POST";
9
- if (a instanceof Blob) {
10
- const l = new T(n), u = await y(t, l, {
7
+ async function S(t, o, e, n) {
8
+ const r = e?.body, l = e?.method === "PUT" ? "PUT" : "POST";
9
+ if (o instanceof Blob) {
10
+ const i = new T(n), d = await y(t, i, {
11
11
  ...e,
12
- method: i,
13
- body: a
12
+ method: l,
13
+ body: o
14
14
  });
15
- return p(u, t, l, e);
15
+ return m(d, t, i, e);
16
16
  }
17
- const s = new FormData(), d = { ...a };
18
- r instanceof Object && Object.entries(r).forEach(([l, u]) => {
19
- u instanceof Blob ? d[l] = u : Array.isArray(u) ? u.forEach((o, g) => {
20
- s.append(`${l}[${g}]`, String(o));
21
- }) : s.append(l, String(u));
17
+ const a = new FormData(), u = { ...o };
18
+ r instanceof Object && Object.entries(r).forEach(([i, d]) => {
19
+ d instanceof Blob ? u[i] = d : Array.isArray(d) ? d.forEach((s, g) => {
20
+ a.append(`${i}[${g}]`, String(s));
21
+ }) : a.append(i, String(d));
22
22
  });
23
- for (const l in d)
24
- s.append(l, d[l]);
25
- const b = new T(n), w = await y(t, b, {
23
+ for (const i in u)
24
+ a.append(i, u[i]);
25
+ const b = new T(n), p = await y(t, b, {
26
26
  ...e,
27
- method: i,
28
- body: s
27
+ method: l,
28
+ body: a
29
29
  });
30
- return p(w, t, b, e);
30
+ return m(p, t, b, e);
31
31
  }
32
- const y = async function(t, a, e) {
33
- const n = await C(t, a, e), r = n.method, i = e == null ? void 0 : e.onUploadProgress, s = R(n.url, n.params);
34
- return await new Promise((d) => {
35
- let b = null, w = !1;
36
- const l = function() {
37
- w || (o.abort(), w = !0);
32
+ const y = async function(t, o, e) {
33
+ const n = await C(t, o, e), r = n.method, l = e?.onUploadProgress, a = R(n.url, n.params);
34
+ return await new Promise((u) => {
35
+ let b = null, p = !1;
36
+ const i = function() {
37
+ p || (s.abort(), p = !0);
38
38
  };
39
- function u() {
40
- b !== null && clearTimeout(b), n.abort && n.abort.removeEventListener("abort", l);
39
+ function d() {
40
+ b !== null && clearTimeout(b), n.abort && n.abort.removeEventListener("abort", i);
41
41
  }
42
- const o = new XMLHttpRequest();
42
+ const s = new XMLHttpRequest();
43
43
  let g = !1;
44
- if (o.open(r, s, !0), i) {
44
+ if (s.open(r, a, !0), l) {
45
45
  let f = 1;
46
- o.upload.addEventListener("progress", (h) => {
47
- f = h.total, i({ total: h.total, loaded: h.loaded });
48
- }), o.addEventListener("load", () => {
49
- i({ loaded: f, total: f });
46
+ s.upload.addEventListener("progress", (h) => {
47
+ f = h.total, l({ total: h.total, loaded: h.loaded });
48
+ }), s.addEventListener("load", () => {
49
+ l({ loaded: f, total: f });
50
50
  });
51
51
  }
52
- o.addEventListener("load", () => {
53
- const f = o.status;
54
- u(), d({
55
- url: s,
52
+ s.addEventListener("load", () => {
53
+ const f = s.status;
54
+ d(), u({
55
+ url: a,
56
56
  method: r,
57
57
  status: f,
58
- statusText: o.statusText,
59
- headers: S(o),
60
- body: r === "HEAD" || f === 204 ? "" : o.responseText
58
+ statusText: s.statusText,
59
+ headers: U(s),
60
+ body: r === "HEAD" || f === 204 ? "" : s.responseText
61
61
  });
62
- }), o.addEventListener(
62
+ }), s.addEventListener(
63
63
  "error",
64
64
  (f) => {
65
- u(), d({
66
- url: s,
65
+ d(), u({
66
+ url: a,
67
67
  method: r,
68
- status: o.status || -1,
69
- statusText: o.statusText || m.NetworkError,
68
+ status: s.status || -1,
69
+ statusText: s.statusText || w.NetworkError,
70
70
  body: "",
71
71
  rawError: f
72
72
  });
73
73
  },
74
74
  !0
75
- ), o.addEventListener("abort", () => {
76
- u(), d({
77
- url: s,
75
+ ), s.addEventListener("abort", () => {
76
+ d(), u({
77
+ url: a,
78
78
  method: r,
79
79
  status: g ? -1 : 0,
80
80
  // 设置为 0 可以防止自动重试的默认策略
81
- statusText: g ? m.Timeout : m.Aborted,
81
+ statusText: g ? w.Timeout : w.Aborted,
82
82
  body: ""
83
83
  });
84
84
  }), Object.entries(n.headers).forEach(([f, h]) => {
85
- o.setRequestHeader(f, h);
86
- }), n.credentials === "include" && (o.withCredentials = !0), o.send(n.body || void 0), n.abort && n.abort.addEventListener("abort", l), n.timeout > 0 && (b = setTimeout(function() {
87
- g = !0, l();
85
+ s.setRequestHeader(f, h);
86
+ }), n.credentials === "include" && (s.withCredentials = !0), s.send(n.body || void 0), n.abort && n.abort.addEventListener("abort", i), n.timeout > 0 && (b = setTimeout(function() {
87
+ g = !0, i();
88
88
  }, n.timeout));
89
89
  });
90
90
  };
91
- function S(t) {
92
- const a = {};
91
+ function U(t) {
92
+ const o = {};
93
93
  if (!t)
94
- return a;
94
+ return o;
95
95
  const e = t.getAllResponseHeaders();
96
96
  return e && e !== "null" && e.replace(/\r/g, "").split(`
97
97
  `).forEach((n) => {
98
98
  const r = n.trim();
99
99
  if (!r)
100
100
  return;
101
- const i = r.split(":"), s = i[0].trim();
102
- s && (a[s] = (i[1] || "").trim());
103
- }), a;
101
+ const l = r.split(":"), a = l[0].trim();
102
+ a && (o[a] = (l[1] || "").trim());
103
+ }), o;
104
104
  }
105
- async function O(t, a, e = {}) {
105
+ async function O(t, o, e = {}) {
106
106
  const n = window;
107
107
  "callback" in e || (e.callback = "jsonxData" + Math.random().toString(16).slice(2));
108
108
  const r = e.callback + "";
109
109
  if (!t)
110
110
  return null;
111
- const i = R(t, e, !0);
112
- return new Promise((s) => {
113
- n[r] = function(d) {
114
- if (r in window && delete n[r], a(d))
115
- return d;
116
- console.warn("response type check failed", t, d), s(null);
117
- }, q(i).catch(function() {
118
- s(null), delete n[r];
111
+ const l = R(t, e, !0);
112
+ return new Promise((a) => {
113
+ n[r] = function(u) {
114
+ if (r in window && delete n[r], o(u))
115
+ return u;
116
+ console.warn("response type check failed", t, u), a(null);
117
+ }, q(l).catch(function() {
118
+ a(null), delete n[r];
119
119
  });
120
120
  });
121
121
  }
122
- async function P(t, a, e = {}) {
122
+ async function P(t, o, e = {}) {
123
123
  const n = window;
124
124
  return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), t ? await q(R(t, e, !0)).then(() => {
125
125
  const r = n[e.var + ""];
126
- return a(r) ? r : (console.warn("response type check failed", t, r), null);
126
+ return o(r) ? r : (console.warn("response type check failed", t, r), null);
127
127
  }).catch(() => null) : null;
128
128
  }
129
- const A = async function(t, a, e) {
130
- return await k(t, a, e, {
129
+ const A = async function(t, o, e) {
130
+ return await S(t, o, e, {
131
131
  baseURL: c.getConfig("baseURL"),
132
132
  logHandler: c.getConfig("logHandler"),
133
133
  errorHandler: c.getConfig("errorHandler"),
@@ -136,15 +136,15 @@ const A = async function(t, a, e) {
136
136
  responseHandler: c.getConfig("responseHandler")
137
137
  });
138
138
  };
139
- function U(t) {
139
+ function j(t) {
140
140
  if (!E.window)
141
141
  throw new Error("Default Module Only Support In Browser");
142
- return E.fetch ? new H(L, t) : new H(j, t);
142
+ return E.fetch ? new H(L, t) : new H(k, t);
143
143
  }
144
- const c = U(), M = c.setConfig, N = c.request, B = c.head, X = c.get, F = c.post, G = c.del, I = c.put, $ = c.patch;
144
+ const c = j(), M = c.setConfig, N = c.request, B = c.head, X = c.get, F = c.post, G = c.del, I = c.put, $ = c.patch;
145
145
  export {
146
- U as NetRequest,
147
- m as RequestInternalError,
146
+ j as NetRequest,
147
+ w as RequestInternalError,
148
148
  G as del,
149
149
  X as get,
150
150
  K as getResponseRulesDescription,
package/dist/node.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-CsPcCrZK.cjs"),y=require("./request.fetch-Clr0F0uQ.cjs"),b=require("node:http"),g=require("node:https"),E=async function(r,a,c){return e.handleResponse(await e.retryRequest(w,r,a,c),r,a,c)},w=async function(r,a,c){const t=await e.convertOptions(r,a,c);if(!e.At(t.url))return{url:t.url,method:t.method,status:-1,statusText:e.RequestInternalError.URLFormatError,headers:{},body:""};const R=/^https:\/\//i.test(t.url)?g:b,u=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>u.searchParams.set(n,i[n]));const q=t.method==="HEAD";return new Promise(n=>{const d=R.request(u,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(o){const m=[];o.on("data",h=>m.push(h)),o.on("end",()=>{const h=e.fromEntries(Object.entries(o.headers).map(([f,l])=>[f.toLowerCase(),Array.isArray(l)?l.join(","):l]));n({url:u.toString(),method:t.method,status:o.statusCode||-1,statusText:o.statusMessage||e.RequestInternalError.Unknown,headers:h,body:q||o.statusCode===204?"":Buffer.concat(m).toString("utf-8")})})});d.on("error",o=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.NetworkError,body:"",rawError:o})}),d.on("timeout",()=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.Timeout,body:""})}),t.body&&d.write(t.body),d.end()})};function p(r){return e.jt.fetch?new e.NetRequestHandler(y.fetchRequest,r):new e.NetRequestHandler(E,r)}const s=p(),j=s.setConfig,C=s.head,I=s.get,N=s.post,S=s.del,T=s.put,O=s.patch;exports.RequestInternalError=e.RequestInternalError;exports.getResponseRulesDescription=e.getResponseRulesDescription;exports.NetRequest=p;exports.del=S;exports.get=I;exports.head=C;exports.patch=O;exports.post=N;exports.put=T;exports.setGlobalConfig=j;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-sL4_1f7S.cjs"),y=require("./request.fetch-0OA7qu9S.cjs"),b=require("node:http"),g=require("node:https"),E=async function(r,a,c){return e.handleResponse(await e.retryRequest(w,r,a,c),r,a,c)},w=async function(r,a,c){const t=await e.convertOptions(r,a,c);if(!e.Et(t.url))return{url:t.url,method:t.method,status:-1,statusText:e.RequestInternalError.URLFormatError,headers:{},body:""};const R=/^https:\/\//i.test(t.url)?g:b,u=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>u.searchParams.set(n,i[n]));const q=t.method==="HEAD";return new Promise(n=>{const d=R.request(u,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(o){const m=[];o.on("data",h=>m.push(h)),o.on("end",()=>{const h=e.fromEntries(Object.entries(o.headers).map(([f,l])=>[f.toLowerCase(),Array.isArray(l)?l.join(","):l]));n({url:u.toString(),method:t.method,status:o.statusCode||-1,statusText:o.statusMessage||e.RequestInternalError.Unknown,headers:h,body:q||o.statusCode===204?"":Buffer.concat(m).toString("utf-8")})})});d.on("error",o=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.NetworkError,body:"",rawError:o})}),d.on("timeout",()=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.Timeout,body:""})}),t.body&&d.write(t.body),d.end()})};function p(r){return e.Ct.fetch?new e.NetRequestHandler(y.fetchRequest,r):new e.NetRequestHandler(E,r)}const s=p(),C=s.setConfig,I=s.head,N=s.get,S=s.post,T=s.del,j=s.put,O=s.patch;exports.RequestInternalError=e.RequestInternalError;exports.getResponseRulesDescription=e.getResponseRulesDescription;exports.NetRequest=p;exports.del=T;exports.get=N;exports.head=I;exports.patch=O;exports.post=S;exports.put=j;exports.setGlobalConfig=C;
package/dist/node.js CHANGED
@@ -1,11 +1,11 @@
1
- import { h as b, r as q, c as w, A as g, a as d, f as E, N as f, j } from "./retry-DQlh3z7q.js";
2
- import { d as J } from "./retry-DQlh3z7q.js";
3
- import { f as x } from "./request.fetch-D8zNsNGx.js";
4
- import A from "node:http";
5
- import C from "node:https";
6
- const N = async function(o, a, u) {
7
- return b(await q(T, o, a, u), o, a, u);
8
- }, T = async function(o, a, u) {
1
+ import { h as b, r as q, c as w, E as g, a as d, f as E, N as f, C } from "./retry-vMhW20_a.js";
2
+ import { g as J } from "./retry-vMhW20_a.js";
3
+ import { f as x } from "./request.fetch-BJaP3VPV.js";
4
+ import N from "node:http";
5
+ import T from "node:https";
6
+ const j = async function(o, a, u) {
7
+ return b(await q(L, o, a, u), o, a, u);
8
+ }, L = async function(o, a, u) {
9
9
  const t = await w(o, a, u);
10
10
  if (!g(t.url))
11
11
  return {
@@ -16,7 +16,7 @@ const N = async function(o, a, u) {
16
16
  headers: {},
17
17
  body: ""
18
18
  };
19
- const R = /^https:\/\//i.test(t.url) ? C : A, n = new URL(t.url), i = t.params;
19
+ const R = /^https:\/\//i.test(t.url) ? T : N, n = new URL(t.url), i = t.params;
20
20
  i instanceof Object && Object.keys(i).forEach((r) => n.searchParams.set(r, i[r]));
21
21
  const l = t.method === "HEAD";
22
22
  return new Promise((r) => {
@@ -64,12 +64,12 @@ const N = async function(o, a, u) {
64
64
  }), t.body && c.write(t.body), c.end();
65
65
  });
66
66
  };
67
- function L(o) {
68
- return j.fetch ? new f(x, o) : new f(N, o);
67
+ function O(o) {
68
+ return C.fetch ? new f(x, o) : new f(j, o);
69
69
  }
70
- const s = L(), k = s.setConfig, B = s.head, D = s.get, P = s.post, F = s.del, G = s.put, I = s.patch;
70
+ const s = O(), k = s.setConfig, B = s.head, D = s.get, P = s.post, F = s.del, G = s.put, I = s.patch;
71
71
  export {
72
- L as NetRequest,
72
+ O as NetRequest,
73
73
  d as RequestInternalError,
74
74
  F as del,
75
75
  D as get,
@@ -0,0 +1 @@
1
+ "use strict";const r=require("./retry-sL4_1f7S.cjs"),E=async function(s,a,i){return r.handleResponse(await r.retryRequest(w,s,a,i),s,a,i)},w=async function(s,a,i){const t=await r.convertOptions(s,a,i),c=new URL(t.url),u=t.params;u instanceof Object&&Object.keys(u).forEach(e=>c.searchParams.set(e,u[e]));const o=r.Ct.AbortController?new AbortController:null;function l(){o&&!o.signal.aborted&&o.abort()}t.abort&&t.abort.addEventListener("abort",l);let d=!1;const h=t.timeout>0?setTimeout(function(){d=!0,l()},t.timeout):null,f=t.method==="HEAD";return await fetch(c,{method:t.method,headers:Object.keys(t.headers).length>0?new Headers(t.headers):void 0,body:t.body,credentials:t.credentials,signal:o?.signal,redirect:"follow"}).then(async e=>{const n={url:c.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:r.fromEntries([...e.headers.entries()])},b=f||e.status===204?"":await e.text().catch(m=>m);return b instanceof Error?{...n,body:"",statusText:r.RequestInternalError.Unknown,rawError:b}:{...n,body:b}}).catch(e=>{const n=o?.signal.aborted;return{url:c.toString(),method:t.method,status:n&&!d?0:-1,statusText:d?r.RequestInternalError.Timeout:n?r.RequestInternalError.Aborted:r.RequestInternalError.NetworkError,body:"",rawError:e}}).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",l)})};exports.fetchRequest=E;
@@ -1,47 +1,47 @@
1
- import { h as w, r as y, c as E, j as T, f as R, a as c } from "./retry-DQlh3z7q.js";
2
- const x = async function(s, o, n) {
3
- return w(await y(g, s, o, n), s, o, n);
4
- }, g = async function(s, o, n) {
5
- const t = await E(s, o, n), i = new URL(t.url), u = t.params;
1
+ import { h as w, r as y, c as E, C as T, f as R, a as c } from "./retry-vMhW20_a.js";
2
+ const x = async function(a, s, n) {
3
+ return w(await y(g, a, s, n), a, s, n);
4
+ }, g = async function(a, s, n) {
5
+ const t = await E(a, s, n), i = new URL(t.url), u = t.params;
6
6
  u instanceof Object && Object.keys(u).forEach((e) => i.searchParams.set(e, u[e]));
7
7
  const r = T.AbortController ? new AbortController() : null;
8
8
  function d() {
9
9
  r && !r.signal.aborted && r.abort();
10
10
  }
11
11
  t.abort && t.abort.addEventListener("abort", d);
12
- let b = !1;
13
- const l = t.timeout > 0 ? setTimeout(function() {
14
- b = !0, d();
12
+ let l = !1;
13
+ const h = t.timeout > 0 ? setTimeout(function() {
14
+ l = !0, d();
15
15
  }, t.timeout) : null, f = t.method === "HEAD";
16
16
  return await fetch(i, {
17
17
  method: t.method,
18
18
  headers: Object.keys(t.headers).length > 0 ? new Headers(t.headers) : void 0,
19
19
  body: t.body,
20
20
  credentials: t.credentials,
21
- signal: r == null ? void 0 : r.signal,
21
+ signal: r?.signal,
22
22
  redirect: "follow"
23
23
  }).then(async (e) => {
24
- const a = {
24
+ const o = {
25
25
  url: i.toString(),
26
26
  method: t.method,
27
27
  status: e.status,
28
28
  statusText: e.statusText,
29
29
  headers: R([...e.headers.entries()])
30
- }, h = f || e.status === 204 ? "" : await e.text().catch((m) => m);
31
- return h instanceof Error ? { ...a, body: "", statusText: c.Unknown, rawError: h } : { ...a, body: h };
30
+ }, b = f || e.status === 204 ? "" : await e.text().catch((m) => m);
31
+ return b instanceof Error ? { ...o, body: "", statusText: c.Unknown, rawError: b } : { ...o, body: b };
32
32
  }).catch((e) => {
33
- const a = r == null ? void 0 : r.signal.aborted;
33
+ const o = r?.signal.aborted;
34
34
  return {
35
35
  url: i.toString(),
36
36
  method: t.method,
37
- status: a && !b ? 0 : -1,
37
+ status: o && !l ? 0 : -1,
38
38
  // 设置为 0 可以防止自动重试的默认策略
39
- statusText: b ? c.Timeout : a ? c.Aborted : c.NetworkError,
39
+ statusText: l ? c.Timeout : o ? c.Aborted : c.NetworkError,
40
40
  body: "",
41
41
  rawError: e
42
42
  };
43
43
  }).finally(() => {
44
- l !== null && clearTimeout(l), t.abort && t.abort.removeEventListener("abort", d);
44
+ h !== null && clearTimeout(h), t.abort && t.abort.removeEventListener("abort", d);
45
45
  });
46
46
  };
47
47
  export {
@@ -0,0 +1,3 @@
1
+ "use strict";const l=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),K="wx"in l&&R(l.wx)&&"getSystemInfo"in l.wx&&d(l.wx.getSystemInfo),k={wx:K,fetch:"fetch"in l&&d(l.fetch),window:"window"in l&&R(l.window)&&!K,requestAnimationFrame:"requestAnimationFrame"in l&&d(l.requestAnimationFrame),localStorage:"localStorage"in l&&R(l.localStorage)&&"getItem"in l.localStorage&&d(l.localStorage.getItem),sessionStorage:"sessionStorage"in l&&R(l.sessionStorage)&&"getItem"in l.sessionStorage&&d(l.sessionStorage.getItem),File:"File"in l&&d(l.File),Blob:"Blob"in l&&d(l.Blob),Proxy:"Proxy"in l&&d(l.Proxy),Request:"Request"in l&&d(l.Request),FormData:"FormData"in l&&d(l.FormData),TextDecoder:"TextDecoder"in l&&d(l.TextDecoder),ResizeObserver:"ResizeObserver"in l&&d(l.ResizeObserver),AbortController:"AbortController"in l&&d(l.AbortController),URLSearchParams:"URLSearchParams"in l&&d(l.URLSearchParams),EventSource:"EventSource"in l&&d(l.EventSource)};function d(t){return typeof t=="function"}function R(t){return typeof t=="object"&&t!==null}function re(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function X(){}function Y(t,e){const s={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)},n=`[${t}]`;return["log","error","warn"].forEach(r=>{const o=console[r];s[r]=(...i)=>{o.apply(console,[n,...i])}}),s}function oe(t){const e=t||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:e,enumerable:!1,configurable:!0}),"setPrototypeOf"in Object&&Object.setPrototypeOf(this,new.target.prototype),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,this.constructor)}}}const ie=/^(?:https?:)?\/\/.+$/i,ae=/^https?:\/\/.+$/i,le=/^\{[\d\D]*\}$/,ue=/^\[[\d\D]*\]$/;function ce(t){return typeof t=="string"}function N(t,e=!1){return e?ie.test(t):ae.test(t)}function he(t){return t==null}function Q(t,...e){return t!==null&&typeof t=="object"&&!(t instanceof Map)&&!(t instanceof Set)&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!Array.isArray(t)&&e.every(s=>s in t)}function y(t,...e){if(!t||typeof t!="object")return!1;const s=Object.getPrototypeOf(t);return s!==Object.prototype&&s!==null?!1:e.every(n=>n in t)}function U(t,e){return Array.isArray(t)&&t.every(s=>e(s))}function x(t){if(typeof t!="number"||Number.isNaN(t)||!Number.isFinite(t))return!1;if(Number.isInteger(t))return Number.isSafeInteger(t);if(t===0)return!0;const e=Math.abs(t);return e>=Number.EPSILON&&e<=Number.MAX_SAFE_INTEGER}function Z(t){return le.test(t)||ue.test(t)}function fe(t,e=20){const s=Math.max(e,10),n=[...t];return n.length<=s?t:n.slice(0,s-3).join("")+"..."}function F(t,e){try{const s=JSON.parse(t);return e?e(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);Y("LoadUtils");async function de(t){return await new Promise(function(e){const s=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("charset","utf-8"),n.onload=function(){s.removeChild(n),e(!0)},n.onerror=function(){s.removeChild(n),e(!1)},n.setAttribute("src",t),s.appendChild(n)})}function z(t){return Object.getOwnPropertyNames(t).forEach(function(e){delete t[e]}),t}const g=Y("Validator");function j(t){return t?`"${fe(t).replace(/"/g,'\\"')}"`:"empty string"}function T(t){return typeof t=="object"&&t&&"constructor"in t&&typeof t.constructor=="function"?t.constructor.name||"ClassInstance":Object.prototype.toString.call(t).replace(/(?:.+ |]$)/g,"")}function O(t){return typeof t=="bigint"}function a(t){return new Error(`${t?`${t}()`:"method"} is not allowed after locked`)}class M{_ps={};_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;pattern(e,s){if(this._locked)throw a("pattern");return this._ps[`#${e||"custom"}`]=s,this}url(e=!1){if(this._locked)throw a("url");return this._ps.url=e?/^(?:https?:)?\/\/.+$/i:/^https?:\/\/.+$/i,this}dataUri(){if(this._locked)throw a("dataUri");return this._ps.dataUri=/^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$/,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,ce)?(this._allow=e,z(this._ps)):y(s)&&(this._allow=Object.values(s).map(n=>`${n}`),z(this._ps)),this}disallow(...e){return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new M;return e._ps={...this._ps},e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=g.warn){if(e===void 0)return this._opt||(s("should be a string, but got undefined"),!1);if(e===null)return this._null||(s("should be a string, but got null"),!1);if(typeof e!="string")return s(`should be a string, but got ${typeof e}`),!1;if(this._allow.length>0)return this._allow.includes(e)||(s(`${j(e)} is not allowed, just support ${this._allow.map(j).join(", ")}`),!1);if(this._reject.length>0&&this._reject.some(r=>typeof r=="string"?r===e:r.test(e)))return s(`${j(e)} is not allowed`),!1;const n=Object.keys(this._ps);return n.length>0&&!n.some(r=>{const o=this._ps[r];return o instanceof RegExp?o.test(e):o(e)})?(s(`${j(e)} is not match pattern ${n.join(" | ")}`),!1):!0}}class L{_int=!1;_min=-1/0;_max=1/0;_allow=[];_reject=[];_infinite=!1;_unsafe=!1;_nan=!1;_locked=!1;_opt=!1;_null=!1;int(){if(this._locked)throw a("int");return this._int=!0,this}min(e){if(this._locked)throw a("min");return Number.isNaN(e)||(this._min=e),this}max(e){if(this._locked)throw a("max");return Number.isNaN(e)||(this._max=e),this}allowNaN(){if(this._locked)throw a("allowNaN");return this._nan=!0,this}allowInfinity(){if(this._locked)throw a("allowInfinity");return this._infinite=!0,this._unsafe=!0,this}unsafe(){if(this._locked)throw a("unsafe");return this._unsafe=!0,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,x)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>x(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new L;return e._int=this._int,e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._infinite=this._infinite,e._unsafe=this._unsafe,e._nan=this._nan,e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a number, but got undefined"),!1):e===null?this._null||(s("should be a number, but got null"),!1):typeof e!="number"?(s(`should be a number, but got ${typeof e}`),!1):Number.isNaN(e)?this._nan||(s("should be a number, but got NaN"),!1):!Number.isFinite(e)&&!this._infinite?(s("should be a number, but got Infinity"),!1):this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):this._int&&Math.ceil(e)!==e?(s(`${e} is not an integer`),!1):!x(e)&&!this._unsafe?(s(`${e} is not a safe number`),!1):e>=this._min&&e<=this._max||(s(`${e} is not in range [${this._min}, ${this._max}]`),!1)}}class P{_min=null;_max=null;_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,O)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>O(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new P;return e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a bigint, but got undefined"),!1):e===null?this._null||(s("should be a bigint, but got null"),!1):O(e)?this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):(this._min!==null?e>=this._min:!0)&&(this._max!==null?e<=this._max:!0)||(s(`${e} is not in range [${this._min===null?-1/0:this._min}, ${this._max===null?1/0:this._max}]`),!1):(s(`should be a bigint, but got ${typeof e}`),!1)}}class C{_locked=!1;_opt=!1;_null=!1;optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new C}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a boolean, but got undefined"),!1):e===null?this._null||(s("should be a boolean, but got null"),!1):typeof e!="boolean"?(s(`should be a boolean, but got ${typeof e}`),!1):!0}}class v{_shape;_plain=!1;_locked=!1;_opt=!1;_null=!1;constructor(e){this._shape=e}plain(){if(this._locked)throw a("plain");return this._plain=!0,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}get shape(){return{...this._shape}}clone(){const e=new v(this._shape);return e._plain=this._plain,e._locked=!1,e}match(e,s){return e in this._shape?this._shape[e].validate(s,X):!1}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a object, but got undefined"),!1):e===null?this._null||(s("should be a object, but got null"),!1):Q(e)?this._plain&&!y(e)?(s(`should be a plain object, but got ${T(e)}`),!1):Object.keys(this._shape).every(n=>this._shape[n].validate(e[n],(...r)=>{s(`[.${String(n)}]`,...r)})):(s(`should be a object, but got ${T(e)}`),!1)}}class I{_val;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new I(this._val)}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a record, but got undefined"),!1):e===null?this._null||(s("should be a record, but got null"),!1):y(e)?Object.keys(e).every(n=>this._val.validate(e[n],(...r)=>{s(`[:${n}]`,...r)})):(s(`should be a record, but got ${T(e)}`),!1)}}class q{_val;_min=0;_max=1/0;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new q(this._val);return e._min=this._min,e._max=this._max,e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a array, but got undefined"),!1):e===null?this._null||(s("should be a array, but got null"),!1):Array.isArray(e)?e.length<this._min||e.length>this._max?(this._min===this._max?s(`should be a array with length ${this._min}`):s(`should be a array with length between ${this._min} and ${this._max}`),!1):e.every((n,r)=>this._val.validate(n,(...o)=>{s(`[${r}]`,...o)})):(s(`should be a array, but got ${typeof e}`),!1)}}class D{_vs;_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new D(...this._vs)}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a tuple, but got undefined"),!1):e===null?this._null||(s("should be a tuple, but got null"),!1):Array.isArray(e)?e.length!==this._vs.length?(s(`should be a tuple with length ${this._vs.length}, but got ${e.length}`),!1):this._vs.every((n,r)=>n.validate(e[r],(...o)=>{s(`[idx:${r}]`,...o)})):(s(`should be a tuple, but got ${typeof e}`),!1)}}class B{_vs;_key="";_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}key(e){if(this._locked)throw a("key");return this._vs.every(s=>s instanceof v)?this._key=e:g.warn("union type key can only be used when all validators are ObjectValidator"),this}satisfies(){return this}lock(){return this._locked=!0,this}get validators(){return[...this._vs]}clone(){const e=new B(...this._vs);return e._key=this._key,e._locked=!1,e}validate(e,s=g.warn){if(e===void 0)return this._opt||(s("should be a union, but got undefined"),!1);if(e===null)return this._null||(s("should be a union, but got null"),!1);if(this._key&&Q(e)&&e){const r=e[this._key];if(r===void 0)return s(`key field "${this._key}" is not found`,e),!1;const o=this._vs.find(i=>i instanceof v&&i.match(this._key,r));return o?o.validate(e,s):(s(`key field "${this._key}" value is match union definition`,r),!1)}const n=this._vs.some(r=>r.validate(e,X));return n||s("value is not match union definition",e),n}}class E{_name="";_guard;_locked=!1;_opt=!1;_null=!1;constructor(e,s){this._name=e,this._guard=s}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new E(this._name,this._guard)}validate(e,s=g.warn){const n=this._name||"custom type";return e===void 0?this._opt||(s(`should be ${n}, but got undefined`),!1):e===null?this._null||(s(`should be ${n}, but got null`),!1):this._guard(e)||(s(`custom validation${this._name?`(${this._name})`:""} failed`),!1)}}function me(t,e){if(typeof t=="string"){if(!e)throw new Error("custom type guard must be defined");return new E(t,e)}return new E("",t)}const _e={shape(t){return t},define(t){return t},guard(t){return function(e){return t.validate(e)}},object(t){return new v(t)},record(t){return new I(t)},array(t){return new q(t)},tuple(...t){return new D(...t)},union(...t){return new B(...t)},string(){return new M},bool(){return new C},number(){return new L},bigint(){return new P},custom:me,unknown(){return{validate(t){return!0}}},never(){return{validate(t){return!1}}}},ge=t=>y(t)&&Object.keys(t).length===0;_e.custom("EmptyObject",ge);function pe(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function be(t,e=""){return!e||N(t,!0)?V(t):(V(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function V(t){return N(t,!0)?t.startsWith("http")?t:("location"in globalThis?location.protocol:"https:")+t:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+t.replace(/^\/+/,"")}function ye(t,e){const s={};return(t.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(n){const r=n.split("="),o=r[0],i=decodeURIComponent(r[1]||"");s[o]!==void 0?s[o]+=","+i:s[o]=i}),e!==!0?s[e]||"":s}function we(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const s=t.split("#"),n=s[0].split("?"),r=n[0],o=n.length>1?n[1]:"",i=s.length>1?"#"+s[1]:"",u=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!u.length||!o?s[0]+i:(u.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+o.replace(new RegExp("(?:^|&)(?:"+u.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+i)}function ke(t,e,s=!1){const n=typeof e=="string"?e:Object.keys(e).map(i=>`${i}=${encodeURIComponent(e[i])}`).join("&");if(!n)return t;const r=t.split("#");s&&(r[0]=we(r[0],(n.match(/([^=&#?]+)=[^&#]+/g)||[]).map(i=>i.replace(/=.+$/,""))));const o=r[0].indexOf("?")+1?"&":"?";return(r[0]+o+n+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}function ve(t){const e=t.match(/(?:\?|&)([^=]+)(?:&|$)/g);return e?e.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class $e{ttl;cache;constructor(e=500){this.cache={},this.ttl=Math.max(e,0)}getKey(e,s,n,r){if(e.toLowerCase()!=="get"&&!r)return"";const o=e.toLowerCase(),i=s.replace(/#.+/,""),u=i.replace(/\?.+/g,"");if(r){const h=r()||"";return h?`${u}_${o}_${h}`:""}const c=Object.assign(ye(i,!0),n),m=ve(i),f=Object.keys(c).sort().map(h=>`${h}#${c[h]}`);return`${u}_${o}_${f.join(",")}_${m.join(",")}`}updateTTL(e){this.ttl=Math.max(e,0)}get(e,s){if(Math.max(s??this.ttl,0)===0)return null;const r=this.cache[e];return r?r.ttl<Date.now()?(delete this.cache[e],null):r.res:null}set(e,s,n){const r=Math.max(n??this.ttl,0);r!==0&&(this.cache[e]={ttl:Date.now()+r,res:s})}}class ee{config={baseURL:"/",maxRetry:0,retryInterval:100,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}};constructor(e){e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!N(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return be(e,this.config.baseURL)}showMessage(e,s,n,r){this.config.messageHandler&&s&&this.config.messageHandler(e,s,n,r)}}const H={UnexpectResponse:"UnexpectResponse",Aborted:"Aborted",Unknown:"Unknown",NetworkError:"NetworkError",Timeout:"Timeout",NotSupport:"NotSupport",URLFormatError:"URLFormatError"};function je(t,e,s,n){if(e.ok&&!he(e.data)&&n){const r=pe(n,s.get("defaultTypeGuardMessage"));return r.guard(e.data)||(e.code=H.UnexpectResponse,s.showMessage(!0,`${t} ${r.message}`,e.code,e.status),console.error(e.code,t,e.data),e.data=null,e.message=r.message),e}return e}class Re{agent;config;cache;constructor(e,s){this.config=new ee(s),this.agent=e,this.cache=new $e(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.request=this.request.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async request(e,s){const n=this.cache.getKey(s?.method||"GET",e,s?.params,s?.cacheResolve);if(n){const r=this.cache.get(n,s?.cacheTTL);if(r)return await r}try{const r=this.agent(e,this.config,s);return n&&this.cache.set(n,r,s?.cacheTTL),await r}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:H.Unknown,message:r instanceof Error?`${r.message}
2
+ ${r.stack||""}`:String(r),headers:{},data:null}}}async guard(e,s,n){return je(e,s,this.config,n)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,s){const n=Object.assign({},s||null);return n.method="HEAD",this.guard(e,await this.request(e,n),null)}async get(e,s,n){const r=Object.assign({},n||null);r.method="GET";const o=this.request(e,r);return this.guard(e,await o,s||null)}async post(e,s,n,r){const o=Object.assign({},r||null);return o.method="POST",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async del(e,s,n){const r=Object.assign({},n||null);return r.method="DELETE",this.guard(e,await this.request(e,r),s||null)}async put(e,s,n,r){const o=Object.assign({},r||null);return o.method="PUT",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async patch(e,s,n,r){const o=Object.assign({},r||null);return o.method="PATCH",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}}async function Ee(t,e,s){const n=Object.assign({method:"GET"},s),r=k.FormData?n.body instanceof FormData:!1,o=r&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,i=o==="GET"||o==="HEAD"||o==="DELETE";i&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const u=Object.assign(r||i?{}:{"Content-Type":k.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),c=n.params||{},m={};Object.keys(c).forEach(_=>{c[_]!==void 0&&(m[_]=Ne(c[_]))});const f=e.getFullUrl(t),h=xe(n.body),p=n.timeout||e.get("timeout"),b=await async function(){const _=e.get("requestTransformer");if(_)return await _({headers:u,params:m,method:o,url:f,body:h})}(),w=typeof b=="string"&&b?b:f;return e.get("logHandler")?.({type:"ready",url:w,method:o,headers:u,timeout:p,body:h}),{url:w,method:o,body:h,params:m,headers:u,timeout:p,abort:n.abort,credentials:n.credentials||e.get("credentials")}}function Ne(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function xe(t){if(t)return typeof t=="string"||k.URLSearchParams&&t instanceof URLSearchParams||t instanceof ArrayBuffer||k.Blob&&t instanceof Blob||k.FormData&&t instanceof FormData?t:JSON.stringify(t)}const te="data",$="message";function Oe(t,e,s,n,r){const o=r||n;return G(t)?Le(o.ok||n.ok,t,e,s):Te(o.failed||n.failed,e,s)}const Fe=function(t){const e=[],s=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(s.messageField||$)+" 作为错误消息");break}const n=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(n.dataField||te)+" 作为响应数据,读取 "+(n.messageField||$)+" 作为提示消息"),n.statusField&&e.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&e.push(" 并忽略以下消息:"+n.ignoreMessage);break}return e.join(`
3
+ `)};function Te(t,e,s){const n=t||{resolve:"json",messageField:$},r={ok:!1,code:e,message:s,data:null};switch(n.resolve){case"body":r.message=W(s)||s;break;case"json":const{code:o,message:i}=Se(s,n.converter,n.statusField,n.messageField);r.code=o||e,r.message=W(s)||i;break}return r}function Se(t,e,s,n=$){if(!Z(t))return{message:""};const r=A(F(t),e);return!r||!y(r)?{message:t}:{code:s?S(r,s):"",message:S(r,n)||t}}function S(t,e){const s=Array.isArray(e)?e:[e];for(const n of s)if(n in t)return Ae(t[n]);return""}function Ae(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const Ue=/<title>([^<]+)<\/title>/i,Me=/<message>([^<]+)<\/message>/i;function W(t){const e=t.match(Ue);if(e)return e[1];const s=t.match(Me);return s?s[1]:""}function Le(t,e,s,n){const r=t||{resolve:"body"},o={ok:!0,code:s,message:"",data:null};if(e===204||!n)return o;if(r.resolve==="body")return o.data=Z(n)?A(F(n),t.converter):n,o;const i=A(F(n),t.converter);if(!i||!y(i))return o.ok=!1,o.code="ResponseFormatError",o.message="响应内容无法格式化为 Object",o;const u=r.statusField,c=r.statusOKValue||"",m=r.dataField||te,f=r.messageField||$,h=r.ignoreMessage||"";if(u&&!(u in i))return o.ok=!1,o.code="ResponseFieldMissing",o.message="响应内容找不到状态字段 "+u,o;const p=u?i[u]+"":"";return o.ok=u?p===c:!0,o.code=p||s,o.data=m===!0?i:m in i?i[m]:null,o.message=S(i,f),h&&o.message&&(Array.isArray(h)&&h.includes(o.message)||typeof h=="string"&&o.message===h)&&(o.message=""),o}function G(t){return t>=200&&t<400}function A(t,e){return e?typeof e=="function"?e(t):(console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'),t):t}const Pe=oe("APIError");function Ce(t){const e={};for(const r in t.headers)(r.startsWith("x-")||r.includes("trace")||r.includes("server")||/\b(?:id|uuid)\b/.test(r))&&(e[r]=t.headers[r]);const s=t.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),n=t.status<0?"unknown":t.status;return{sentryError:new Pe(`${s} | ${n}${t.code?` | ${t.code}`:""}`),sentryTags:{...e,status:n,method:t.method,code:t.code||"unknown",message:t.message||"empty"},sentryExtra:{url:t.url,responseBody:t.body||"empty",responseHeaders:t.headers,rawError:t.error}}}function se(t){return t.reduce((e,[s,n])=>(s&&(e[s]=n||""),e),{})}function Ie(t,e,s,n){const r=t.status,o=t.method,i=se(Object.entries(t.headers||{}).map(([b,w])=>[b.toLowerCase(),w])),{ok:u,code:c,data:m,message:f}=Oe(r,t.statusText,t.body,s.get("responseRule"),n?.responseRule);if(!G(r)){const b=Ce({url:t.url,method:t.method,status:r,code:c,message:f,body:t.body,headers:i,error:t.rawError});(s.get("errorHandler")||qe)({url:e,method:o,status:r,code:c,message:f,headers:i,rawError:t.rawError,responseBody:t.body,...b})}if(r<0)return J({ok:!1,status:r,code:t.statusText,headers:{},message:"",data:null},`${o} ${e} ${t.statusText}`,o,e,s,n);const h={ok:u,data:m,code:c,message:f,status:r,headers:i};s.get("responseHandler")?.({...h},o,e);const p=u?f:f||t.statusText;return J(h,p,o,e,s,n)}function J(t,e,s,n,r,o){const i=r.get("message"),u=i===!1||o?.message===!1?!1:o?.message||i;if(u!==!1){const c=typeof u=="function"?u(t,s,n,e):e;c instanceof Error?r.showMessage(!0,c.message,t.code,t.status):c&&typeof c=="object"&&"message"in c?r.showMessage(!1,c.message,t.code,t.status):r.showMessage(!t.ok,c,t.code,t.status)}return t}function qe(t){const e={};for(const s in t)s.startsWith("sentry")||(e[s]=t[s]);console.error("RequestError",e)}async function ne(t,e,s,n,r){const o=r||0,i=Math.max(0,Math.min(10,n?.maxRetry??s.get("maxRetry")??0)),u=n?.retryResolve??s.get("retryResolve"),c=s.get("logHandler");c?.({type:"prepare",url:e,method:n?.method||"GET",retry:o,maxRetry:i,message:o===0?"start":`retry ${o}/${i} start`,headers:n?.headers,options:n});const m=Date.now(),f=await t(e,s,n),h=f.status,p=Date.now()-m,b=`[cost ${p}][${h}] ${h<0?f.body:""}`;c?.({type:"finished",url:e,method:f.method,retry:o,maxRetry:i,message:o===0?`finish ${b}`:`retry ${o}/${i} finish ${b}`,response:f,headers:f.headers,cost:p});const w=G(h);if(!i||o>=i||u==="network"&&h>0||u==="status"&&w||Array.isArray(u)&&!u.includes(h)||typeof u=="function"&&u(f,o)!==!0)return f;const _=n?.retryInterval??s.get("retryInterval")??100;return await re(Math.max(100,_==="2EB"?Math.pow(2,o)*100:typeof _=="function"?_(o+1,{url:e,status:h,method:f.method})||0:_)),await ne(t,e,s,n,o+1)}exports.Ct=k;exports.Et=N;exports.NetRequestHandler=Re;exports.RequestGlobalConfig=ee;exports.RequestInternalError=H;exports.convertOptions=Ee;exports.fromEntries=se;exports.getResponseRulesDescription=Fe;exports.handleResponse=Ie;exports.retryRequest=ne;exports.ue=de;exports.ye=ke;