@seayoo-web/request 2.1.1 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +120 -121
- package/dist/index.cjs +2 -2
- package/dist/index.js +12 -11
- package/dist/node.cjs +1 -1
- package/dist/node.js +24 -24
- package/dist/request.fetch-C7PHZPCL.cjs +1 -0
- package/dist/request.fetch-zIatpucl.js +46 -0
- package/dist/retry-DsJb9GfI.cjs +3 -0
- package/dist/retry-zhJVeNp_.js +595 -0
- package/dist/wx.cjs +1 -1
- package/dist/wx.js +8 -8
- package/package.json +3 -3
- package/types/inc/main.d.ts +2 -2
- package/types/inc/rule.d.ts +1 -1
- package/types/inc/type.d.ts +9 -9
- package/types/index.d.ts +2 -1
- package/dist/request.fetch-3tu4c4YP.js +0 -42
- package/dist/request.fetch-WuNmpi3J.cjs +0 -1
- package/dist/retry-C2OSRA9r.cjs +0 -2
- package/dist/retry-DUbMIN1-.js +0 -572
package/dist/wx.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-DsJb9GfI.cjs"),l=async function(t,r,u){return e.handleResponse(await e.retryRequest(f,t,r,u),t,r,u)},f=async function(t,r,u){const s=await e.convertOptions(t,r,u),a=s.method==="PATCH"?"POST":s.method,c=e.ce(s.url,s.params);return e.Rt.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:e.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?"":p(n.data)})}})}):{url:c,method:a,status:-1,statusText:e.RequestInternalError.NotSupport,body:""}};function p(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.Rt.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(l,t)}const o=i(),y=o.setConfig,g=o.head,h=o.get,R=o.post,q=o.del,x=o.put;exports.NetRequest=i;exports.del=q;exports.get=h;exports.head=g;exports.post=R;exports.put=x;exports.setGlobalConfig=y;
|
package/dist/wx.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { h as
|
|
1
|
+
import { h as f, r as p, c as l, a as h, d as i, b as d, N as y } from "./retry-zhJVeNp_.js";
|
|
2
2
|
const x = async function(t, n, r) {
|
|
3
|
-
return
|
|
3
|
+
return f(await p(m, t, n, r), t, n, r);
|
|
4
4
|
}, m = async function(t, n, r) {
|
|
5
|
-
const e = await
|
|
5
|
+
const e = await l(t, n, r), a = e.method === "PATCH" ? "POST" : e.method, u = h(e.url, e.params);
|
|
6
6
|
return i.wx ? new Promise((c) => {
|
|
7
7
|
wx.request({
|
|
8
8
|
url: u,
|
|
@@ -42,16 +42,16 @@ const x = async function(t, n, r) {
|
|
|
42
42
|
function w(t) {
|
|
43
43
|
return typeof t == "string" ? t : t instanceof ArrayBuffer && i.TextDecoder ? new TextDecoder().decode(t) : JSON.stringify(t);
|
|
44
44
|
}
|
|
45
|
-
function
|
|
45
|
+
function R(t) {
|
|
46
46
|
return new y(x, t);
|
|
47
47
|
}
|
|
48
|
-
const s =
|
|
48
|
+
const s = R(), g = s.setConfig, q = s.head, b = s.get, C = s.post, N = s.del, S = s.put;
|
|
49
49
|
export {
|
|
50
|
-
|
|
50
|
+
R as NetRequest,
|
|
51
51
|
N as del,
|
|
52
52
|
b as get,
|
|
53
|
-
|
|
53
|
+
q as head,
|
|
54
54
|
C as post,
|
|
55
55
|
S as put,
|
|
56
|
-
|
|
56
|
+
g as setGlobalConfig
|
|
57
57
|
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seayoo-web/request",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
|
+
"description": "request tools for seayoo web",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"source": "./src/index.ts",
|
|
7
7
|
"main": "./dist/index.js",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
"happy-dom": "^12.10.3",
|
|
60
60
|
"msw": "^2.7.0",
|
|
61
61
|
"vitest": "^3.0.5",
|
|
62
|
-
"@seayoo-web/utils": "^3.
|
|
62
|
+
"@seayoo-web/utils": "^3.3.3"
|
|
63
63
|
},
|
|
64
64
|
"scripts": {
|
|
65
65
|
"build": "vite build && tsc --emitDeclarationOnly",
|
package/types/inc/main.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type TypeGuardParam, type IRequestOptions, type IRequestGlobalConfig, type IResponseResult, type NetRequestAgent, type ResponseWithType, type ResponseWithoutType } from "./type";
|
|
2
2
|
type RequestBody = NonNullable<IRequestOptions["body"]>;
|
|
3
3
|
/** 工具函数主类 */
|
|
4
4
|
export declare class NetRequestHandler {
|
|
@@ -15,7 +15,7 @@ export declare class NetRequestHandler {
|
|
|
15
15
|
*/
|
|
16
16
|
private guard;
|
|
17
17
|
/**
|
|
18
|
-
* 修改默认请求配置:
|
|
18
|
+
* 修改默认请求配置: baseURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
|
|
19
19
|
*/
|
|
20
20
|
setConfig(config: IRequestGlobalConfig): void;
|
|
21
21
|
/**
|
package/types/inc/rule.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ type ResponseInfo = Pick<IResponseResult, "ok" | "code" | "data" | "message">;
|
|
|
3
3
|
/**
|
|
4
4
|
* 分析响应内容中的错误信息和数据
|
|
5
5
|
*/
|
|
6
|
-
export declare function
|
|
6
|
+
export declare function analysesResponse(status: number, statusText: string, responseText: string, globalRule: IResponseRule, rule?: IResponseRule): ResponseInfo;
|
|
7
7
|
/**
|
|
8
8
|
* 将 Response Rules 转化成为自然描述语言
|
|
9
9
|
*/
|
package/types/inc/type.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { RequestGlobalConfig } from "./config";
|
|
2
2
|
import type { MaybePromise, TypeGuard, TypeGuardFn } from "@seayoo-web/utils";
|
|
3
3
|
export type IBaseRequestBody = Blob | ArrayBuffer | FormData | URLSearchParams | string;
|
|
4
|
-
export declare const enum
|
|
4
|
+
export declare const enum RequestInternalError {
|
|
5
5
|
/** 响应数据校验失败 */
|
|
6
6
|
UnexpectResponse = "UnexpectResponse",
|
|
7
7
|
/** 请求被取消 */
|
|
@@ -28,7 +28,7 @@ export interface IBaseRequestOptions {
|
|
|
28
28
|
/** 发送的 body 内容,method 为 GET / HEAD / DELETE 时无效 */
|
|
29
29
|
body?: IBaseRequestBody | object | unknown[];
|
|
30
30
|
/**
|
|
31
|
-
* 是否携带用户认证信息(cookie, basic http auth 等),默认 "same-
|
|
31
|
+
* 是否携带用户认证信息(cookie, basic http auth 等),默认 "same-origin",
|
|
32
32
|
*
|
|
33
33
|
* 使用 xhRequest 时,omit 无效,nodejs 环境无效
|
|
34
34
|
*/
|
|
@@ -49,9 +49,9 @@ export interface IRetryRequestOptions {
|
|
|
49
49
|
/** 重试策略:默认 network,可选 status 或者指定特殊的 status 或自定义检查 */
|
|
50
50
|
retryResolve?: IRetryResolve;
|
|
51
51
|
/**
|
|
52
|
-
* 两次重试的间隔,如果设置时间,则单位 ms,或者设置函数返回等待的时间(单位ms),默认
|
|
52
|
+
* 两次重试的间隔,如果设置时间,则单位 ms,或者设置函数返回等待的时间(单位ms),默认 100,最小 100,函数参数 retryIndex 从 1 开始
|
|
53
53
|
*
|
|
54
|
-
* 特殊值 2EB 表示以 2 为底的指数退避,首次延迟为
|
|
54
|
+
* 特殊值 2EB 表示以 2 为底的指数退避,首次延迟为 100ms,第二次为 200ms,第三次为 400ms,第四次为 800ms...
|
|
55
55
|
*
|
|
56
56
|
* 扩展阅读 https://en.wikipedia.org/wiki/Exponential_backoff
|
|
57
57
|
*/
|
|
@@ -61,7 +61,7 @@ export interface IOtherRequestOptions {
|
|
|
61
61
|
/**
|
|
62
62
|
* 如果设置为 false 则关闭通用提示
|
|
63
63
|
*
|
|
64
|
-
* 设置函数可以自定义提示,函数返回
|
|
64
|
+
* 设置函数可以自定义提示,函数返回 falsely 则不提示
|
|
65
65
|
*
|
|
66
66
|
* 如果返回 Error 则强制以 error 方式提示 Error.message
|
|
67
67
|
*
|
|
@@ -153,7 +153,7 @@ export interface IResponseRule {
|
|
|
153
153
|
*
|
|
154
154
|
* - body
|
|
155
155
|
*
|
|
156
|
-
* 此时
|
|
156
|
+
* 此时 response body 被格式化为 json 并作为接口返回的数据使用,如果格式化失败,则返回 body 本身的字符串
|
|
157
157
|
*/
|
|
158
158
|
resolve: "json" | "body";
|
|
159
159
|
/** 将响应内容进行风格转化 */
|
|
@@ -221,8 +221,8 @@ interface RetryCount extends LogBase {
|
|
|
221
221
|
maxRetry: number;
|
|
222
222
|
message: string;
|
|
223
223
|
}
|
|
224
|
-
interface
|
|
225
|
-
type: "
|
|
224
|
+
interface LogPrepare extends RetryCount {
|
|
225
|
+
type: "prepare";
|
|
226
226
|
/** 请求的参数 */
|
|
227
227
|
options?: IRequestOptions;
|
|
228
228
|
/** 自定义追加的请求 header 头 */
|
|
@@ -246,6 +246,6 @@ interface LogFinished extends RetryCount {
|
|
|
246
246
|
/** 请求响应的 header */
|
|
247
247
|
headers?: Record<string, string | undefined>;
|
|
248
248
|
}
|
|
249
|
-
export type IRequestLog =
|
|
249
|
+
export type IRequestLog = LogPrepare | LogReady | LogFinished;
|
|
250
250
|
export type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>;
|
|
251
251
|
export {};
|
package/types/index.d.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { xhrUpload } from "./inc/request.xhr";
|
|
|
3
3
|
import type { IRequestGlobalConfig } from "./inc/type";
|
|
4
4
|
export { jsonp, jsonx } from "./inc/jsonp";
|
|
5
5
|
export { getResponseRulesDescription } from "./inc/rule";
|
|
6
|
-
export {
|
|
6
|
+
export { RequestInternalError } from "./inc/type";
|
|
7
|
+
export type { NetRequestHandler } from "./inc/main";
|
|
7
8
|
export type { IRequestOptions, IRequestGlobalConfig, IResponseRule, IResponseResult, IRequestLog } from "./inc/type";
|
|
8
9
|
/**
|
|
9
10
|
* 基于 xhr 模块的上传工具,支持上传进度
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { h as m, r as w, c as y, l as E, f as R, a as u } from "./retry-DUbMIN1-.js";
|
|
2
|
-
const x = async function(r, s, o) {
|
|
3
|
-
return m(await w(g, r, s, o), r, s, o);
|
|
4
|
-
}, g = async function(r, s, o) {
|
|
5
|
-
const t = await y(r, s, o), n = new URL(t.url), i = t.params;
|
|
6
|
-
i instanceof Object && Object.keys(i).forEach((e) => n.searchParams.set(e, i[e]));
|
|
7
|
-
const a = E.AbortController ? new AbortController() : null;
|
|
8
|
-
function c() {
|
|
9
|
-
a && !a.signal.aborted && a.abort();
|
|
10
|
-
}
|
|
11
|
-
t.abort && t.abort.addEventListener("abort", c);
|
|
12
|
-
const h = t.timeout > 0 ? setTimeout(c, t.timeout) : null, l = t.method === "HEAD";
|
|
13
|
-
return await fetch(n, {
|
|
14
|
-
method: t.method,
|
|
15
|
-
headers: Object.keys(t.headers).length > 0 ? new Headers(t.headers) : void 0,
|
|
16
|
-
body: t.body,
|
|
17
|
-
credentials: t.credentials,
|
|
18
|
-
signal: a == null ? void 0 : a.signal,
|
|
19
|
-
redirect: "follow"
|
|
20
|
-
}).then(async (e) => {
|
|
21
|
-
const b = {
|
|
22
|
-
url: n.toString(),
|
|
23
|
-
method: t.method,
|
|
24
|
-
status: e.status,
|
|
25
|
-
statusText: e.statusText,
|
|
26
|
-
headers: R([...e.headers.entries()])
|
|
27
|
-
}, d = l || e.status === 204 ? "" : await e.text().catch((f) => f);
|
|
28
|
-
return d instanceof Error ? { ...b, body: "", statusText: u.Unknown, rawError: d } : { ...b, body: d };
|
|
29
|
-
}).catch((e) => ({
|
|
30
|
-
url: n.toString(),
|
|
31
|
-
method: t.method,
|
|
32
|
-
status: -1,
|
|
33
|
-
statusText: a != null && a.signal.aborted ? u.Aborted : u.NetworkError,
|
|
34
|
-
body: "",
|
|
35
|
-
rawError: e
|
|
36
|
-
})).finally(() => {
|
|
37
|
-
h !== null && clearTimeout(h), t.abort && t.abort.removeEventListener("abort", c);
|
|
38
|
-
});
|
|
39
|
-
};
|
|
40
|
-
export {
|
|
41
|
-
x as f
|
|
42
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const s=require("./retry-C2OSRA9r.cjs"),m=async function(a,o,n){return s.handleResponse(await s.retryRequest(w,a,o,n),a,o,n)},w=async function(a,o,n){const t=await s.convertOptions(a,o,n),i=new URL(t.url),c=t.params;c instanceof Object&&Object.keys(c).forEach(e=>i.searchParams.set(e,c[e]));const r=s.lt.AbortController?new AbortController:null;function u(){r&&!r.signal.aborted&&r.abort()}t.abort&&t.abort.addEventListener("abort",u);const h=t.timeout>0?setTimeout(u,t.timeout):null,b=t.method==="HEAD";return await fetch(i,{method:t.method,headers:Object.keys(t.headers).length>0?new Headers(t.headers):void 0,body:t.body,credentials:t.credentials,signal:r==null?void 0:r.signal,redirect:"follow"}).then(async e=>{const l={url:i.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:s.fromEntries([...e.headers.entries()])},d=b||e.status===204?"":await e.text().catch(f=>f);return d instanceof Error?{...l,body:"",statusText:s.RequestInteralError.Unknown,rawError:d}:{...l,body:d}}).catch(e=>({url:i.toString(),method:t.method,status:-1,statusText:r!=null&&r.signal.aborted?s.RequestInteralError.Aborted:s.RequestInteralError.NetworkError,body:"",rawError:e})).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",u)})};exports.fetchRequest=m;
|
package/dist/retry-C2OSRA9r.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var G=Object.defineProperty;var J=(e,t,s)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var y=(e,t,s)=>J(e,typeof t!="symbol"?t+"":t,s);const h=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},R={wx:"wx"in h&&D(h.wx),fetch:"fetch"in h&&w(h.fetch),window:"window"in h&&D(h.window),Blob:"Blob"in h&&w(h.Blob),FormData:"FormData"in h&&w(h.FormData),TextDecoder:"TextDecoder"in h&&w(h.TextDecoder),AbortController:"AbortController"in h&&w(h.AbortController)};function w(e){return typeof e=="function"}function D(e){return typeof e=="object"&&e!==null}function W(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}function V(){}function Z(e){const t=e||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:t,enumerable:!1,configurable:!0}),"setPrototypeOf"in Object&&Object.setPrototypeOf(this,new.target.prototype),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,this.constructor)}}}const Q=/^(?:https?:)?\/\/.+$/i,z=/^https?:\/\/.+$/i,Y=/^\{[\d\D]*\}$/,X=/^\[[\d\D]*\]$/;function O(e,t=!1){return t?Q.test(e):z.test(e)}function ee(e){return e==null}function v(e,...t){if(!e||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s!==Object.prototype&&s!==null?!1:t.every(r=>r in e)}function _(e){return Y.test(e)||X.test(e)}function $(e){return e?e[0].toLowerCase()+e.slice(1):""}const B=/_\w*/,H=/-\w*/;function M(e){const t=B.test(e)?e.replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(s,r)=>r.toUpperCase()):H.test(e)?e.replace(/(?:^-*|-*$)/g,"").replace(/-+(\w)/g,(s,r)=>r.toUpperCase()):e;return $(t)}function L(e){return B.test(e)?$(e).replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(t,s)=>"_"+s.toLowerCase()):H.test(e)?$(e.replace(/(?:^-*|-*$)/g,"")).replace(/-+(\w)/g,(t,s)=>"_"+s.toLowerCase()):$(e).replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function T(e,t){try{const s=JSON.parse(e);return t?t(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);function k(e,t=!1){return typeof e=="string"?M(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?k(s):typeof s=="object"&&s?k(s,!0):s):v(e)?Object.keys(e).reduce((s,r)=>{const o=M(String(r)),n=o.charAt(0).toLowerCase()+o.slice(1);return s[n]=t?e[r]:k(e[r]),s},{}):e}function E(e,t=!1){return typeof e=="string"?L(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?E(s):typeof s=="object"&&s?E(s,t):s):v(e)?Object.keys(e).reduce((s,r)=>{const o=L(String(r));return s[o]=t?e[r]:E(e[r]),s},{}):e}async function te(e){return await new Promise(function(t){const s=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("charset","utf-8"),r.onload=function(){s.removeChild(r),t(!0)},r.onerror=function(){s.removeChild(r),t(!1)},r.setAttribute("src",e),s.appendChild(r)})}function se(e,t="数据未能正确识别"){return typeof e=="function"?{guard:e,message:t}:{guard:e.guard,message:e.message||t}}function re(e,t=""){return!t||O(e,!0)?x(e):(x(t)+"/"+e).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function x(e){return O(e,!0)?e.startsWith("http")?e:("location"in globalThis?location.protocol:"https:")+e:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+e.replace(/^\/+/,"")}function ne(e,t){const s={};return(e.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(r){const o=r.split("="),n=o[0],a=decodeURIComponent(o[1]||"");s[n]!==void 0?s[n]+=","+a:s[n]=a}),t!==!0?s[t]||"":s}function oe(e,t){if(t){if(t===!0)return e.replace(/\?[^#]*/,"")}else return e;const s=e.split("#"),r=s[0].split("?"),o=r[0],n=r.length>1?r[1]:"",a=s.length>1?"#"+s[1]:"",c=typeof t=="string"?[t]:Array.isArray(t)?t:[];return!c.length||!n?s[0]+a:(c.map(i=>i.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(o+"?"+n.replace(new RegExp("(?:^|&)(?:"+c.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+a)}function ae(e,t,s=!1){const r=typeof t=="string"?t:Object.keys(t).map(a=>`${a}=${encodeURIComponent(t[a])}`).join("&");if(!r)return e;const o=e.split("#");s&&(o[0]=oe(o[0],(r.match(/([^=&#?]+)=[^&#]+/g)||[]).map(a=>a.replace(/=.+$/,""))));const n=o[0].indexOf("?")+1?"&":"?";return(o[0]+n+r+(o.length>1?"#"+o[1]:"")).replace(/\?&/,"?")}function ce(e){const t=e.match(/(?:\?|&)([^=]+)(?:&|$)/g);return t?t.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class ie{constructor(t=500){y(this,"ttl");y(this,"cache");this.cache={},this.ttl=Math.max(t,0)}getKey(t,s){const r=t.replace(/#.+/,""),o=r.replace(/\?.+/g,""),n=Object.assign(ne(r,!0),s),a=ce(r),c=Object.keys(n).sort().map(i=>`${i}#${n[i]}`);return`${o}_${c.join(",")}_${a.join(",")}`}updateTTL(t){this.ttl=Math.max(t,0)}get(t){if(this.ttl===0)return null;const s=this.cache[t];return s?s.ttl<Date.now()?(delete this.cache[t],null):s.res:null}set(t,s){this.ttl!==0&&(this.cache[t]={ttl:Date.now()+this.ttl,res:s})}}class q{constructor(t){y(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});t&&this.set(t)}set(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!O(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)}get(t){return this.config[t]}getFullUrl(t){return re(t,this.config.baseURL)}showMessage(t,s,r,o){this.config.messageHandler&&s&&this.config.messageHandler(t,s,r,o)}}var C=(e=>(e.UnexpectResponse="UnexpectResponse",e.Aborted="Aborted",e.Unknown="Unknown",e.NetworkError="NetworkError",e.Timeout="Timeout",e.NotSupport="NotSupport",e.URLFormatError="URLFormatError",e))(C||{});function ue(e,t,s,r){if(t.ok&&!ee(t.data)&&r){const o=se(r,s.get("defaultTypeGuardMessage"));return o.guard(t.data)||(t.code=C.UnexpectResponse,s.showMessage(!0,`${e} ${o.message}`,t.code,t.status),console.error(t.code,e,t.data),t.data=null,t.message=o.message),t}return t}class le{constructor(t,s){y(this,"agent");y(this,"config");y(this,"cache");this.config=new q(s),this.agent=t,this.cache=new ie(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.request=this.request.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async request(t,s){try{return await this.agent(t,this.config,s)}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:"Unkonwn",message:String(r),headers:{},data:null}}}async guard(t,s,r){return ue(t,s,this.config,r)}setConfig(t){this.config.set(t),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(t){return this.config.get(t)}async head(t,s){const r=Object.assign({},s||null);return r.method="HEAD",this.guard(t,await this.request(t,r),null)}async get(t,s,r){const o=Object.assign({},r||null);o.method="GET";const n=this.cache.getKey(t,o.params),a=this.cache.get(n);if(a)return this.guard(t,await a,s||null);const c=this.request(t,o);return this.cache.set(n,c),this.guard(t,await c,s||null)}async post(t,s,r,o){const n=Object.assign({},o||null);return n.method="POST",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async del(t,s,r){const o=Object.assign({},r||null);return o.method="DELETE",this.guard(t,await this.request(t,o),s||null)}async put(t,s,r,o){const n=Object.assign({},o||null);return n.method="PUT",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async patch(t,s,r,o){const n=Object.assign({},o||null);return n.method="PATCH",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}}async function he(e,t,s){var m;const r=Object.assign({method:"GET"},s),o=R.FormData?r.body instanceof FormData:!1,n=o&&r.method!=="POST"&&r.method!=="PUT"?"POST":r.method,a=n==="GET"||n==="HEAD"||n==="DELETE";a&&r.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete r.body);const c=Object.assign(o||a?{}:{"Content-Type":R.Blob&&r.body instanceof Blob?r.body.type||"application/octet-stream":"application/json;charset=utf-8"},r.headers),i=r.params||{},d={};Object.keys(i).forEach(b=>{i[b]!==void 0&&(d[b]=de(i[b]))});const u=t.getFullUrl(e),l=fe(r.body),f=r.timeout||t.get("timeout"),g=await async function(){const b=t.get("requestTransformer");if(b)return await b({headers:c,params:d,method:n,url:u,body:l})}(),p=typeof g=="string"&&g?g:u;return(m=t.get("logHandler"))==null||m({type:"ready",url:p,method:n,headers:c,timeout:f,body:l}),{url:p,method:n,body:l,params:d,headers:c,timeout:f,abort:r.abort,credentials:r.credentials||t.get("credentials")||"same-origin"}}function de(e){return typeof e=="string"?e:Array.isArray(e)?e.join(","):e+""}function fe(e){if(e)return typeof e=="string"||e instanceof URLSearchParams||e instanceof ArrayBuffer||R.Blob&&e instanceof Blob||R.FormData&&e instanceof FormData?e:JSON.stringify(e)}const N="data",j="message";function ge(e,t,s,r,o){const n=o||r;return U(e)?je(n.ok||r.ok,e,t,s):pe(n.failed||r.failed,t,s)}const me=function(e){const t=[],s=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(s.messageField||j)+" 作为错误消息");break}const r=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),r.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(r.dataField||N)+" 作为响应数据,读取 "+(r.messageField||j)+" 作为提示消息"),r.statusField&&t.push(" 当 "+r.statusField+" 为 "+(r.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),r.ignoreMessage&&t.push(" 并忽略以下消息:"+r.ignoreMessage);break}return t.join(`
|
|
2
|
-
`)};function pe(e,t,s){const r=e||{resolve:"json",messageField:j},o={ok:!1,code:t,message:s,data:null};switch(r.resolve){case"body":o.message=P(s)||s;break;case"json":const{code:n,message:a}=ye(s,r.converter,r.statusField,r.messageField);o.code=n||t,o.message=P(s)||a;break}return o}function ye(e,t,s,r=j){if(!_(e))return{message:""};const o=A(T(e),t);return!o||!v(o)?{message:e}:{code:s?F(o,s):"",message:F(o,r)||e}}function F(e,t){const s=Array.isArray(t)?t:[t];for(const r of s)if(r in e)return be(e[r]);return""}function be(e){return e?typeof e=="string"?e:JSON.stringify(e):""}const we=/<title>([^<]+)<\/title>/i,Re=/<message>([^<]+)<\/message>/i;function P(e){const t=e.match(we);if(t)return t[1];const s=e.match(Re);return s?s[1]:""}function je(e,t,s,r){const o=e||{resolve:"body"},n={ok:!0,code:s,message:"",data:null};if(t===204||!r)return n;if(o.resolve==="body")return n.data=_(r)?A(T(r),e.converter):r,n;const a=A(T(r),e.converter);if(!a||!v(a))return n.ok=!1,n.code="ResponseFormatError",n.message="响应内容无法格式化为 Object",n;const c=o.statusField,i=o.statusOKValue||"",d=o.dataField||N,u=o.messageField||j,l=o.ignoreMessage||"";if(c&&!(c in a))return n.ok=!1,n.code="ResponseFieldMissing",n.message="响应内容找不到状态字段 "+c,n;const f=c?a[c]+"":"";return n.ok=c?f===i:!0,n.code=f||s,n.data=d===!0?a:d in a?a[d]:null,n.message=F(a,u),l&&n.message&&(Array.isArray(l)&&l.includes(n.message)||typeof l=="string"&&n.message===l)&&(n.message=""),n}function U(e){return e>=200&&e<400}function A(e,t){return t==="camelize"?k(e):t==="snakify"?E(e):e}const $e=Z("APIError");function ke(e){const t={};for(const o in e.headers)(o.startsWith("x-")||o.includes("trace")||o.includes("server")||/\b(?:id|uuid)\b/.test(o))&&(t[o]=e.headers[o]);const s=e.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),r=e.status<0?"unknown":e.status;return{sentryError:new $e(`${s} | ${r}${e.code?` | ${e.code}`:""}`),sentryTags:{...t,status:r,method:e.method,code:e.code||"unknown",message:e.message||"empty"},sentryExtra:{url:e.url,responseBody:e.body||"empty",responseHeaders:e.headers,rawError:e.error}}}function I(e){return e.reduce((t,[s,r])=>(s&&(t[s]=r||""),t),{})}function Ee(e,t,s,r){var g;const o=e.status,n=e.method,a=I(Object.entries(e.headers||{}).map(([p,m])=>[p.toLowerCase(),m])),{ok:c,code:i,data:d,message:u}=ge(o,e.statusText,e.body,s.get("responseRule"),r==null?void 0:r.responseRule);if(!U(o)){const p=ke({url:e.url,method:e.method,status:o,code:i,message:u,body:e.body,headers:a,error:e.rawError});(s.get("errorHandler")||Oe)({url:t,method:n,status:o,code:i,message:u,headers:a,rawError:e.rawError,responseBody:e.body,...p})}if(o<0)return S({ok:!1,status:o,code:e.statusText,headers:{},message:"",data:null},`${n} ${t} ${e.statusText}`,n,t,s,r);const l={ok:c,data:d,code:i,message:u,status:o,headers:a};(g=s.get("responseHandler"))==null||g({...l},n,t);const f=c?u:u||e.statusText;return S(l,f,n,t,s,r)}function S(e,t,s,r,o,n){const a=o.get("message"),c=a===!1||(n==null?void 0:n.message)===!1?!1:(n==null?void 0:n.message)||a;if(c!==!1){const i=typeof c=="function"?c(e,s,r,t):t;i instanceof Error?o.showMessage(!0,i.message,e.code,e.status):i&&typeof i=="object"&&"message"in i?o.showMessage(!1,i.message,e.code,e.status):o.showMessage(!e.ok,i,e.code,e.status)}return e}function Oe(e){const t={};for(const s in e)s.startsWith("sentry")||(t[s]=e[s]);console.error("RequestError",t)}async function K(e,t,s,r,o){const n=o||0,a=Math.max(0,Math.min(10,(r==null?void 0:r.maxRetry)??s.get("maxRetry")??0)),c=(r==null?void 0:r.retryResolve)??s.get("retryResolve"),i=s.get("logHandler")||V;i({type:"prepear",url:t,method:(r==null?void 0:r.method)||"GET",retry:n,maxRetry:a,message:n===0?"start":`retry ${n}/${a} start`,headers:r==null?void 0:r.headers,options:r});const d=Date.now(),u=await e(t,s,r),l=u.status,f=Date.now()-d,g=`[cost ${f}][${l}] ${l<0?u.body:""}`;i({type:"finished",url:t,method:u.method,retry:n,maxRetry:a,message:n===0?`finish ${g}`:`retry ${n}/${a} finish ${g}`,response:u,headers:u.headers,cost:f});const p=U(l);if(!a||c==="network"&&l>0||c==="status"&&p||Array.isArray(c)&&!c.includes(l)||typeof c=="function"&&c(u,n)!==!0||n>=a)return u;const m=(r==null?void 0:r.retryInterval)??s.get("retryInterval")??1e3;return await W(Math.max(100,m==="2EB"?Math.pow(2,n)*1e3:typeof m=="function"?m(n+1)||0:m)),await K(e,t,s,r,n+1)}exports.Ie=te;exports.NetRequestHandler=le;exports.RequestGlobalConfig=q;exports.RequestInteralError=C;exports.Zt=ae;exports.convertOptions=he;exports.fromEntries=I;exports.getResponseRulesDescription=me;exports.handleResponse=Ee;exports.lt=R;exports.retryRequest=K;exports.tt=O;
|