@seayoo-web/request 3.3.1 → 3.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
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(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./retry-D-T4xE0P.cjs"),y=require("./request.fetch-zj8Hd-er.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
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,6 +1,6 @@
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";
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-DUa9q26R.js";
2
+ import { g as K } from "./retry-DUa9q26R.js";
3
+ import { f as L } from "./request.fetch-b7wSTFXy.js";
4
4
  const k = async function(t, o, e) {
5
5
  return m(await x(y, t, o, e), t, o, e);
6
6
  };
package/dist/node.cjs CHANGED
@@ -1 +1 @@
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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-D-T4xE0P.cjs"),y=require("./request.fetch-zj8Hd-er.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,6 +1,6 @@
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";
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-DUa9q26R.js";
2
+ import { g as J } from "./retry-DUa9q26R.js";
3
+ import { f as x } from "./request.fetch-b7wSTFXy.js";
4
4
  import N from "node:http";
5
5
  import T from "node:https";
6
6
  const j = async function(o, a, u) {
@@ -1,4 +1,4 @@
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";
1
+ import { h as w, r as y, c as E, C as T, f as R, a as c } from "./retry-DUa9q26R.js";
2
2
  const x = async function(a, s, n) {
3
3
  return w(await y(g, a, s, n), a, s, n);
4
4
  }, g = async function(a, s, n) {
@@ -1 +1 @@
1
- "use strict";const r=require("./retry-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
+ "use strict";const r=require("./retry-D-T4xE0P.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,3 +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;
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 T(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 F(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 C{_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 C;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 M{_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 M;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 L{_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 L;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 P{_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 P}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 ${F(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 ${F(e)}`),!1)}}class q{_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 q(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 ${F(e)}`),!1)}}class I{_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 I(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 q(t)},array(t){return new I(t)},tuple(...t){return new D(...t)},union(...t){return new B(...t)},string(){return new C},bool(){return new P},number(){return new M},bigint(){return new L},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(h=>h.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;timer=null;loopCheck(){if(Object.keys(this.cache).forEach(s=>{this.cache[s].ttl<Date.now()&&delete this.cache[s]}),Object.keys(this.cache).length===0){this.timer=null;return}this.timer=setTimeout(this.loopCheck,5e3)}constructor(e=500){this.cache={},this.ttl=Math.max(e,0),this.loopCheck=this.loopCheck.bind(this)}getKey(e,s,n,r){if(e.toLowerCase()!=="get"&&!r)return"";const o=e.toLowerCase(),i=s.replace(/#.+/,""),u=i.replace(/\?.+/g,"");if(r)try{const c=r()||"";return c?`${u}_${o}_${c}`:""}catch(c){return console.warn("[RequestCache] cacheResolve error",s,n,c),""}const h=Object.assign(ye(i,!0),n),m=ve(i),f=Object.keys(h).sort().map(c=>`${c}#${h[c]}`);return`${u}_${o}_${f.join(",")}_${m.join(",")}`}updateTTL(e){this.ttl=Math.max(e,0)}get(e,s){if(Math.max(s??this.ttl,0)===0)return null;const r=this.cache[e];return r?r.ttl<Date.now()?(delete this.cache[e],null):r.res:null}set(e,s,n){const r=Math.max(n??this.ttl,0);r!==0&&(this.cache[e]={ttl:Date.now()+r,res:s},this.timer===null&&(this.timer=setTimeout(this.loopCheck,5e3)))}del(e){this.cache[e]&&delete this.cache[e]}}class ee{config={baseURL:"/",maxRetry:0,retryInterval:100,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}};constructor(e){e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!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);n&&this.cache.set(n,r,s?.cacheTTL);const o=await r;return(!o.ok||o.status<0)&&this.cache.del(n),o}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:H.Unknown,message:r instanceof Error?`${r.message}
2
+ ${r.stack||""}`:String(r),headers:{},data:null}}}async guard(e,s,n){return je(e,s,this.config,n)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,s){const n=Object.assign({},s||null);return n.method="HEAD",this.guard(e,await this.request(e,n),null)}async get(e,s,n){const r=Object.assign({},n||null);r.method="GET";const o=this.request(e,r);return this.guard(e,await o,s||null)}async post(e,s,n,r){const o=Object.assign({},r||null);return o.method="POST",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async del(e,s,n){const r=Object.assign({},n||null);return r.method="DELETE",this.guard(e,await this.request(e,r),s||null)}async put(e,s,n,r){const o=Object.assign({},r||null);return o.method="PUT",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async patch(e,s,n,r){const o=Object.assign({},r||null);return o.method="PATCH",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}}async function Ee(t,e,s){const n=Object.assign({method:"GET"},s),r=k.FormData?n.body instanceof FormData:!1,o=r&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,i=o==="GET"||o==="HEAD"||o==="DELETE";i&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const u=Object.assign(r||i?{}:{"Content-Type":k.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),h=n.params||{},m={};Object.keys(h).forEach(_=>{h[_]!==void 0&&(m[_]=Ne(h[_]))});const f=e.getFullUrl(t),c=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:c})}(),w=typeof b=="string"&&b?b:f;return e.get("logHandler")?.({type:"ready",url:w,method:o,headers:u,timeout:p,body:c}),{url:w,method:o,body:c,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)?Me(o.ok||n.ok,t,e,s):Fe(o.failed||n.failed,e,s)}const Te=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 Fe(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(T(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,Ce=/<message>([^<]+)<\/message>/i;function W(t){const e=t.match(Ue);if(e)return e[1];const s=t.match(Ce);return s?s[1]:""}function Me(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(T(n),t.converter):n,o;const i=A(T(n),t.converter);if(!i||!y(i))return o.ok=!1,o.code="ResponseFormatError",o.message="响应内容无法格式化为 Object",o;const u=r.statusField,h=r.statusOKValue||"",m=r.dataField||te,f=r.messageField||$,c=r.ignoreMessage||"";if(u&&!(u in i))return o.ok=!1,o.code="ResponseFieldMissing",o.message="响应内容找不到状态字段 "+u,o;const p=u?i[u]+"":"";return o.ok=u?p===h:!0,o.code=p||s,o.data=m===!0?i:m in i?i[m]:null,o.message=S(i,f),c&&o.message&&(Array.isArray(c)&&c.includes(o.message)||typeof c=="string"&&o.message===c)&&(o.message=""),o}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 Le=oe("APIError");function Pe(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 Le(`${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 qe(t,e,s,n){const r=t.status,o=t.method,i=se(Object.entries(t.headers||{}).map(([b,w])=>[b.toLowerCase(),w])),{ok:u,code:h,data:m,message:f}=Oe(r,t.statusText,t.body,s.get("responseRule"),n?.responseRule);if(!G(r)){const b=Pe({url:t.url,method:t.method,status:r,code:h,message:f,body:t.body,headers:i,error:t.rawError});(s.get("errorHandler")||Ie)({url:e,method:o,status:r,code:h,message:f,headers:i,rawError:t.rawError,responseBody:t.body,...b})}if(r<0)return J({ok:!1,status:r,code:t.statusText,headers:{},message:"",data:null},`${o} ${e} ${t.statusText}`,o,e,s,n);const c={ok:u,data:m,code:h,message:f,status:r,headers:i};s.get("responseHandler")?.({...c},o,e);const p=u?f:f||t.statusText;return J(c,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 h=typeof u=="function"?u(t,s,n,e):e;h instanceof Error?r.showMessage(!0,h.message,t.code,t.status):h&&typeof h=="object"&&"message"in h?r.showMessage(!1,h.message,t.code,t.status):r.showMessage(!t.ok,h,t.code,t.status)}return t}function Ie(t){const e={};for(const s in t)s.startsWith("sentry")||(e[s]=t[s]);console.error("RequestError",e)}async function ne(t,e,s,n,r){const o=r||0,i=Math.max(0,Math.min(10,n?.maxRetry??s.get("maxRetry")??0)),u=n?.retryResolve??s.get("retryResolve"),h=s.get("logHandler");h?.({type:"prepare",url:e,method:n?.method||"GET",retry:o,maxRetry:i,message:o===0?"start":`retry ${o}/${i} start`,headers:n?.headers,options:n});const m=Date.now(),f=await t(e,s,n),c=f.status,p=Date.now()-m,b=`[cost ${p}][${c}] ${c<0?f.body:""}`;h?.({type:"finished",url:e,method:f.method,retry:o,maxRetry:i,message:o===0?`finish ${b}`:`retry ${o}/${i} finish ${b}`,response:f,headers:f.headers,cost:p});const w=G(c);if(!i||o>=i||u==="network"&&c>0||u==="status"&&w||Array.isArray(u)&&!u.includes(c)||typeof u=="function"&&u(f,o)!==!0)return f;const _=n?.retryInterval??s.get("retryInterval")??100;return await re(Math.max(100,_==="2EB"?Math.pow(2,o)*100:typeof _=="function"?_(o+1,{url:e,status:c,method:f.method})||0:_)),await ne(t,e,s,n,o+1)}exports.Ct=k;exports.Et=N;exports.NetRequestHandler=Re;exports.RequestGlobalConfig=ee;exports.RequestInternalError=H;exports.convertOptions=Ee;exports.fromEntries=se;exports.getResponseRulesDescription=Te;exports.handleResponse=qe;exports.retryRequest=ne;exports.ue=de;exports.ye=ke;
@@ -119,7 +119,7 @@ const g = X("Validator");
119
119
  function j(t) {
120
120
  return t ? `"${ue(t).replace(/"/g, '\\"')}"` : "empty string";
121
121
  }
122
- function F(t) {
122
+ function T(t) {
123
123
  return typeof t == "object" && t && "constructor" in t && typeof t.constructor == "function" ? t.constructor.name || "ClassInstance" : Object.prototype.toString.call(t).replace(/(?:.+ |]$)/g, "");
124
124
  }
125
125
  function N(t) {
@@ -197,7 +197,7 @@ class M {
197
197
  }) ? (s(`${j(e)} is not match pattern ${n.join(" | ")}`), !1) : !0;
198
198
  }
199
199
  }
200
- class L {
200
+ class C {
201
201
  _int = !1;
202
202
  _min = -1 / 0;
203
203
  _max = 1 / 0;
@@ -257,14 +257,14 @@ class L {
257
257
  return this._locked = !0, this;
258
258
  }
259
259
  clone() {
260
- const e = new L();
260
+ const e = new C();
261
261
  return e._int = this._int, e._min = this._min, e._max = this._max, e._allow = [...this._allow], e._reject = [...this._reject], e._infinite = this._infinite, e._unsafe = this._unsafe, e._nan = this._nan, e._locked = !1, e;
262
262
  }
263
263
  validate(e, s = g.warn) {
264
264
  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);
265
265
  }
266
266
  }
267
- class P {
267
+ class L {
268
268
  _min = null;
269
269
  _max = null;
270
270
  _allow = [];
@@ -301,7 +301,7 @@ class P {
301
301
  return this._locked = !0, this;
302
302
  }
303
303
  clone() {
304
- const e = new P();
304
+ const e = new L();
305
305
  return e._min = this._min, e._max = this._max, e._allow = [...this._allow], e._reject = [...this._reject], e._locked = !1, e;
306
306
  }
307
307
  validate(e, s = g.warn) {
@@ -310,7 +310,7 @@ class P {
310
310
  ), !1) : (s(`should be a bigint, but got ${typeof e}`), !1);
311
311
  }
312
312
  }
313
- class C {
313
+ class P {
314
314
  _locked = !1;
315
315
  _opt = !1;
316
316
  _null = !1;
@@ -326,7 +326,7 @@ class C {
326
326
  return this._locked = !0, this;
327
327
  }
328
328
  clone() {
329
- return new C();
329
+ return new P();
330
330
  }
331
331
  validate(e, s = g.warn) {
332
332
  return e === void 0 ? this._opt || (s("should be a boolean, but got undefined"), !1) : e === null ? this._null || (s("should be a boolean, but got null"), !1) : typeof e != "boolean" ? (s(`should be a boolean, but got ${typeof e}`), !1) : !0;
@@ -373,9 +373,9 @@ class v {
373
373
  return e in this._shape ? this._shape[e].validate(s, J) : !1;
374
374
  }
375
375
  validate(e, s = g.warn) {
376
- return e === void 0 ? this._opt || (s("should be a object, but got undefined"), !1) : e === null ? this._null || (s("should be a object, but got null"), !1) : Y(e) ? this._plain && !y(e) ? (s(`should be a plain object, but got ${F(e)}`), !1) : Object.keys(this._shape).every((n) => this._shape[n].validate(e[n], (...r) => {
376
+ return e === void 0 ? this._opt || (s("should be a object, but got undefined"), !1) : e === null ? this._null || (s("should be a object, but got null"), !1) : Y(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) => {
377
377
  s(`[.${String(n)}]`, ...r);
378
- })) : (s(`should be a object, but got ${F(e)}`), !1);
378
+ })) : (s(`should be a object, but got ${T(e)}`), !1);
379
379
  }
380
380
  }
381
381
  class I {
@@ -405,7 +405,7 @@ class I {
405
405
  (n) => this._val.validate(e[n], (...r) => {
406
406
  s(`[:${n}]`, ...r);
407
407
  })
408
- ) : (s(`should be a record, but got ${F(e)}`), !1);
408
+ ) : (s(`should be a record, but got ${T(e)}`), !1);
409
409
  }
410
410
  }
411
411
  class D {
@@ -623,15 +623,15 @@ const he = {
623
623
  },
624
624
  /** 布尔型类型验证 */
625
625
  bool() {
626
- return new C();
626
+ return new P();
627
627
  },
628
628
  /** 数字验证 */
629
629
  number() {
630
- return new L();
630
+ return new C();
631
631
  },
632
632
  /** bigint 验证 */
633
633
  bigint() {
634
- return new P();
634
+ return new L();
635
635
  },
636
636
  /** 自定义验证 */
637
637
  custom: ce,
@@ -685,9 +685,9 @@ function ge(t, e) {
685
685
  return t.replace(/\?[^#]*/, "");
686
686
  } else return t;
687
687
  const s = t.split("#"), n = s[0].split("?"), r = n[0], o = n.length > 1 ? n[1] : "", i = s.length > 1 ? "#" + s[1] : "", u = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
688
- return !u.length || !o ? s[0] + i : (u.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + o.replace(new RegExp("(?:^|&)(?:" + u.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + i);
688
+ return !u.length || !o ? s[0] + i : (u.map((h) => h.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + o.replace(new RegExp("(?:^|&)(?:" + u.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + i);
689
689
  }
690
- function Le(t, e, s = !1) {
690
+ function Ce(t, e, s = !1) {
691
691
  const n = typeof e == "string" ? e : Object.keys(e).map((i) => `${i}=${encodeURIComponent(e[i])}`).join("&");
692
692
  if (!n)
693
693
  return t;
@@ -706,18 +706,32 @@ function pe(t) {
706
706
  class be {
707
707
  ttl;
708
708
  cache;
709
+ timer = null;
710
+ // 定时循环以清理缓存
711
+ loopCheck() {
712
+ if (Object.keys(this.cache).forEach((s) => {
713
+ this.cache[s].ttl < Date.now() && delete this.cache[s];
714
+ }), Object.keys(this.cache).length === 0) {
715
+ this.timer = null;
716
+ return;
717
+ }
718
+ this.timer = setTimeout(this.loopCheck, 5e3);
719
+ }
709
720
  constructor(e = 500) {
710
- this.cache = {}, this.ttl = Math.max(e, 0);
721
+ this.cache = {}, this.ttl = Math.max(e, 0), this.loopCheck = this.loopCheck.bind(this);
711
722
  }
712
723
  getKey(e, s, n, r) {
713
724
  if (e.toLowerCase() !== "get" && !r)
714
725
  return "";
715
726
  const o = e.toLowerCase(), i = s.replace(/#.+/, ""), u = i.replace(/\?.+/g, "");
716
- if (r) {
717
- const h = r() || "";
718
- return h ? `${u}_${o}_${h}` : "";
719
- }
720
- const c = Object.assign(_e(i, !0), n), m = pe(i), f = Object.keys(c).sort().map((h) => `${h}#${c[h]}`);
727
+ if (r)
728
+ try {
729
+ const c = r() || "";
730
+ return c ? `${u}_${o}_${c}` : "";
731
+ } catch (c) {
732
+ return console.warn("[RequestCache] cacheResolve error", s, n, c), "";
733
+ }
734
+ const h = Object.assign(_e(i, !0), n), m = pe(i), f = Object.keys(h).sort().map((c) => `${c}#${h[c]}`);
721
735
  return `${u}_${o}_${f.join(",")}_${m.join(",")}`;
722
736
  }
723
737
  updateTTL(e) {
@@ -734,7 +748,10 @@ class be {
734
748
  r !== 0 && (this.cache[e] = {
735
749
  ttl: Date.now() + r,
736
750
  res: s
737
- });
751
+ }, this.timer === null && (this.timer = setTimeout(this.loopCheck, 5e3)));
752
+ }
753
+ del(e) {
754
+ this.cache[e] && delete this.cache[e];
738
755
  }
739
756
  }
740
757
  class ye {
@@ -801,7 +818,7 @@ function we(t, e, s, n) {
801
818
  }
802
819
  return e;
803
820
  }
804
- class Pe {
821
+ class Le {
805
822
  agent;
806
823
  config;
807
824
  cache;
@@ -820,7 +837,9 @@ class Pe {
820
837
  }
821
838
  try {
822
839
  const r = this.agent(e, this.config, s);
823
- return n && this.cache.set(n, r, s?.cacheTTL), await r;
840
+ n && this.cache.set(n, r, s?.cacheTTL);
841
+ const o = await r;
842
+ return (!o.ok || o.status < 0) && this.cache.del(n), o;
824
843
  } catch (r) {
825
844
  return console.error("RequestError", r), {
826
845
  ok: !1,
@@ -881,7 +900,7 @@ ${r.stack || ""}` : String(r),
881
900
  return o.method = "PATCH", o.body = s || {}, this.guard(e, await this.request(e, o), n || null);
882
901
  }
883
902
  }
884
- async function Ce(t, e, s) {
903
+ async function Pe(t, e, s) {
885
904
  const n = Object.assign({ method: "GET" }, s), r = k.FormData ? n.body instanceof FormData : !1, o = r && n.method !== "POST" && n.method !== "PUT" ? "POST" : n.method, i = o === "GET" || o === "HEAD" || o === "DELETE";
886
905
  i && n.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete n.body);
887
906
  const u = Object.assign(
@@ -889,19 +908,19 @@ async function Ce(t, e, s) {
889
908
  "Content-Type": k.Blob && n.body instanceof Blob ? n.body.type || "application/octet-stream" : "application/json;charset=utf-8"
890
909
  },
891
910
  n.headers
892
- ), c = n.params || {}, m = {};
893
- Object.keys(c).forEach((_) => {
894
- c[_] !== void 0 && (m[_] = ke(c[_]));
911
+ ), h = n.params || {}, m = {};
912
+ Object.keys(h).forEach((_) => {
913
+ h[_] !== void 0 && (m[_] = ke(h[_]));
895
914
  });
896
- const f = e.getFullUrl(t), h = ve(n.body), p = n.timeout || e.get("timeout"), b = await async function() {
915
+ const f = e.getFullUrl(t), c = ve(n.body), p = n.timeout || e.get("timeout"), b = await async function() {
897
916
  const _ = e.get("requestTransformer");
898
917
  if (_)
899
- return await _({ headers: u, params: m, method: o, url: f, body: h });
918
+ return await _({ headers: u, params: m, method: o, url: f, body: c });
900
919
  }(), w = typeof b == "string" && b ? b : f;
901
- return e.get("logHandler")?.({ type: "ready", url: w, method: o, headers: u, timeout: p, body: h }), {
920
+ return e.get("logHandler")?.({ type: "ready", url: w, method: o, headers: u, timeout: p, body: c }), {
902
921
  url: w,
903
922
  method: o,
904
- body: h,
923
+ body: c,
905
924
  params: m,
906
925
  headers: u,
907
926
  timeout: p,
@@ -970,11 +989,11 @@ function Ee(t, e, s, n = $) {
970
989
  return { message: "" };
971
990
  const r = S(O(t), e);
972
991
  return !r || !y(r) ? { message: t } : {
973
- code: s ? T(r, s) : "",
974
- message: T(r, n) || t
992
+ code: s ? F(r, s) : "",
993
+ message: F(r, n) || t
975
994
  };
976
995
  }
977
- function T(t, e) {
996
+ function F(t, e) {
978
997
  const s = Array.isArray(e) ? e : [e];
979
998
  for (const n of s)
980
999
  if (n in t)
@@ -1006,11 +1025,11 @@ function Oe(t, e, s, n) {
1006
1025
  const i = S(O(n), t.converter);
1007
1026
  if (!i || !y(i))
1008
1027
  return o.ok = !1, o.code = "ResponseFormatError", o.message = "响应内容无法格式化为 Object", o;
1009
- const u = r.statusField, c = r.statusOKValue || "", m = r.dataField || ee, f = r.messageField || $, h = r.ignoreMessage || "";
1028
+ const u = r.statusField, h = r.statusOKValue || "", m = r.dataField || ee, f = r.messageField || $, c = r.ignoreMessage || "";
1010
1029
  if (u && !(u in i))
1011
1030
  return o.ok = !1, o.code = "ResponseFieldMissing", o.message = "响应内容找不到状态字段 " + u, o;
1012
1031
  const p = u ? i[u] + "" : "";
1013
- return o.ok = u ? p === c : !0, o.code = p || s, o.data = m === !0 ? i : m in i ? i[m] : null, o.message = T(i, f), h && o.message && (Array.isArray(h) && h.includes(o.message) || typeof h == "string" && o.message === h) && (o.message = ""), o;
1032
+ return o.ok = u ? p === h : !0, o.code = p || s, o.data = m === !0 ? i : m in i ? i[m] : null, o.message = F(i, f), c && o.message && (Array.isArray(c) && c.includes(o.message) || typeof c == "string" && o.message === c) && (o.message = ""), o;
1014
1033
  }
1015
1034
  function H(t) {
1016
1035
  return t >= 200 && t < 400;
@@ -1018,14 +1037,14 @@ function H(t) {
1018
1037
  function S(t, e) {
1019
1038
  return e ? typeof e == "function" ? e(t) : (console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'), t) : t;
1020
1039
  }
1021
- const Fe = se("APIError");
1022
- function Te(t) {
1040
+ const Te = se("APIError");
1041
+ function Fe(t) {
1023
1042
  const e = {};
1024
1043
  for (const r in t.headers)
1025
1044
  (r.startsWith("x-") || r.includes("trace") || r.includes("server") || /\b(?:id|uuid)\b/.test(r)) && (e[r] = t.headers[r]);
1026
1045
  const s = t.url.replace(/^(?:https?:)?\/*/i, "").replace(/\?.+/, ""), n = t.status < 0 ? "unknown" : t.status;
1027
1046
  return {
1028
- sentryError: new Fe(`${s} | ${n}${t.code ? ` | ${t.code}` : ""}`),
1047
+ sentryError: new Te(`${s} | ${n}${t.code ? ` | ${t.code}` : ""}`),
1029
1048
  sentryTags: {
1030
1049
  ...e,
1031
1050
  status: n,
@@ -1050,7 +1069,7 @@ function Se(t) {
1050
1069
  function De(t, e, s, n) {
1051
1070
  const r = t.status, o = t.method, i = Se(
1052
1071
  Object.entries(t.headers || {}).map(([b, w]) => [b.toLowerCase(), w])
1053
- ), { ok: u, code: c, data: m, message: f } = $e(
1072
+ ), { ok: u, code: h, data: m, message: f } = $e(
1054
1073
  r,
1055
1074
  t.statusText,
1056
1075
  t.body,
@@ -1058,11 +1077,11 @@ function De(t, e, s, n) {
1058
1077
  n?.responseRule
1059
1078
  );
1060
1079
  if (!H(r)) {
1061
- const b = Te({
1080
+ const b = Fe({
1062
1081
  url: t.url,
1063
1082
  method: t.method,
1064
1083
  status: r,
1065
- code: c,
1084
+ code: h,
1066
1085
  message: f,
1067
1086
  body: t.body,
1068
1087
  headers: i,
@@ -1072,7 +1091,7 @@ function De(t, e, s, n) {
1072
1091
  url: e,
1073
1092
  method: o,
1074
1093
  status: r,
1075
- code: c,
1094
+ code: h,
1076
1095
  message: f,
1077
1096
  headers: i,
1078
1097
  rawError: t.rawError,
@@ -1089,16 +1108,16 @@ function De(t, e, s, n) {
1089
1108
  s,
1090
1109
  n
1091
1110
  );
1092
- const h = { ok: u, data: m, code: c, message: f, status: r, headers: i };
1093
- s.get("responseHandler")?.({ ...h }, o, e);
1111
+ const c = { ok: u, data: m, code: h, message: f, status: r, headers: i };
1112
+ s.get("responseHandler")?.({ ...c }, o, e);
1094
1113
  const p = u ? f : f || t.statusText;
1095
- return W(h, p, o, e, s, n);
1114
+ return W(c, p, o, e, s, n);
1096
1115
  }
1097
1116
  function W(t, e, s, n, r, o) {
1098
1117
  const i = r.get("message"), u = i === !1 || o?.message === !1 ? !1 : o?.message || i;
1099
1118
  if (u !== !1) {
1100
- const c = typeof u == "function" ? u(t, s, n, e) : e;
1101
- 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);
1119
+ const h = typeof u == "function" ? u(t, s, n, e) : e;
1120
+ h instanceof Error ? r.showMessage(!0, h.message, t.code, t.status) : h && typeof h == "object" && "message" in h ? r.showMessage(!1, h.message, t.code, t.status) : r.showMessage(!t.ok, h, t.code, t.status);
1102
1121
  }
1103
1122
  return t;
1104
1123
  }
@@ -1109,8 +1128,8 @@ function Ae(t) {
1109
1128
  console.error("RequestError", e);
1110
1129
  }
1111
1130
  async function Ue(t, e, s, n, r) {
1112
- const o = r || 0, i = Math.max(0, Math.min(10, n?.maxRetry ?? s.get("maxRetry") ?? 0)), u = n?.retryResolve ?? s.get("retryResolve"), c = s.get("logHandler");
1113
- c?.({
1131
+ const o = r || 0, i = Math.max(0, Math.min(10, n?.maxRetry ?? s.get("maxRetry") ?? 0)), u = n?.retryResolve ?? s.get("retryResolve"), h = s.get("logHandler");
1132
+ h?.({
1114
1133
  type: "prepare",
1115
1134
  url: e,
1116
1135
  method: n?.method || "GET",
@@ -1120,8 +1139,8 @@ async function Ue(t, e, s, n, r) {
1120
1139
  headers: n?.headers,
1121
1140
  options: n
1122
1141
  });
1123
- 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 : ""}`;
1124
- c?.({
1142
+ const m = Date.now(), f = await t(e, s, n), c = f.status, p = Date.now() - m, b = `[cost ${p}][${c}] ${c < 0 ? f.body : ""}`;
1143
+ h?.({
1125
1144
  type: "finished",
1126
1145
  url: e,
1127
1146
  method: f.method,
@@ -1132,28 +1151,28 @@ async function Ue(t, e, s, n, r) {
1132
1151
  headers: f.headers,
1133
1152
  cost: p
1134
1153
  });
1135
- const w = H(h);
1136
- if (!i || o >= i || u === "network" && h > 0 || u === "status" && w || Array.isArray(u) && !u.includes(h) || typeof u == "function" && u(f, o) !== !0)
1154
+ const w = H(c);
1155
+ if (!i || o >= i || u === "network" && c > 0 || u === "status" && w || Array.isArray(u) && !u.includes(c) || typeof u == "function" && u(f, o) !== !0)
1137
1156
  return f;
1138
1157
  const _ = n?.retryInterval ?? s.get("retryInterval") ?? 100;
1139
1158
  return await te(
1140
1159
  Math.max(
1141
1160
  100,
1142
- _ === "2EB" ? Math.pow(2, o) * 100 : typeof _ == "function" ? _(o + 1, { url: e, status: h, method: f.method }) || 0 : _
1161
+ _ === "2EB" ? Math.pow(2, o) * 100 : typeof _ == "function" ? _(o + 1, { url: e, status: c, method: f.method }) || 0 : _
1143
1162
  )
1144
1163
  ), await Ue(t, e, s, n, o + 1);
1145
1164
  }
1146
1165
  export {
1147
1166
  k as C,
1148
1167
  A as E,
1149
- Pe as N,
1168
+ Le as N,
1150
1169
  ye as R,
1151
1170
  Z as a,
1152
- Ce as c,
1171
+ Pe as c,
1153
1172
  Se as f,
1154
1173
  Ie as g,
1155
1174
  De as h,
1156
1175
  Ue as r,
1157
1176
  Me as u,
1158
- Le as y
1177
+ Ce as y
1159
1178
  };
package/dist/wx.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-sL4_1f7S.cjs"),l=async function(e,o,u){return t.handleResponse(await t.retryRequest(p,e,o,u),e,o,u)},p=async function(e,o,u){const s=await t.convertOptions(e,o,u),a=s.method==="PATCH"?"POST":s.method,c=t.ye(s.url,s.params);return t.Ct.wx?new Promise(d=>{wx.request({url:c,data:s.body,header:s.headers,method:a,dataType:"string",responseType:"text",fail(){d({url:c,method:a,status:-1,statusText:t.RequestInternalError.Unknown,body:""})},success(n){d({url:c,method:a,status:n.statusCode,statusText:n.statusCode+"",headers:{...n.header},body:s.method==="HEAD"||n.statusCode===204?"":f(n.data)})}})}):{url:c,method:a,status:-1,statusText:t.RequestInternalError.NotSupport,body:""}};function f(e){return typeof e=="string"?e:e instanceof ArrayBuffer&&t.Ct.TextDecoder?new TextDecoder().decode(e):JSON.stringify(e)}function i(e){return new t.NetRequestHandler(l,e)}const r=i(),y=r.setConfig,R=r.head,g=r.get,q=r.post,h=r.del,x=r.put;exports.RequestInternalError=t.RequestInternalError;exports.getResponseRulesDescription=t.getResponseRulesDescription;exports.NetRequest=i;exports.del=h;exports.get=g;exports.head=R;exports.post=q;exports.put=x;exports.setGlobalConfig=y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-D-T4xE0P.cjs"),l=async function(e,o,u){return t.handleResponse(await t.retryRequest(p,e,o,u),e,o,u)},p=async function(e,o,u){const s=await t.convertOptions(e,o,u),a=s.method==="PATCH"?"POST":s.method,c=t.ye(s.url,s.params);return t.Ct.wx?new Promise(d=>{wx.request({url:c,data:s.body,header:s.headers,method:a,dataType:"string",responseType:"text",fail(){d({url:c,method:a,status:-1,statusText:t.RequestInternalError.Unknown,body:""})},success(n){d({url:c,method:a,status:n.statusCode,statusText:n.statusCode+"",headers:{...n.header},body:s.method==="HEAD"||n.statusCode===204?"":f(n.data)})}})}):{url:c,method:a,status:-1,statusText:t.RequestInternalError.NotSupport,body:""}};function f(e){return typeof e=="string"?e:e instanceof ArrayBuffer&&t.Ct.TextDecoder?new TextDecoder().decode(e):JSON.stringify(e)}function i(e){return new t.NetRequestHandler(l,e)}const r=i(),y=r.setConfig,R=r.head,g=r.get,q=r.post,h=r.del,x=r.put;exports.RequestInternalError=t.RequestInternalError;exports.getResponseRulesDescription=t.getResponseRulesDescription;exports.NetRequest=i;exports.del=h;exports.get=g;exports.head=R;exports.post=q;exports.put=x;exports.setGlobalConfig=y;
package/dist/wx.js CHANGED
@@ -1,5 +1,5 @@
1
- import { h as p, r as f, c as l, y, C as i, a as d, N as h } from "./retry-vMhW20_a.js";
2
- import { g as H } from "./retry-vMhW20_a.js";
1
+ import { h as p, r as f, c as l, y, C as i, a as d, N as h } from "./retry-DUa9q26R.js";
2
+ import { g as H } from "./retry-DUa9q26R.js";
3
3
  const x = async function(t, n, r) {
4
4
  return p(await f(g, t, n, r), t, n, r);
5
5
  }, g = async function(t, n, r) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "3.3.1",
3
+ "version": "3.3.2",
4
4
  "description": "request tools for seayoo web",
5
5
  "type": "module",
6
6
  "source": "./src/index.ts",
@@ -3,9 +3,12 @@ import { RequestCacheResolve } from "./type";
3
3
  export declare class Cache<T = unknown> {
4
4
  private ttl;
5
5
  private cache;
6
+ private timer;
7
+ private loopCheck;
6
8
  constructor(ttl?: number);
7
9
  getKey(method: string, url: string, param?: Record<string, unknown>, resolve?: RequestCacheResolve): string;
8
10
  updateTTL(ttl: number): void;
9
11
  get(key: string, ttl?: number): Promise<T> | null;
10
12
  set(key: string, action: Promise<T>, ttl?: number): void;
13
+ del(key: string): void;
11
14
  }