@seayoo-web/request 1.7.11 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Migeration.md ADDED
@@ -0,0 +1,7 @@
1
+ ## v1 to v2
2
+
3
+ `RequestOptions` 破坏性更新如下:
4
+
5
+ 1. 删除了 `requestHandler` 参数,可以使用 `requestTransformer` 来检查和修改请求数据
6
+ 2. `errorHandler` 处理函数的参数改为单一 option,原有平铺的参数被收入到 option 中
7
+ 3. `url` 现在不再支持通过前缀 `/` 来跳过全局 baseURL 的合并处理以保持跟社区习惯一致;跳过全局 baseURL 的唯一方法就是设置一个完整的 url 地址
package/README.md CHANGED
@@ -19,7 +19,10 @@
19
19
  6. 支持多实例,多端(浏览器,nodejs,微信小程序)
20
20
  7. get 请求函数支持并发缓存(默认缓存 500ms)
21
21
  8. 函数永不抛错,返回固定解析结构 { ok, data, status, headers, code, message }
22
- 9. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
22
+ 9. 提供格式化良好的 sentry 信息用于错误上报
23
+ 10. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
24
+
25
+ [大版本迁移说明](./Migeration.md)
23
26
 
24
27
  ## 示例
25
28
 
@@ -111,12 +114,11 @@ setConfig({ timeout: 10000 })
111
114
 
112
115
  类型:string
113
116
 
114
- 说明:需要以 / 开头或者是一个完整的 url 地址;此设置会给所有请求的 url 增加 baseURL 作为前缀,但以下两种情况除外
117
+ 说明:需要以 / 开头或者是一个完整的 url 地址;此设置会给所有请求的 url 增加 baseURL 作为前缀,但以下情况除外
115
118
 
116
119
  1. 请求时传入的 url 为完整 url,即以 http:// 或 https:// 开头
117
- 2. 请求时传入的 url 以 / 开头
118
120
 
119
- > node 环境仅仅支持完整 url 地址
121
+ > node 环境仅仅支持完整 url 地址作为 baseURL
120
122
 
121
123
  ### credentials
122
124
 
@@ -134,7 +136,7 @@ setConfig({ timeout: 10000 })
134
136
 
135
137
  ### cacheTTL
136
138
 
137
- 类型: number
139
+ 类型:number
138
140
 
139
141
  说明:用于控制 get 请求的缓冲时效,单位 ms,默认 500,设置为 0 则禁用缓冲
140
142
 
@@ -233,6 +235,8 @@ status 表示网络错误或者http 状态码错误时重试;
233
235
 
234
236
  也可以设置为一个重试检查函数,返回 true 则进行重试;
235
237
 
238
+ > 如果需要收集错误的重试信息,可以通过设置 retryResolve 为一个函数来检查或上报请求结果
239
+
236
240
  ### retryInterval
237
241
 
238
242
  类型:number | "2EB" | ((retryIndex: number) => number)
@@ -261,9 +265,20 @@ status 表示网络错误或者http 状态码错误时重试;
261
265
 
262
266
  ### errorHandler
263
267
 
264
- 类型:null | ((status: number, method: string, url: string, headers: Record<string, string>, rawError?: Error | ProgressEvent, responseBody?: string) => void)
265
-
266
- 说明:全局错误处理函数,仅仅在 http status 错误时触发,通常用于检查 401 未登录状态进行跳转登录,其中 rawError 为请求工具的原始错误,可用以进行 Sentry 信息上报;
268
+ 类型:null | ((data: {
269
+ status: number,
270
+ code: string,
271
+ method: string,
272
+ url: string,
273
+ headers: Record<string, string>,
274
+ rawError?: Error | ProgressEvent,
275
+ responseBody: string,
276
+ sentryError: Error,
277
+ sentryTags: Record<string, string | number>,
278
+ sentryExtra: Record<string, unknown>
279
+ }) => void)
280
+
281
+ 说明:全局错误处理函数,仅仅在 http status 错误时触发,通常用于检查 401 未登录状态进行跳转登录,其中 sentryError / sentryTags / sentryExtra 可用以进行 Sentry 信息上报;
267
282
 
268
283
  ### responseHandler
269
284
 
@@ -275,7 +290,7 @@ status 表示网络错误或者http 状态码错误时重试;
275
290
 
276
291
  类型:null | ((isError: boolean, message: string, code: string, status:number) => void)
277
292
 
278
- 说明:全局默认提示函数,isError 表示需要提示的消息是否为错误消息,message 为提示内容,code 为状态描述码,status 为http状态码
293
+ 说明:全局默认提示函数,isError 表示需要提示的消息是否为错误消息,message 为提示内容,code 为状态描述码,status 为 http 状态码
279
294
 
280
295
  ### logHandler
281
296
 
@@ -366,7 +381,7 @@ status 表示网络错误或者http 状态码错误时重试;
366
381
  说明:表示当前请求的状态信息,其可能值有
367
382
 
368
383
  - http statusText 当请求完成且无自定义错误码时,可能为空字符串
369
- - responseRule 中自定义的错误码字段所传递的值
384
+ - responseRule 中自定义的错误码字段所传递的值
370
385
  - "NetworkError","Failed","Aborted" 或 "Unknown" 网络错误或取消等异常情况
371
386
 
372
387
  ### message
@@ -388,8 +403,8 @@ status 表示网络错误或者http 状态码错误时重试;
388
403
  说明:响应的数据内容,其可能值为:
389
404
 
390
405
  - unknown:如果不提供类型守卫,则返回 unknown
391
- - null: 网络请求错误、类型守卫检查失败、服务器没有返回正确格式的 json 数据,则返回 null
392
- - T: 如果成功返回并通过类型守卫检查,则返回类型守卫对应的类型
406
+ - null:网络请求错误、类型守卫检查失败、服务器没有返回正确格式的 json 数据,则返回 null
407
+ - T: 如果成功返回并通过类型守卫检查,则返回类型守卫对应的类型
393
408
 
394
409
  ## 类型守卫
395
410
 
@@ -406,18 +421,22 @@ type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>
406
421
 
407
422
  ## Request函数
408
423
 
424
+ ## request\<T\>(url: string, options?: IRequestOptions)
425
+
426
+ 底层实现的 request 工具函数,未绑定类型守卫处理,返回的数据类型固定为 unknown;同时也未对请求做任何缓存处理;通常情况推荐使用以下的包装函数:get / post / head / del / put / patch
427
+
409
428
  ### get\<T\>(url: string, typeGard?: TypeGuardParam\<T\> | null, options?: IRequestOptions)
410
429
 
411
- - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址,或者以 / 开头,node 环境仅仅支持完整 url 地址
430
+ - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址
412
431
  - **typeGuard**: 可选类型守卫,如果设置为 null,则返回的内容为 unkonwn,否则就是经过类型守卫检查后的类型化数据,推荐传递类型守卫
413
432
  - **options**: 可选请求配置参数
414
433
 
415
- > 注意,get 请求默认设置 500ms 缓存,即对同一个请求(url+params)在 500ms 内不再重复发起请求,而是直接返回上一次的结果
434
+ > 注意,get 请求默认设置 500ms 缓存,即对同一个请求(url+params)在 500ms 内不再重复发起请求,而是直接返回上一次的结果,其中 params 会从 options.params 以及 url 中查找
416
435
 
417
436
  ### post(url: string, data: RequstBody, typeGard?: TypeGuardParam\<T\> | null, options?: IRequestOptions)
418
437
 
419
- - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址,或者以 / 开头,node 环境仅仅支持完整 url 地址
420
- - **data**: 请求发送的数据,等同于 IRequestOptions.body
438
+ - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址
439
+ - **data**: 请求发送的数据,会覆盖 IRequestOptions.body
421
440
  - **typeGuard**: 可选类型守卫,如果设置为 null,则返回的内容为 unkonwn,否则就是经过类型守卫检查后的类型化数据,推荐传递类型守卫,除非对响应内容不关心(比如 httpStatus 为 204 或 202)
422
441
  - **options**: 可选请求配置参数
423
442
 
@@ -501,4 +520,23 @@ setGlobalConfig({
501
520
  return message;
502
521
  }
503
522
  })
504
- ```
523
+ ```
524
+
525
+ Sentry 信息上报
526
+
527
+ ```js
528
+ import { captureException } from "@sentry/vue";
529
+
530
+ setGlobalConfig({
531
+ errorHandler({ status, sentryError, sentryTags, sentryExtra }) {
532
+ if(status === 401) {
533
+ return
534
+ }
535
+ captureException(sentryError, {
536
+ tags: sentryTags,
537
+ extra: sentryExtra,
538
+ })
539
+ }
540
+ })
541
+ ```
542
+
@@ -5,7 +5,7 @@ export declare class RequestGlobalConfig {
5
5
  constructor(config?: IRequestGlobalConfig);
6
6
  set(config: Partial<IRequestGlobalConfig>): void;
7
7
  get<T extends keyof IRequestGlobalConfig>(key: T): SomeRequired<IRequestGlobalConfig, "timeout" | "credentials" | "baseURL" | "maxRetry" | "cacheTTL" | "responseRule" | "retryInterval" | "retryResolve">[T];
8
- /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
8
+ /** 基于 baseURL 返回完整的 url 地址 */
9
9
  getFullUrl(url: string): string;
10
10
  /** 提示消息 */
11
11
  showMessage(isError: boolean, message: string | false, code: string, status: number): void;
@@ -1,4 +1,4 @@
1
- import type { TypeGuardParam, IRequestOptions, IRequestGlobalConfig, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./type";
1
+ import type { TypeGuardParam, IRequestOptions, IRequestGlobalConfig, IResponseResult, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./type";
2
2
  type RequestBody = NonNullable<IRequestOptions["body"]>;
3
3
  /** 工具函数主类 */
4
4
  export declare class NetRequestHandler {
@@ -9,7 +9,7 @@ export declare class NetRequestHandler {
9
9
  /**
10
10
  * 执行网络请求
11
11
  */
12
- private exec;
12
+ request(url: string, options?: IRequestOptions): Promise<IResponseResult<unknown>>;
13
13
  /**
14
14
  * 检查响应的数据类型
15
15
  */
@@ -35,6 +35,7 @@ export declare class NetRequestHandler {
35
35
  /**
36
36
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
37
37
  */
38
+ post(url: string): ResponseWithoutType;
38
39
  post(url: string, data: RequestBody): ResponseWithoutType;
39
40
  post(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
40
41
  post<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
@@ -47,12 +48,14 @@ export declare class NetRequestHandler {
47
48
  /**
48
49
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
49
50
  */
51
+ put(url: string): ResponseWithoutType;
50
52
  put(url: string, data: RequestBody): ResponseWithoutType;
51
53
  put(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
52
54
  put<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
53
55
  /**
54
56
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
55
57
  */
58
+ patch(url: string): ResponseWithoutType;
56
59
  patch(url: string, data: RequestBody): ResponseWithoutType;
57
60
  patch(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
58
61
  patch<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
@@ -0,0 +1,11 @@
1
+ import { IRequestGlobalConfig } from "./type";
2
+ /** 根据响应组织整理 sentry 上报信息 */
3
+ export declare function getSentryExceptionData(data: {
4
+ url: string;
5
+ status: number;
6
+ code: string;
7
+ method: string;
8
+ message: string;
9
+ body: string;
10
+ headers: Record<string, string>;
11
+ }): Pick<Parameters<NonNullable<IRequestGlobalConfig["errorHandler"]>>[0], "sentryError" | "sentryTags" | "sentryExtra">;
@@ -71,12 +71,6 @@ export type IRequestGlobalConfig = {
71
71
  baseURL?: string;
72
72
  /** 用于 get 请求的缓存时长,单位 ms,建议不小于 100 */
73
73
  cacheTTL?: number;
74
- /**
75
- * 请改用 requestTransformer
76
- *
77
- * @deprecated
78
- */
79
- requestHandler?: null | ((headers: Record<string, string>, params: Record<string, string>, method: string, url: string) => MaybePromise<void | string>);
80
74
  /**
81
75
  * 全局 request 转化函数,headers 和 params 为引用型数据可直接修改,如果返回字符串,则替换原来的 url 进行请求
82
76
  */
@@ -88,14 +82,26 @@ export type IRequestGlobalConfig = {
88
82
  url: string;
89
83
  body?: IBaseRequestBody;
90
84
  }) => MaybePromise<void | string>);
91
- /** 全局错误处理函数,仅仅在 statusCode 错误时触发 */
92
- errorHandler?: null | ((status: number, method: string, url: string, headers: Record<string, string>, rawError?: ERequestRawError, responseBody?: string) => void);
85
+ /** 全局错误处理函数,仅在 statusCode 错误时触发 */
86
+ errorHandler?: null | ((data: {
87
+ status: number;
88
+ code: string;
89
+ message: string;
90
+ method: string;
91
+ url: string;
92
+ headers: Record<string, string>;
93
+ rawError?: ERequestRawError;
94
+ responseBody: string;
95
+ sentryError: Error;
96
+ sentryTags: Record<string, string | number>;
97
+ sentryExtra: Record<string, unknown>;
98
+ }) => void);
93
99
  /** 全局响应处理函数,任意状态都会触发 */
94
100
  responseHandler?: null | ((result: IResponseResult, method: string, url: string) => void);
95
101
  /** 全局消息提示函数 */
96
102
  messageHandler?: null | ((isError: boolean, message: string, code: string, status: number) => void);
97
103
  /** 全局日志打印函数 */
98
- logHandler?: null | ((data: IRequestLog) => void);
104
+ logHandler?: null | ((log: IRequestLog) => void);
99
105
  } & Pick<IBaseRequestOptions, "credentials" | "timeout"> & IRetryRequestOptions & IOtherRequestOptions;
100
106
  /**
101
107
  * 失败重试策略:
@@ -142,7 +148,7 @@ export interface IResponseRule {
142
148
  dataField?: string | true;
143
149
  /** 消息字段名,仅在自定义状态失败时有效 */
144
150
  messageField?: string | string[];
145
- /** 忽略特定的消息内容,如果可能是多个值,则设置为数组 */
151
+ /** 忽略特定的消息内容,如果可能是多个值,则设置为数组,区分大小写 */
146
152
  ignoreMessage?: string | string[];
147
153
  };
148
154
  }
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./version-Gwc_LKMM.cjs"),y=require("./request.fetch-DiLKV6wn.cjs"),m=async function(t,o,e){return s.handleResponse(await s.retryRequest(w,t,o,e),t,o,e)};async function q(t,o,e,n){const r=e==null?void 0:e.body,i=(e==null?void 0:e.method)==="PUT"?"PUT":"POST";if(o instanceof Blob){const l=new s.RequestGlobalConfig(n),f=await w(t,l,{...e,method:i,body:o});return s.handleResponse(f,t,l,e)}const c=new FormData,u={...o};r instanceof Object&&Object.entries(r).forEach(([l,f])=>{f instanceof Blob?u[l]=f:Array.isArray(f)?f.forEach((a,g)=>{c.append(`${l}[${g}]`,String(a))}):c.append(l,String(f))});for(const l in u)c.append(l,u[l]);const b=new s.RequestGlobalConfig(n),p=await w(t,b,{...e,method:i,body:c});return s.handleResponse(p,t,b,e)}const w=async function(t,o,e){const n=await s.convertOptions(t,o,e),r=n.method,i=e==null?void 0:e.onUploadProgress,c=s.Wt(n.url,n.params);return await new Promise(u=>{let b=null,p=!1;const l=function(){p||(a.abort(),p=!0)};function f(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",l)}const a=new XMLHttpRequest;if(a.open(r,c,!0),i){let g=1;a.upload.addEventListener("progress",h=>{g=h.total,i({total:h.total,loaded:h.loaded})}),a.addEventListener("load",()=>{i({loaded:g,total:g})})}a.addEventListener("load",()=>{f(),u({url:c,method:r,status:a.status,statusText:a.statusText,headers:H(a),body:r==="HEAD"?"":a.responseText})}),a.addEventListener("error",g=>{f(),u({url:c,method:r,status:-1,statusText:"Failed",body:"",rawError:g})},!0),a.addEventListener("abort",()=>{f(),u({url:c,method:r,status:-1,statusText:"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(l,n.timeout))})};function H(t){const o={};if(!t)return o;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
2
- `).forEach(n=>{const r=n.trim();if(!r)return;const i=r.split(":"),c=i[0].trim();c&&(o[c]=(i[1]||"").trim())}),o}async function T(t,o,e={}){const n=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const r=e.callback+"";if(!t)return null;const i=s.Wt(t,e,!0);return new Promise(c=>{n[r]=function(u){if(r in window&&delete n[r],o(u))return u;console.warn("response type check faild",t,u),c(null)},s.xe(i).catch(function(){c(null),delete n[r]})})}async function E(t,o,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await s.xe(s.Wt(t,e,!0)).then(()=>{const r=n[e.var+""];return o(r)?r:(console.warn("response type check faild",t,r),null)}).catch(()=>null):null}const x=async function(t,o,e){return await q(t,o,e,{baseURL:d.getConfig("baseURL"),logHandler:d.getConfig("logHandler"),errorHandler:d.getConfig("errorHandler"),requestTransformer:d.getConfig("requestTransformer"),messageHandler:d.getConfig("messageHandler"),responseHandler:d.getConfig("responseHandler")})};function R(t){if(!s.Support.window)throw new Error("Default Module Only Support In Browser");return s.Support.fetch?new s.NetRequestHandler(y.fetchRequest,t):new s.NetRequestHandler(m,t)}const d=R(),C=d.setConfig,S=d.head,v=d.get,j=d.post,L=d.del,D=d.put,U=d.patch;exports.getResponseRulesDescription=s.getResponseRulesDescription;exports.version=s.version;exports.NetRequest=R;exports.del=L;exports.get=v;exports.head=S;exports.jsonp=T;exports.jsonx=E;exports.patch=U;exports.post=j;exports.put=D;exports.setGlobalConfig=C;exports.upload=x;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./version-8nwh2c5_.cjs"),y=require("./request.fetch-B7HV6dbq.cjs"),m=async function(t,o,e){return s.handleResponse(await s.retryRequest(w,t,o,e),t,o,e)};async function q(t,o,e,n){const r=e==null?void 0:e.body,i=(e==null?void 0:e.method)==="PUT"?"PUT":"POST";if(o instanceof Blob){const d=new s.RequestGlobalConfig(n),f=await w(t,d,{...e,method:i,body:o});return s.handleResponse(f,t,d,e)}const c=new FormData,u={...o};r instanceof Object&&Object.entries(r).forEach(([d,f])=>{f instanceof Blob?u[d]=f:Array.isArray(f)?f.forEach((a,g)=>{c.append(`${d}[${g}]`,String(a))}):c.append(d,String(f))});for(const d in u)c.append(d,u[d]);const b=new s.RequestGlobalConfig(n),p=await w(t,b,{...e,method:i,body:c});return s.handleResponse(p,t,b,e)}const w=async function(t,o,e){const n=await s.convertOptions(t,o,e),r=n.method,i=e==null?void 0:e.onUploadProgress,c=s.vt(n.url,n.params);return await new Promise(u=>{let b=null,p=!1;const d=function(){p||(a.abort(),p=!0)};function f(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",d)}const a=new XMLHttpRequest;if(a.open(r,c,!0),i){let g=1;a.upload.addEventListener("progress",h=>{g=h.total,i({total:h.total,loaded:h.loaded})}),a.addEventListener("load",()=>{i({loaded:g,total:g})})}a.addEventListener("load",()=>{f(),u({url:c,method:r,status:a.status,statusText:a.statusText,headers:H(a),body:r==="HEAD"?"":a.responseText})}),a.addEventListener("error",g=>{f(),u({url:c,method:r,status:-1,statusText:"Failed",body:"",rawError:g})},!0),a.addEventListener("abort",()=>{f(),u({url:c,method:r,status:-1,statusText:"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",d),n.timeout>0&&(b=setTimeout(d,n.timeout))})};function H(t){const o={};if(!t)return o;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
2
+ `).forEach(n=>{const r=n.trim();if(!r)return;const i=r.split(":"),c=i[0].trim();c&&(o[c]=(i[1]||"").trim())}),o}async function E(t,o,e={}){const n=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const r=e.callback+"";if(!t)return null;const i=s.vt(t,e,!0);return new Promise(c=>{n[r]=function(u){if(r in window&&delete n[r],o(u))return u;console.warn("response type check faild",t,u),c(null)},s.Ee(i).catch(function(){c(null),delete n[r]})})}async function T(t,o,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await s.Ee(s.vt(t,e,!0)).then(()=>{const r=n[e.var+""];return o(r)?r:(console.warn("response type check faild",t,r),null)}).catch(()=>null):null}const v=async function(t,o,e){return await q(t,o,e,{baseURL:l.getConfig("baseURL"),logHandler:l.getConfig("logHandler"),errorHandler:l.getConfig("errorHandler"),requestTransformer:l.getConfig("requestTransformer"),messageHandler:l.getConfig("messageHandler"),responseHandler:l.getConfig("responseHandler")})};function R(t){if(!s.Support.window)throw new Error("Default Module Only Support In Browser");return s.Support.fetch?new s.NetRequestHandler(y.fetchRequest,t):new s.NetRequestHandler(m,t)}const l=R(),C=l.setConfig,S=l.request,x=l.head,j=l.get,L=l.post,D=l.del,U=l.put,k=l.patch;exports.getResponseRulesDescription=s.getResponseRulesDescription;exports.version=s.version;exports.NetRequest=R;exports.del=D;exports.get=j;exports.head=x;exports.jsonp=E;exports.jsonx=T;exports.patch=k;exports.post=L;exports.put=U;exports.request=S;exports.setGlobalConfig=C;exports.upload=v;
package/dist/index.d.ts CHANGED
@@ -17,6 +17,10 @@ export declare function NetRequest(config?: IRequestGlobalConfig): NetRequestHan
17
17
  * 设置全局默认的 Request Config
18
18
  */
19
19
  export declare const setGlobalConfig: (config: IRequestGlobalConfig) => void;
20
+ /**
21
+ * 发送一个网络请求
22
+ */
23
+ export declare const request: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => Promise<import("./inc/type").IResponseResult<unknown>>;
20
24
  /**
21
25
  * 发送一个 HEAD 请求
22
26
  */
@@ -33,6 +37,7 @@ export declare const get: {
33
37
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
34
38
  */
35
39
  export declare const post: {
40
+ (url: string): import("./inc/type").ResponseWithoutType;
36
41
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
37
42
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
38
43
  <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
@@ -49,6 +54,7 @@ export declare const del: {
49
54
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
50
55
  */
51
56
  export declare const put: {
57
+ (url: string): import("./inc/type").ResponseWithoutType;
52
58
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
53
59
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
54
60
  <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
@@ -57,6 +63,7 @@ export declare const put: {
57
63
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
58
64
  */
59
65
  export declare const patch: {
66
+ (url: string): import("./inc/type").ResponseWithoutType;
60
67
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
61
68
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
62
69
  <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
package/dist/index.js CHANGED
@@ -1,27 +1,27 @@
1
- import { h as w, r as E, R as y, c as T, W as p, x, S as R, N as H } from "./version-brZzjGeL.js";
2
- import { g as $, v as z } from "./version-brZzjGeL.js";
3
- import { f as q } from "./request.fetch-BUHa5oaL.js";
4
- const C = async function(t, a, e) {
5
- return w(await E(m, t, a, e), t, a, e);
1
+ import { h as w, r as q, R as y, c as T, v as p, E as H, S as R, N as E } from "./version-DZdKrbQd.js";
2
+ import { g as I, a as J } from "./version-DZdKrbQd.js";
3
+ import { f as x } from "./request.fetch-DhEWVivW.js";
4
+ const v = async function(t, a, e) {
5
+ return w(await q(m, t, a, e), t, a, e);
6
6
  };
7
- async function L(t, a, e, n) {
7
+ async function C(t, a, e, n) {
8
8
  const r = e == null ? void 0 : e.body, d = (e == null ? void 0 : e.method) === "PUT" ? "PUT" : "POST";
9
9
  if (a instanceof Blob) {
10
- const c = new y(n), u = await m(t, c, {
10
+ const l = new y(n), u = await m(t, l, {
11
11
  ...e,
12
12
  method: d,
13
13
  body: a
14
14
  });
15
- return w(u, t, c, e);
15
+ return w(u, t, l, e);
16
16
  }
17
17
  const s = new FormData(), i = { ...a };
18
- r instanceof Object && Object.entries(r).forEach(([c, u]) => {
19
- u instanceof Blob ? i[c] = u : Array.isArray(u) ? u.forEach((o, f) => {
20
- s.append(`${c}[${f}]`, String(o));
21
- }) : s.append(c, String(u));
18
+ r instanceof Object && Object.entries(r).forEach(([l, u]) => {
19
+ u instanceof Blob ? i[l] = u : Array.isArray(u) ? u.forEach((o, f) => {
20
+ s.append(`${l}[${f}]`, String(o));
21
+ }) : s.append(l, String(u));
22
22
  });
23
- for (const c in i)
24
- s.append(c, i[c]);
23
+ for (const l in i)
24
+ s.append(l, i[l]);
25
25
  const b = new y(n), h = await m(t, b, {
26
26
  ...e,
27
27
  method: d,
@@ -33,11 +33,11 @@ const m = async function(t, a, e) {
33
33
  const n = await T(t, a, e), r = n.method, d = e == null ? void 0 : e.onUploadProgress, s = p(n.url, n.params);
34
34
  return await new Promise((i) => {
35
35
  let b = null, h = !1;
36
- const c = function() {
36
+ const l = function() {
37
37
  h || (o.abort(), h = !0);
38
38
  };
39
39
  function u() {
40
- b !== null && clearTimeout(b), n.abort && n.abort.removeEventListener("abort", c);
40
+ b !== null && clearTimeout(b), n.abort && n.abort.removeEventListener("abort", l);
41
41
  }
42
42
  const o = new XMLHttpRequest();
43
43
  if (o.open(r, s, !0), d) {
@@ -54,7 +54,7 @@ const m = async function(t, a, e) {
54
54
  method: r,
55
55
  status: o.status,
56
56
  statusText: o.statusText,
57
- headers: S(o),
57
+ headers: L(o),
58
58
  body: r === "HEAD" ? "" : o.responseText
59
59
  });
60
60
  }), o.addEventListener(
@@ -80,10 +80,10 @@ const m = async function(t, a, e) {
80
80
  });
81
81
  }), Object.entries(n.headers).forEach(([f, g]) => {
82
82
  o.setRequestHeader(f, g);
83
- }), n.credentials === "include" && (o.withCredentials = !0), o.send(n.body || void 0), n.abort && n.abort.addEventListener("abort", c), n.timeout > 0 && (b = setTimeout(c, n.timeout));
83
+ }), n.credentials === "include" && (o.withCredentials = !0), o.send(n.body || void 0), n.abort && n.abort.addEventListener("abort", l), n.timeout > 0 && (b = setTimeout(l, n.timeout));
84
84
  });
85
85
  };
86
- function S(t) {
86
+ function L(t) {
87
87
  const a = {};
88
88
  if (!t)
89
89
  return a;
@@ -109,46 +109,47 @@ async function k(t, a, e = {}) {
109
109
  if (r in window && delete n[r], a(i))
110
110
  return i;
111
111
  console.warn("response type check faild", t, i), s(null);
112
- }, x(d).catch(function() {
112
+ }, H(d).catch(function() {
113
113
  s(null), delete n[r];
114
114
  });
115
115
  });
116
116
  }
117
117
  async function D(t, a, e = {}) {
118
118
  const n = window;
119
- return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), t ? await x(p(t, e, !0)).then(() => {
119
+ return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), t ? await H(p(t, e, !0)).then(() => {
120
120
  const r = n[e.var + ""];
121
121
  return a(r) ? r : (console.warn("response type check faild", t, r), null);
122
122
  }).catch(() => null) : null;
123
123
  }
124
124
  const O = async function(t, a, e) {
125
- return await L(t, a, e, {
126
- baseURL: l.getConfig("baseURL"),
127
- logHandler: l.getConfig("logHandler"),
128
- errorHandler: l.getConfig("errorHandler"),
129
- requestTransformer: l.getConfig("requestTransformer"),
130
- messageHandler: l.getConfig("messageHandler"),
131
- responseHandler: l.getConfig("responseHandler")
125
+ return await C(t, a, e, {
126
+ baseURL: c.getConfig("baseURL"),
127
+ logHandler: c.getConfig("logHandler"),
128
+ errorHandler: c.getConfig("errorHandler"),
129
+ requestTransformer: c.getConfig("requestTransformer"),
130
+ messageHandler: c.getConfig("messageHandler"),
131
+ responseHandler: c.getConfig("responseHandler")
132
132
  });
133
133
  };
134
- function v(t) {
134
+ function S(t) {
135
135
  if (!R.window)
136
136
  throw new Error("Default Module Only Support In Browser");
137
- return R.fetch ? new H(q, t) : new H(C, t);
137
+ return R.fetch ? new E(x, t) : new E(v, t);
138
138
  }
139
- const l = v(), P = l.setConfig, A = l.head, M = l.get, N = l.post, B = l.del, F = l.put, X = l.patch;
139
+ const c = S(), P = c.setConfig, A = c.request, M = c.head, N = c.get, B = c.post, F = c.del, X = c.put, G = c.patch;
140
140
  export {
141
- v as NetRequest,
142
- B as del,
143
- M as get,
144
- $ as getResponseRulesDescription,
145
- A as head,
141
+ S as NetRequest,
142
+ F as del,
143
+ N as get,
144
+ I as getResponseRulesDescription,
145
+ M as head,
146
146
  k as jsonp,
147
147
  D as jsonx,
148
- X as patch,
149
- N as post,
150
- F as put,
148
+ G as patch,
149
+ B as post,
150
+ X as put,
151
+ A as request,
151
152
  P as setGlobalConfig,
152
153
  O as upload,
153
- z as version
154
+ J as version
154
155
  };
package/dist/node.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("node:http"),R=require("node:https"),o=require("./version-Gwc_LKMM.cjs"),g=require("./request.fetch-DiLKV6wn.cjs"),w=async function(s,u,c){return o.handleResponse(await o.retryRequest(S,s,u,c),s,u,c)},S=async function(s,u,c){const t=await o.convertOptions(s,u,c);if(!o.G(t.url))return{url:t.url,method:t.method,status:-1,statusText:"URLFormatError",headers:{},body:""};const f=/^https:\/\//i.test(t.url)?R:y,a=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(r=>a.searchParams.set(r,i[r]));const q=t.method==="HEAD";return new Promise(r=>{const d=f.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(e){const p=[];e.on("data",h=>p.push(h)),e.on("end",()=>{const h=o.fromEntries(Object.entries(e.headers).map(([b,m])=>[b.toLowerCase(),Array.isArray(m)?m.join(","):m]));r({url:a.toString(),method:t.method,status:e.statusCode||-1,statusText:e.statusMessage||"Unknown",headers:h,body:q?"":Buffer.concat(p).toString("utf-8")})})});d.on("error",e=>{r({url:a.toString(),method:t.method,status:-1,statusText:e.name||"Unknown",body:e.message,rawError:e})}),d.on("timeout",()=>{r({url:a.toString(),method:t.method,status:-1,statusText:"Timeout",body:""})}),t.body&&d.write(t.body),d.end()})};function l(s){return o.Support.fetch?new o.NetRequestHandler(g.fetchRequest,s):new o.NetRequestHandler(w,s)}const n=l(),T=n.setConfig,j=n.head,C=n.get,E=n.post,N=n.del,O=n.put,U=n.patch;exports.version=o.version;exports.NetRequest=l;exports.del=N;exports.get=C;exports.head=j;exports.patch=U;exports.post=E;exports.put=O;exports.setGlobalConfig=T;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("node:http"),R=require("node:https"),o=require("./version-8nwh2c5_.cjs"),g=require("./request.fetch-B7HV6dbq.cjs"),w=async function(s,u,c){return o.handleResponse(await o.retryRequest(S,s,u,c),s,u,c)},S=async function(s,u,c){const t=await o.convertOptions(s,u,c);if(!o.K(t.url))return{url:t.url,method:t.method,status:-1,statusText:"URLFormatError",headers:{},body:""};const f=/^https:\/\//i.test(t.url)?R:y,a=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(r=>a.searchParams.set(r,i[r]));const q=t.method==="HEAD";return new Promise(r=>{const d=f.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(e){const p=[];e.on("data",h=>p.push(h)),e.on("end",()=>{const h=o.fromEntries(Object.entries(e.headers).map(([b,m])=>[b.toLowerCase(),Array.isArray(m)?m.join(","):m]));r({url:a.toString(),method:t.method,status:e.statusCode||-1,statusText:e.statusMessage||"Unknown",headers:h,body:q?"":Buffer.concat(p).toString("utf-8")})})});d.on("error",e=>{r({url:a.toString(),method:t.method,status:-1,statusText:e.name||"Unknown",body:e.message,rawError:e})}),d.on("timeout",()=>{r({url:a.toString(),method:t.method,status:-1,statusText:"Timeout",body:""})}),t.body&&d.write(t.body),d.end()})};function l(s){return o.Support.fetch?new o.NetRequestHandler(g.fetchRequest,s):new o.NetRequestHandler(w,s)}const n=l(),T=n.setConfig,j=n.head,C=n.get,E=n.post,N=n.del,O=n.put,U=n.patch;exports.version=o.version;exports.NetRequest=l;exports.del=N;exports.get=C;exports.head=j;exports.patch=U;exports.post=E;exports.put=O;exports.setGlobalConfig=T;
package/dist/node.d.ts CHANGED
@@ -26,6 +26,7 @@ export declare const get: {
26
26
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
27
27
  */
28
28
  export declare const post: {
29
+ (url: string): import("./inc/type").ResponseWithoutType;
29
30
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
30
31
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
31
32
  <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
@@ -42,6 +43,7 @@ export declare const del: {
42
43
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
43
44
  */
44
45
  export declare const put: {
46
+ (url: string): import("./inc/type").ResponseWithoutType;
45
47
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
46
48
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
47
49
  <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
@@ -50,6 +52,7 @@ export declare const put: {
50
52
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
51
53
  */
52
54
  export declare const patch: {
55
+ (url: string): import("./inc/type").ResponseWithoutType;
53
56
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
54
57
  (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
55
58
  <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
package/dist/node.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import y from "node:http";
2
2
  import R from "node:https";
3
- import { h as w, r as q, c as g, G as x, f as S, S as E, N as p } from "./version-brZzjGeL.js";
4
- import { v as z } from "./version-brZzjGeL.js";
5
- import { f as T } from "./request.fetch-BUHa5oaL.js";
3
+ import { h as w, r as q, c as g, K as x, f as S, S as E, N as p } from "./version-DZdKrbQd.js";
4
+ import { a as z } from "./version-DZdKrbQd.js";
5
+ import { f as T } from "./request.fetch-DhEWVivW.js";
6
6
  const U = async function(o, a, u) {
7
7
  return w(await q(j, o, a, u), o, a, u);
8
8
  }, j = async function(o, a, u) {
@@ -67,15 +67,15 @@ const U = async function(o, a, u) {
67
67
  function C(o) {
68
68
  return E.fetch ? new p(T, o) : new p(U, o);
69
69
  }
70
- const s = C(), H = s.setConfig, k = s.head, G = s.get, P = s.post, B = s.del, D = s.put, F = s.patch;
70
+ const s = C(), H = s.setConfig, k = s.head, P = s.get, B = s.post, D = s.del, F = s.put, G = s.patch;
71
71
  export {
72
72
  C as NetRequest,
73
- B as del,
74
- G as get,
73
+ D as del,
74
+ P as get,
75
75
  k as head,
76
- F as patch,
77
- P as post,
78
- D as put,
76
+ G as patch,
77
+ B as post,
78
+ F as put,
79
79
  H as setGlobalConfig,
80
80
  z as version
81
81
  };
@@ -1 +1 @@
1
- "use strict";const r=require("./version-Gwc_LKMM.cjs"),h=async function(s,o,n){return r.handleResponse(await r.retryRequest(b,s,o,n),s,o,n)},b=async function(s,o,n){const t=await r.convertOptions(s,o,n),i=new URL(t.url),d=t.params;d instanceof Object&&Object.keys(d).forEach(a=>i.searchParams.set(a,d[a]));const e=r.Support.AbortController?new AbortController:null;function u(){e&&!e.signal.aborted&&e.abort()}t.abort&&t.abort.addEventListener("abort",u);const c=t.timeout>0?setTimeout(u,t.timeout):null;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:e==null?void 0:e.signal,redirect:"follow"}).then(async a=>({url:i.toString(),method:t.method,status:a.status,statusText:a.statusText,headers:r.fromEntries([...a.headers.entries()]),body:t.method==="HEAD"?"":await a.text()})).catch(a=>({url:i.toString(),method:t.method,status:-1,statusText:e!=null&&e.signal.aborted?"Aborted":"NetworkError",body:String(a),rawError:e!=null&&e.signal.aborted?void 0:a})).finally(()=>{c!==null&&clearTimeout(c),t.abort&&t.abort.removeEventListener("abort",u)})};exports.fetchRequest=h;
1
+ "use strict";const r=require("./version-8nwh2c5_.cjs"),h=async function(s,o,n){return r.handleResponse(await r.retryRequest(b,s,o,n),s,o,n)},b=async function(s,o,n){const t=await r.convertOptions(s,o,n),i=new URL(t.url),d=t.params;d instanceof Object&&Object.keys(d).forEach(a=>i.searchParams.set(a,d[a]));const e=r.Support.AbortController?new AbortController:null;function u(){e&&!e.signal.aborted&&e.abort()}t.abort&&t.abort.addEventListener("abort",u);const c=t.timeout>0?setTimeout(u,t.timeout):null;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:e==null?void 0:e.signal,redirect:"follow"}).then(async a=>({url:i.toString(),method:t.method,status:a.status,statusText:a.statusText,headers:r.fromEntries([...a.headers.entries()]),body:t.method==="HEAD"?"":await a.text()})).catch(a=>({url:i.toString(),method:t.method,status:-1,statusText:e!=null&&e.signal.aborted?"Aborted":"NetworkError",body:String(a),rawError:e!=null&&e.signal.aborted?void 0:a})).finally(()=>{c!==null&&clearTimeout(c),t.abort&&t.abort.removeEventListener("abort",u)})};exports.fetchRequest=h;
@@ -1,4 +1,4 @@
1
- import { h as c, r as h, c as b, S as m, f as l } from "./version-brZzjGeL.js";
1
+ import { h as c, r as h, c as b, S as m, f as l } from "./version-DZdKrbQd.js";
2
2
  const y = async function(s, r, o) {
3
3
  return c(await h(f, s, r, o), s, r, o);
4
4
  }, f = async function(s, r, o) {
@@ -0,0 +1,2 @@
1
+ "use strict";var K=Object.defineProperty;var N=(e,t,s)=>t in e?K(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var y=(e,t,s)=>(N(e,typeof t!="symbol"?t+"":t,s),s);const p=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},w={fetch:"fetch"in p,window:"window"in p,FormData:"FormData"in p,Blob:"Blob"in p,wx:"wx"in p,TextDecoder:"TextDecoder"in p,AbortController:"AbortController"in p};function q(e){return e.reduce((t,[s,r])=>(s&&(t[s]=r||""),t),{})}function G(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}function J(){}function V(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&&Error.captureStackTrace(this,this.constructor)}}}function j(e){return e?e[0].toLowerCase()+e.slice(1):""}const _=/_\w*/,B=/-\w*/;function A(e){const t=_.test(e)?e.replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(s,r)=>r.toUpperCase()):B.test(e)?e.replace(/(?:^-*|-*$)/g,"").replace(/-+(\w)/g,(s,r)=>r.toUpperCase()):e;return j(t)}function D(e){return _.test(e)?j(e).replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(t,s)=>"_"+s.toLowerCase()):B.test(e)?j(e.replace(/(?:^-*|-*$)/g,"")).replace(/-+(\w)/g,(t,s)=>"_"+s.toLowerCase()):j(e).replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const W=/^(?:https?:)?\/\/.+$/i,z=/^https?:\/\/.+$/i,Q=/^\{[\d\D]*\}$/,Z=/^\[[\d\D]*\]$/;function O(e,t=!1){return t?W.test(e):z.test(e)}function X(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 S(e){return Q.test(e)||Z.test(e)}function k(e,t){try{const s=JSON.parse(e);return t?t(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);function E(e,t=!1){return typeof e=="string"?A(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?E(s):typeof s=="object"&&s?E(s,!0):s):v(e)?Object.keys(e).reduce((s,r)=>{const a=A(String(r)),n=a.charAt(0).toLowerCase()+a.slice(1);return s[n]=t?e[r]:E(e[r]),s},{}):e}function $(e,t=!1){return typeof e=="string"?D(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?$(s):typeof s=="object"&&s?$(s,t):s):v(e)?Object.keys(e).reduce((s,r)=>{const a=D(String(r));return s[a]=t?e[r]:$(e[r]),s},{}):e}async function Y(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 ee(e,t="数据未能正确识别"){return typeof e=="function"?{guard:e,message:t}:{guard:e.guard,message:e.message||t}}function te(e,t=""){return!t||O(e,!0)?M(e):(M(t)+"/"+e).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function M(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 se(e,t){const s={};return(e.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(r){const a=r.split("="),n=a[0],o=decodeURIComponent(a[1]||"");s[n]!==void 0?s[n]+=","+o:s[n]=o}),t!==!0?s[t]||"":s}function re(e,t){if(t){if(t===!0)return e.replace(/\?[^#]*/,"")}else return e;const s=e.split("#"),r=s[0].split("?"),a=r[0],n=r.length>1?r[1]:"",o=s.length>1?"#"+s[1]:"",c=typeof t=="string"?[t]:Array.isArray(t)?t:[];return!c.length||!n?s[0]+o:(c.map(i=>i.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(a+"?"+n.replace(new RegExp("(?:^|&)(?:"+c.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function ne(e,t,s=!1){const r=typeof t=="string"?t:Object.keys(t).map(o=>`${o}=${encodeURIComponent(t[o])}`).join("&");if(!r)return e;const a=e.split("#");s&&(a[0]=re(a[0],(r.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const n=a[0].indexOf("?")+1?"&":"?";return(a[0]+n+r+(a.length>1?"#"+a[1]:"")).replace(/\?&/,"?")}function ae(e){const t=e.match(/(?:\?|&)([^=]+)(?:&|$)/g);return t?t.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class oe{constructor(t=500){y(this,"ttl");y(this,"cache");this.cache={},this.ttl=Math.max(t,0)}getKey(t,s){const r=t.replace(/#.+/,""),a=r.replace(/\?.+/g,""),n=Object.assign(se(r,!0),s),o=ae(r),c=Object.keys(n).sort().map(i=>`${i}#${n[i]}`);return`${a}_${c.join(",")}_${o.join(",")}`}updateTTL(t){this.ttl=Math.max(t,0)}get(t){if(this.ttl===0)return null;const s=this.cache[t];return s?s.ttl<Date.now()?(delete this.cache[t],null):s.res:null}set(t,s){this.ttl!==0&&(this.cache[t]={ttl:Date.now()+this.ttl,res:s})}}const U="UnexpectResponse";function ce(e,t,s,r){if(t.ok&&!X(t.data)&&r){const a=ee(r,"响应数据未能正确识别");return a.guard(t.data)||(s.showMessage(!0,`${e} ${a.message}`,t.code,t.status),console.error(U,e,t.data),t.data=null,t.code=U,t.message=a.message),t}return t}class x{constructor(t){y(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});t&&this.set(t)}set(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!O(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)}get(t){return this.config[t]}getFullUrl(t){return te(t,this.config.baseURL)}showMessage(t,s,r,a){this.config.messageHandler&&s&&this.config.messageHandler(t,s,r,a)}}class ie{constructor(t,s){y(this,"agent");y(this,"config");y(this,"cache");this.config=new x(s),this.agent=t,this.cache=new oe(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 ce(t,s,this.config,r)}setConfig(t){this.config.set(t),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(t){return this.config.get(t)}async head(t,s){const r=Object.assign({},s||null);return r.method="HEAD",this.guard(t,await this.request(t,r),null)}async get(t,s,r){const a=Object.assign({},r||null);a.method="GET";const n=this.cache.getKey(t,a.params),o=this.cache.get(n);if(o)return this.guard(t,await o,s||null);const c=this.request(t,a);return this.cache.set(n,c),this.guard(t,await c,s||null)}async post(t,s,r,a){const n=Object.assign({},a||null);return n.method="POST",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async del(t,s,r){const a=Object.assign({},r||null);return a.method="DELETE",this.guard(t,await this.request(t,a),s||null)}async put(t,s,r,a){const n=Object.assign({},a||null);return n.method="PUT",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async patch(t,s,r,a){const n=Object.assign({},a||null);return n.method="PATCH",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}}const H="data",R="message";function ue(e,t,s,r,a){const n=a||r;return T(e)?ye(n.ok||r.ok,e,t,s):he(n.failed||r.failed,t,s)}const le=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||R)+" 作为错误消息");break}const r=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),r.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(r.dataField||H)+" 作为响应数据,读取 "+(r.messageField||R)+" 作为提示消息"),r.statusField&&t.push(" 当 "+r.statusField+" 为 "+(r.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),r.ignoreMessage&&t.push(" 并忽略以下消息:"+r.ignoreMessage);break}return t.join(`
2
+ `)};function he(e,t,s){const r=e||{resolve:"json",messageField:R},a={ok:!1,code:t,message:s,data:null};switch(r.resolve){case"body":a.message=L(s)||s;break;case"json":const{code:n,message:o}=de(s,r.converter,r.statusField,r.messageField);a.code=n||t,a.message=L(s)||o;break}return a}function de(e,t,s,r=R){if(!S(e))return{message:""};const a=F(k(e),t);return!a||!v(a)?{message:e}:{code:s?C(a,s):"",message:C(a,r)||e}}function C(e,t){const s=Array.isArray(t)?t:[t];for(const r of s)if(r in e)return ge(e[r]);return""}function ge(e){return e?typeof e=="string"?e:JSON.stringify(e):""}const fe=/<title>([^<]+)<\/title>/i,me=/<message>([^<]+)<\/message>/i;function L(e){const t=e.match(fe);if(t)return t[1];const s=e.match(me);return s?s[1]:""}function ye(e,t,s,r){const a=e||{resolve:"body"},n={ok:!0,code:s,message:"",data:null};if(t===204||!r)return n;if(a.resolve==="body")return n.data=S(r)?F(k(r),e.converter):r,n;const o=F(k(r),e.converter);if(!o||!v(o))return n.ok=!1,n.code="ResponseFormatError",n.message="响应内容无法格式化为 Object",n;const c=a.statusField,i=a.statusOKValue||"",h=a.dataField||H,u=a.messageField||R,l=a.ignoreMessage||"";if(c&&!(c in o))return n.ok=!1,n.code="ResponseFieldMissing",n.message="响应内容找不到状态字段 "+c,n;const d=c?o[c]+"":"";return n.ok=c?d===i:!0,n.code=d||s,n.data=h===!0?o:h in o?o[h]:null,n.message=C(o,u),l&&n.message&&(Array.isArray(l)&&l.includes(n.message)||typeof l=="string"&&n.message===l)&&(n.message=""),n}function T(e){return e>=200&&e<400}function F(e,t){return t==="camelize"?E(e):t==="snakify"?$(e):e}async function I(e,t,s,r,a){const n=a||0,o=Math.max(0,Math.min(10,(r==null?void 0:r.maxRetry)??s.get("maxRetry")??0)),c=(r==null?void 0:r.retryResolve)??s.get("retryResolve"),i=s.get("logHandler")||J;i({type:"prepear",url:t,method:(r==null?void 0:r.method)||"GET",retry:n,maxRetry:o,message:n===0?"start":`retry ${n}/${o} start`,headers:r==null?void 0:r.headers,options:r});const h=Date.now(),u=await e(t,s,r),l=u.status,d=Date.now()-h,g=`[cost ${d}][${l}] ${l<0?u.body:""}`;i({type:"finished",url:t,method:u.method,retry:n,maxRetry:o,message:n===0?`finish ${g}`:`retry ${n}/${o} finish ${g}`,response:u,headers:u.headers,cost:d});const m=T(l);if(!o||c==="network"&&l>0||c==="status"&&m||Array.isArray(c)&&!c.includes(l)||typeof c=="function"&&c(u,n)!==!0||n>=o)return u;const f=(r==null?void 0:r.retryInterval)??s.get("retryInterval")??1e3;return await G(Math.max(100,f==="2EB"?Math.pow(2,n)*1e3:typeof f=="function"?f(n+1)||0:f)),await I(e,t,s,r,n+1)}async function pe(e,t,s){var f;const r=Object.assign({method:"GET"},s),a=w.FormData?r.body instanceof FormData:!1,n=a&&r.method!=="POST"&&r.method!=="PUT"?"POST":r.method,o=n==="GET"||n==="HEAD"||n==="DELETE";o&&r.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete r.body);const c=Object.assign(a||o?{}:{"Content-Type":w.Blob&&r.body instanceof Blob?r.body.type||"application/octet-stream":"application/json;charset=utf-8"},r.headers),i=r.params||{},h={};Object.keys(i).forEach(b=>{i[b]!==void 0&&(h[b]=be(i[b]))});const u=t.getFullUrl(e),l=we(r.body),d=r.timeout||t.get("timeout"),g=await async function(){const b=t.get("requestTransformer");if(b)return await b({headers:c,params:h,method:n,url:u,body:l})}(),m=typeof g=="string"&&g?g:u;return(f=t.get("logHandler"))==null||f({type:"ready",url:m,method:n,headers:c,timeout:d,body:l}),{url:m,method:n,body:l,params:h,headers:c,timeout:d,abort:r.abort,credentials:r.credentials||t.get("credentials")}}function be(e){return typeof e=="string"?e:Array.isArray(e)?e.join(","):e+""}function we(e){if(e)return typeof e=="string"||e instanceof URLSearchParams||e instanceof ArrayBuffer||w.Blob&&e instanceof Blob||w.FormData&&e instanceof FormData?e:JSON.stringify(e)}const Re=V("APIError");function je(e){const t={};for(const s in e.headers)(s.startsWith("x-")||s.includes("trace")||s.includes("server")||/\bid\b/.test(s))&&(t[s]=e.headers[s]);return{sentryError:new Re(`${e.url.replace(/\?.*$/,"")} | ${e.code}`),sentryTags:{...t,status:e.status<0?"unknown":e.status,method:e.method,code:e.code,message:e.message},sentryExtra:{url:e.url,responseBody:e.body,responseHeaders:e.headers}}}function Ee(e,t,s,r){var g;const a=e.status,n=e.method,o=q(Object.entries(e.headers||{}).map(([m,f])=>[m.toLowerCase(),f])),{ok:c,code:i,data:h,message:u}=ue(a,e.statusText,e.body,s.get("responseRule"),r==null?void 0:r.responseRule);if(!T(a)){const m=je({url:t,method:n,status:a,code:i,message:u,body:e.body,headers:o});(s.get("errorHandler")||$e)({url:t,method:n,status:a,code:i,message:u,headers:o,rawError:e.rawError,responseBody:e.body,...m})}if(a<0)return P({ok:!1,status:a,code:e.statusText,headers:{},message:"",data:null},`${n} ${t} ${e.statusText}`,n,t,s,r);const l={ok:c,data:h,code:i,message:u,status:a,headers:o};(g=s.get("responseHandler"))==null||g({...l},n,t);const d=c?u:u||e.statusText;return P(l,d,n,t,s,r)}function P(e,t,s,r,a,n){const o=a.get("message"),c=o===!1||(n==null?void 0:n.message)===!1?!1:(n==null?void 0:n.message)||o;if(c!==!1){const i=typeof c=="function"?c(e,s,r,t):t;i instanceof Error?a.showMessage(!0,i.message,e.code,e.status):i&&typeof i=="object"&&"message"in i?a.showMessage(!1,i.message,e.code,e.status):a.showMessage(!e.ok,i,e.code,e.status)}return e}function $e(e){const t={};for(const s in e)s.startsWith("sentry")||(t[s]=e[s]);console.error("RequestError",t)}const Oe="2.0.1";exports.Ee=Y;exports.K=O;exports.NetRequestHandler=ie;exports.RequestGlobalConfig=x;exports.Support=w;exports.convertOptions=pe;exports.fromEntries=q;exports.getResponseRulesDescription=le;exports.handleResponse=Ee;exports.retryRequest=I;exports.version=Oe;exports.vt=ne;