@seayoo-web/request 1.5.6 → 1.6.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.
@@ -0,0 +1,436 @@
1
+ var C = Object.defineProperty;
2
+ var A = (t, e, n) => e in t ? C(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n;
3
+ var f = (t, e, n) => (A(t, typeof e != "symbol" ? e + "" : e, n), n);
4
+ const m = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof window < "u" ? window : {}, w = {
5
+ fetch: "fetch" in m,
6
+ window: "window" in m,
7
+ FormData: "FormData" in m,
8
+ Blob: "Blob" in m,
9
+ wx: "wx" in m,
10
+ TextDecoder: "TextDecoder" in m
11
+ };
12
+ async function ne(t, e, n) {
13
+ var p;
14
+ const s = Object.assign({ method: "GET" }, n), r = w.FormData ? s.body instanceof FormData : !1, a = r && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method;
15
+ (a === "GET" || a === "HEAD" || a === "DELETE") && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
16
+ const o = Object.assign(
17
+ r ? {} : {
18
+ "Content-Type": w.Blob && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8"
19
+ },
20
+ s.headers
21
+ ), i = s.params || {}, c = {};
22
+ Object.keys(i).forEach((h) => {
23
+ i[h] !== void 0 && (c[h] = L(i[h]));
24
+ });
25
+ const d = e.getFullUrl(t), l = U(s.body), u = s.timeout || e.get("timeout"), g = await async function() {
26
+ var O;
27
+ const h = e.get("requestTransformer");
28
+ return h ? await h({ headers: o, params: c, method: a, url: d, body: l }) : await ((O = e.get("requestHandler")) == null ? void 0 : O(o, c, a, t));
29
+ }(), y = typeof g == "string" && g ? g : d;
30
+ return (p = e.get("logHandler")) == null || p({ type: "ready", url: y, method: a, headers: o, timeout: u, body: l }), {
31
+ url: y,
32
+ method: a,
33
+ body: l,
34
+ params: c,
35
+ headers: o,
36
+ timeout: u,
37
+ abort: s.abort,
38
+ credentials: s.credentials || e.get("credentials")
39
+ };
40
+ }
41
+ function L(t) {
42
+ return typeof t == "string" ? t : Array.isArray(t) ? t.join(",") : t + "";
43
+ }
44
+ function U(t) {
45
+ if (t)
46
+ return typeof t == "string" || t instanceof URLSearchParams || t instanceof ArrayBuffer || w.Blob && t instanceof Blob || w.FormData && t instanceof FormData ? t : JSON.stringify(t);
47
+ }
48
+ function B(t) {
49
+ return new Promise((e) => setTimeout(e, Math.max(0, t)));
50
+ }
51
+ function P() {
52
+ }
53
+ function R(t, e) {
54
+ try {
55
+ const n = JSON.parse(t);
56
+ return e ? e(n) ? n : null : n;
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+ "" + Math.random().toString(32).slice(2);
62
+ const H = /^(?:https?:)?\/\/.+$/i, S = /^https?:\/\/.+$/i, K = /^\{[\d\D]*\}$/, I = /^\[[\d\D]*\]$/;
63
+ function $(t, e = !1) {
64
+ return e ? H.test(t) : S.test(t);
65
+ }
66
+ function N(t) {
67
+ return t == null;
68
+ }
69
+ function M(t, ...e) {
70
+ if (!t || typeof t != "object")
71
+ return !1;
72
+ const n = Object.getPrototypeOf(t);
73
+ return n !== Object.prototype && n !== null ? !1 : e.every((s) => s in t);
74
+ }
75
+ function D(t) {
76
+ return K.test(t) || I.test(t);
77
+ }
78
+ async function ae(t) {
79
+ return await new Promise(function(e) {
80
+ const n = document.getElementsByTagName("head")[0], s = document.createElement("script");
81
+ s.setAttribute("type", "text/javascript"), s.setAttribute("charset", "utf-8"), s.onload = function() {
82
+ n.removeChild(s), e(!0);
83
+ }, s.onerror = function() {
84
+ n.removeChild(s), e(!1);
85
+ }, s.setAttribute("src", t), n.appendChild(s);
86
+ });
87
+ }
88
+ function q(t, e = "数据未能正确识别") {
89
+ return typeof t == "function" ? {
90
+ guard: t,
91
+ message: e
92
+ } : {
93
+ guard: t.guard,
94
+ message: t.message || e
95
+ };
96
+ }
97
+ function v(t, e = "") {
98
+ return !e || $(t, !0) ? T(t) : (T(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
99
+ }
100
+ function T(t) {
101
+ return $(t, !0) ? t.startsWith("http") ? t : ("location" in globalThis ? location.protocol : "https:") + t : ("location" in globalThis ? location.origin : "http://127.0.0.1") + "/" + t.replace(/^\/+/, "");
102
+ }
103
+ function V(t, e) {
104
+ if (e) {
105
+ if (e === !0)
106
+ return t.replace(/\?[^#]*/, "");
107
+ } else
108
+ return t;
109
+ const n = t.split("#"), s = n[0].split("?"), r = s[0], a = s.length > 1 ? s[1] : "", o = n.length > 1 ? "#" + n[1] : "", i = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
110
+ return !i.length || !a ? n[0] + o : (i.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + a.replace(new RegExp("(?:^|&)(?:" + i.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
111
+ }
112
+ function re(t, e, n = !1) {
113
+ const s = typeof e == "string" ? e : Object.keys(e).map((o) => `${o}=${encodeURIComponent(e[o])}`).join("&");
114
+ if (!s)
115
+ return t;
116
+ const r = t.split("#");
117
+ n && (r[0] = V(
118
+ r[0],
119
+ (s.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
120
+ ));
121
+ const a = r[0].indexOf("?") + 1 ? "&" : "?";
122
+ return (r[0] + a + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
123
+ }
124
+ const x = "data", b = "message";
125
+ function G(t, e, n, s, r) {
126
+ const a = r || s;
127
+ return F(t) ? X(a.ok || s.ok, t, e, n) : J(a.failed || s.failed, e, n);
128
+ }
129
+ const oe = function(t) {
130
+ const e = [], n = t.failed || { resolve: "json" };
131
+ switch (e.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
132
+ case "body":
133
+ e.push(" 将响应内容格式化为字符串并作为错误消息");
134
+ break;
135
+ case "json":
136
+ e.push(" 将响应解析为json,并读取 " + (n.messageField || b) + " 作为错误消息");
137
+ break;
138
+ }
139
+ const s = t.ok || { resolve: "body" };
140
+ switch (e.push("- 当http状态码 >=200 并且 <400 时"), s.resolve) {
141
+ case "body":
142
+ e.push(" 将响应尝试解析为 json,并作为数据内容返回");
143
+ break;
144
+ case "json":
145
+ e.push(
146
+ " 将响应解析为 json,读取 " + (s.dataField || x) + " 作为响应数据,读取 " + (s.messageField || b) + " 作为提示消息"
147
+ ), s.statusField && e.push(" 当 " + s.statusField + " 为 " + (s.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"), s.ignoreMessage && e.push(" 并忽略以下消息:" + s.ignoreMessage);
148
+ break;
149
+ }
150
+ return e.join(`
151
+ `);
152
+ };
153
+ function J(t, e, n) {
154
+ const s = t || { resolve: "json", messageField: b }, r = {
155
+ ok: !1,
156
+ code: e,
157
+ message: n,
158
+ data: null
159
+ };
160
+ switch (s.resolve) {
161
+ case "body":
162
+ r.message = k(n) || n;
163
+ break;
164
+ case "json":
165
+ const { code: a, message: o } = _(n, s.statusField, s.messageField);
166
+ r.code = a || e, r.message = k(n) || o;
167
+ break;
168
+ }
169
+ return r;
170
+ }
171
+ function _(t, e, n = b) {
172
+ if (!D(t))
173
+ return { message: "" };
174
+ const s = R(t);
175
+ return !s || !M(s) ? { message: t } : {
176
+ code: e ? j(s, e) : "",
177
+ message: j(s, n) || t
178
+ };
179
+ }
180
+ function j(t, e) {
181
+ const n = Array.isArray(e) ? e : [e];
182
+ for (const s of n)
183
+ if (s in t)
184
+ return W(t[s]);
185
+ return "";
186
+ }
187
+ function W(t) {
188
+ return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
189
+ }
190
+ const z = /<title>([^<]+)<\/title>/i, Q = /<message>([^<]+)<\/message>/i;
191
+ function k(t) {
192
+ const e = t.match(z);
193
+ if (e)
194
+ return e[1];
195
+ const n = t.match(Q);
196
+ return n ? n[1] : "";
197
+ }
198
+ function X(t, e, n, s) {
199
+ const r = t || { resolve: "body" }, a = {
200
+ ok: !0,
201
+ code: n,
202
+ message: "",
203
+ data: null
204
+ };
205
+ if (e === 202 || e === 204 || !s)
206
+ return a;
207
+ if (r.resolve === "body")
208
+ return a.data = D(s) ? R(s) : s, a;
209
+ const o = R(s);
210
+ if (!o || !M(o))
211
+ return a.ok = !1, a.code = "ResponseFormatError", a.message = "响应内容无法格式化为 Object", a;
212
+ const i = r.statusField, c = r.statusOKValue || "", d = r.dataField || x, l = r.messageField || b, u = r.ignoreMessage || "";
213
+ if (i && !(i in o))
214
+ return a.ok = !1, a.code = "ResponseFieldMissing", a.message = "响应内容找不到状态字段 " + i, a;
215
+ const g = i ? o[i] + "" : "";
216
+ return a.ok = i ? g === c : !0, a.code = g || n, a.data = d === !0 ? o : d in o ? o[d] : null, a.message = j(o, l), u && a.message && (Array.isArray(u) && u.includes(a.message) || typeof u == "string" && a.message === u) && (a.message = ""), a;
217
+ }
218
+ function F(t) {
219
+ return t >= 200 && t < 400;
220
+ }
221
+ async function Y(t, e, n, s, r) {
222
+ const a = r || 0, o = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? n.get("maxRetry") ?? 0)), i = (s == null ? void 0 : s.retryResolve) ?? n.get("retryResolve"), c = n.get("logHandler") || P;
223
+ c({
224
+ type: "prepear",
225
+ url: e,
226
+ method: (s == null ? void 0 : s.method) || "GET",
227
+ retry: a,
228
+ maxRetry: o,
229
+ message: a === 0 ? "start" : `retry ${a}/${o} start`,
230
+ headers: s == null ? void 0 : s.headers,
231
+ options: s
232
+ });
233
+ const d = Date.now(), l = await t(e, n, s), u = l.status, g = Date.now() - d, y = `[cost ${g}][${u}] ${u < 0 ? l.body : ""}`;
234
+ c({
235
+ type: "finished",
236
+ url: e,
237
+ method: l.method,
238
+ retry: a,
239
+ maxRetry: o,
240
+ message: a === 0 ? `finish ${y}` : `retry ${a}/${o} finish ${y}`,
241
+ response: l,
242
+ headers: l.headers,
243
+ cost: g
244
+ });
245
+ const p = F(u);
246
+ if (!o || i === "network" && u > 0 || i === "status" && p || Array.isArray(i) && !i.includes(u) || typeof i == "function" && i(l, a) !== !0 || a >= o)
247
+ return l;
248
+ const h = (s == null ? void 0 : s.retryInterval) ?? n.get("retryInterval") ?? 1e3;
249
+ return await B(
250
+ Math.max(
251
+ 100,
252
+ h === "2EB" ? Math.pow(2, a) * 1e3 : typeof h == "function" ? h(a + 1) || 0 : h
253
+ )
254
+ ), await Y(t, e, n, s, a + 1);
255
+ }
256
+ function ie(t, e, n, s) {
257
+ var o, i;
258
+ if (t.status < 0)
259
+ return E(
260
+ { ok: !1, status: t.status, code: t.statusText, headers: {}, message: "", data: null },
261
+ `${t.method} ${e} ${t.statusText}`,
262
+ t.method,
263
+ e,
264
+ n,
265
+ s
266
+ );
267
+ F(t.status) || (o = n.get("errorHandler")) == null || o(t.status, t.method, e);
268
+ const r = {
269
+ ...G(t.status, t.statusText, t.body, n.get("responseRule"), s == null ? void 0 : s.responseRule),
270
+ status: t.status,
271
+ headers: Object.fromEntries(Object.entries(t.headers || {}).map(([c, d]) => [c.toLowerCase(), d]))
272
+ };
273
+ (i = n.get("responseHandler")) == null || i({ ...r }, t.method, e);
274
+ const a = r.ok ? r.message : `${t.method} ${e} [${r.code || t.statusText}] ${r.message || t.statusText}`;
275
+ return E(r, a, t.method, e, n, s);
276
+ }
277
+ function E(t, e, n, s, r, a) {
278
+ const o = r.get("message"), i = o === !1 || (a == null ? void 0 : a.message) === !1 ? !1 : (a == null ? void 0 : a.message) || o;
279
+ if (i !== !1) {
280
+ const c = typeof i == "function" ? i(t, n, s, e) : e;
281
+ c instanceof Error ? r.showMessage(!0, c.message) : c && typeof c == "object" && "message" in c ? r.showMessage(!1, c.message) : r.showMessage(!t.ok, c);
282
+ }
283
+ return t;
284
+ }
285
+ class Z {
286
+ constructor(e) {
287
+ // 保存的配置需要部分字段强制设置默认值
288
+ f(this, "config", {
289
+ baseURL: "",
290
+ maxRetry: 0,
291
+ retryInterval: 1e3,
292
+ retryResolve: "network",
293
+ timeout: 5e3,
294
+ cacheTTL: 500,
295
+ credentials: "same-origin",
296
+ responseRule: {
297
+ ok: {
298
+ resolve: "body"
299
+ },
300
+ failed: {
301
+ resolve: "json",
302
+ messageField: "message"
303
+ }
304
+ }
305
+ });
306
+ e && this.set(e);
307
+ }
308
+ set(e) {
309
+ if (e.baseURL && !/^\/.+/.test(e.baseURL) && !$(e.baseURL))
310
+ throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
311
+ Object.assign(this.config, e);
312
+ }
313
+ get(e) {
314
+ return this.config[e];
315
+ }
316
+ /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
317
+ getFullUrl(e) {
318
+ return e.startsWith("/") ? v(e) : v(e, this.config.baseURL);
319
+ }
320
+ /** 提示消息 */
321
+ showMessage(e, n) {
322
+ this.config.messageHandler && n && this.config.messageHandler(e, n);
323
+ }
324
+ }
325
+ class ee {
326
+ constructor(e = 500) {
327
+ f(this, "ttl");
328
+ f(this, "cache");
329
+ this.cache = {}, this.ttl = Math.max(e, 0);
330
+ }
331
+ getKey(e, n) {
332
+ const s = Object.keys(n || {}).sort().map((r) => `${r}#${n == null ? void 0 : n[r]}`);
333
+ return e + s.join(",");
334
+ }
335
+ updateTTL(e) {
336
+ this.ttl = Math.max(e, 0);
337
+ }
338
+ get(e) {
339
+ if (this.ttl === 0)
340
+ return null;
341
+ const n = this.cache[e];
342
+ return n ? n.ttl < Date.now() ? (delete this.cache[e], null) : n.res : null;
343
+ }
344
+ set(e, n) {
345
+ this.ttl !== 0 && (this.cache[e] = {
346
+ ttl: Date.now() + this.ttl,
347
+ res: n
348
+ });
349
+ }
350
+ }
351
+ function te(t, e, n, s) {
352
+ if (e.ok && !N(e.data) && s) {
353
+ const r = q(s, "响应数据未能正确识别");
354
+ return r.guard(e.data) || (console.error("ResponseCheckFaild", t, e.data), n.showMessage(!0, `${t} ${r.message}`), e.data = null), e;
355
+ }
356
+ return e;
357
+ }
358
+ class ce {
359
+ constructor(e, n) {
360
+ f(this, "agent");
361
+ f(this, "config");
362
+ f(this, "cache");
363
+ this.config = new Z(n), this.agent = e, this.cache = new ee(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.bind(this), this.get = this.get.bind(this), this.post = this.post.bind(this), this.del = this.del.bind(this), this.patch = this.patch.bind(this), this.put = this.put.bind(this), this.head = this.head.bind(this);
364
+ }
365
+ /**
366
+ * 执行网络请求
367
+ */
368
+ async exec(e, n) {
369
+ return await this.agent(e, this.config, n);
370
+ }
371
+ /**
372
+ * 检查响应的数据类型
373
+ */
374
+ async guard(e, n, s) {
375
+ return te(e, n, this.config, s);
376
+ }
377
+ /**
378
+ * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
379
+ */
380
+ setConfig(e) {
381
+ this.config.set(e), this.cache.updateTTL(this.config.get("cacheTTL"));
382
+ }
383
+ /**
384
+ * 读取默认的请求配置
385
+ */
386
+ getConfig(e) {
387
+ return this.config.get(e);
388
+ }
389
+ /**
390
+ * 发送一个 HEAD 请求,并且不处理响应 body
391
+ */
392
+ async head(e, n) {
393
+ const s = Object.assign({}, n || null);
394
+ return s.method = "HEAD", this.guard(e, await this.exec(e, s), null);
395
+ }
396
+ async get(e, n, s) {
397
+ const r = Object.assign({}, s || null);
398
+ r.method = "GET";
399
+ const a = this.cache.getKey(e, r.params), o = this.cache.get(a);
400
+ if (o)
401
+ return this.guard(e, await o, n || null);
402
+ const i = this.exec(e, r);
403
+ return this.cache.set(a, i), this.guard(e, await i, n || null);
404
+ }
405
+ async post(e, n, s, r) {
406
+ const a = Object.assign({}, r || null);
407
+ return a.method = "POST", a.body = n, this.guard(e, await this.exec(e, a), s || null);
408
+ }
409
+ async del(e, n, s) {
410
+ const r = Object.assign({}, s || null);
411
+ return r.method = "DELETE", this.guard(e, await this.exec(e, r), n || null);
412
+ }
413
+ async put(e, n, s, r) {
414
+ const a = Object.assign({}, r || null);
415
+ return a.method = "PUT", a.body = n, this.guard(e, await this.exec(e, a), s || null);
416
+ }
417
+ async patch(e, n, s, r) {
418
+ const a = Object.assign({}, r || null);
419
+ return a.method = "PATCH", a.body = n, this.guard(e, await this.exec(e, a), s || null);
420
+ }
421
+ }
422
+ const ue = "1.6.1";
423
+ export {
424
+ re as E,
425
+ ce as N,
426
+ Z as R,
427
+ w as S,
428
+ $ as U,
429
+ P as V,
430
+ ae as a,
431
+ ne as c,
432
+ oe as g,
433
+ ie as h,
434
+ Y as r,
435
+ ue as v
436
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";var L=Object.defineProperty;var B=(t,e,n)=>e in t?L(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var f=(t,e,n)=>(B(t,typeof e!="symbol"?e+"":e,n),n);const m=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},b={fetch:"fetch"in m,window:"window"in m,FormData:"FormData"in m,Blob:"Blob"in m,wx:"wx"in m,TextDecoder:"TextDecoder"in m};async function H(t,e,n){var w;const s=Object.assign({method:"GET"},n),r=b.FormData?s.body instanceof FormData:!1,a=r&&s.method!=="POST"&&s.method!=="PUT"?"POST":s.method;(a==="GET"||a==="HEAD"||a==="DELETE")&&s.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);const o=Object.assign(r?{}:{"Content-Type":b.Blob&&s.body instanceof Blob?s.body.type||"application/octet-stream":"application/json;charset=utf-8"},s.headers),i=s.params||{},c={};Object.keys(i).forEach(h=>{i[h]!==void 0&&(c[h]=P(i[h]))});const d=e.getFullUrl(t),l=S(s.body),u=s.timeout||e.get("timeout"),g=await async function(){var v;const h=e.get("requestTransformer");return h?await h({headers:o,params:c,method:a,url:d,body:l}):await((v=e.get("requestHandler"))==null?void 0:v(o,c,a,t))}(),y=typeof g=="string"&&g?g:d;return(w=e.get("logHandler"))==null||w({type:"ready",url:y,method:a,headers:o,timeout:u,body:l}),{url:y,method:a,body:l,params:c,headers:o,timeout:u,abort:s.abort,credentials:s.credentials||e.get("credentials")}}function P(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function S(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||b.Blob&&t instanceof Blob||b.FormData&&t instanceof FormData?t:JSON.stringify(t)}function q(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function M(){}function j(t,e){try{const n=JSON.parse(t);return e?e(n)?n:null:n}catch{return null}}""+Math.random().toString(32).slice(2);const K=/^(?:https?:)?\/\/.+$/i,I=/^https?:\/\/.+$/i,N=/^\{[\d\D]*\}$/,V=/^\[[\d\D]*\]$/;function R(t,e=!1){return e?K.test(t):I.test(t)}function G(t){return t==null}function D(t,...e){if(!t||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n!==Object.prototype&&n!==null?!1:e.every(s=>s in t)}function C(t){return N.test(t)||V.test(t)}async function J(t){return await new Promise(function(e){const n=document.getElementsByTagName("head")[0],s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("charset","utf-8"),s.onload=function(){n.removeChild(s),e(!0)},s.onerror=function(){n.removeChild(s),e(!1)},s.setAttribute("src",t),n.appendChild(s)})}function _(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function F(t,e=""){return!e||R(t,!0)?T(t):(T(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function T(t){return R(t,!0)?t.startsWith("http")?t:("location"in globalThis?location.protocol:"https:")+t:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+t.replace(/^\/+/,"")}function W(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const n=t.split("#"),s=n[0].split("?"),r=s[0],a=s.length>1?s[1]:"",o=n.length>1?"#"+n[1]:"",i=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!i.length||!a?n[0]+o:(i.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+a.replace(new RegExp("(?:^|&)(?:"+i.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function z(t,e,n=!1){const s=typeof e=="string"?e:Object.keys(e).map(o=>`${o}=${encodeURIComponent(e[o])}`).join("&");if(!s)return t;const r=t.split("#");n&&(r[0]=W(r[0],(s.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const a=r[0].indexOf("?")+1?"&":"?";return(r[0]+a+s+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}const x="data",p="message";function Q(t,e,n,s,r){const a=r||s;return $(t)?ne(a.ok||s.ok,t,e,n):Y(a.failed||s.failed,e,n)}const X=function(t){const e=[],n=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),n.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(n.messageField||p)+" 作为错误消息");break}const s=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),s.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(s.dataField||x)+" 作为响应数据,读取 "+(s.messageField||p)+" 作为提示消息"),s.statusField&&e.push(" 当 "+s.statusField+" 为 "+(s.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),s.ignoreMessage&&e.push(" 并忽略以下消息:"+s.ignoreMessage);break}return e.join(`
2
+ `)};function Y(t,e,n){const s=t||{resolve:"json",messageField:p},r={ok:!1,code:e,message:n,data:null};switch(s.resolve){case"body":r.message=k(n)||n;break;case"json":const{code:a,message:o}=Z(n,s.statusField,s.messageField);r.code=a||e,r.message=k(n)||o;break}return r}function Z(t,e,n=p){if(!C(t))return{message:""};const s=j(t);return!s||!D(s)?{message:t}:{code:e?O(s,e):"",message:O(s,n)||t}}function O(t,e){const n=Array.isArray(e)?e:[e];for(const s of n)if(s in t)return ee(t[s]);return""}function ee(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const te=/<title>([^<]+)<\/title>/i,se=/<message>([^<]+)<\/message>/i;function k(t){const e=t.match(te);if(e)return e[1];const n=t.match(se);return n?n[1]:""}function ne(t,e,n,s){const r=t||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(e===202||e===204||!s)return a;if(r.resolve==="body")return a.data=C(s)?j(s):s,a;const o=j(s);if(!o||!D(o))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;const i=r.statusField,c=r.statusOKValue||"",d=r.dataField||x,l=r.messageField||p,u=r.ignoreMessage||"";if(i&&!(i in o))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+i,a;const g=i?o[i]+"":"";return a.ok=i?g===c:!0,a.code=g||n,a.data=d===!0?o:d in o?o[d]:null,a.message=O(o,l),u&&a.message&&(Array.isArray(u)&&u.includes(a.message)||typeof u=="string"&&a.message===u)&&(a.message=""),a}function $(t){return t>=200&&t<400}async function A(t,e,n,s,r){const a=r||0,o=Math.max(0,Math.min(10,(s==null?void 0:s.maxRetry)??n.get("maxRetry")??0)),i=(s==null?void 0:s.retryResolve)??n.get("retryResolve"),c=n.get("logHandler")||M;c({type:"prepear",url:e,method:(s==null?void 0:s.method)||"GET",retry:a,maxRetry:o,message:a===0?"start":`retry ${a}/${o} start`,headers:s==null?void 0:s.headers,options:s});const d=Date.now(),l=await t(e,n,s),u=l.status,g=Date.now()-d,y=`[cost ${g}][${u}] ${u<0?l.body:""}`;c({type:"finished",url:e,method:l.method,retry:a,maxRetry:o,message:a===0?`finish ${y}`:`retry ${a}/${o} finish ${y}`,response:l,headers:l.headers,cost:g});const w=$(u);if(!o||i==="network"&&u>0||i==="status"&&w||Array.isArray(i)&&!i.includes(u)||typeof i=="function"&&i(l,a)!==!0||a>=o)return l;const h=(s==null?void 0:s.retryInterval)??n.get("retryInterval")??1e3;return await q(Math.max(100,h==="2EB"?Math.pow(2,a)*1e3:typeof h=="function"?h(a+1)||0:h)),await A(t,e,n,s,a+1)}function ae(t,e,n,s){var o,i;if(t.status<0)return E({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,n,s);$(t.status)||(o=n.get("errorHandler"))==null||o(t.status,t.method,e);const r={...Q(t.status,t.statusText,t.body,n.get("responseRule"),s==null?void 0:s.responseRule),status:t.status,headers:Object.fromEntries(Object.entries(t.headers||{}).map(([c,d])=>[c.toLowerCase(),d]))};(i=n.get("responseHandler"))==null||i({...r},t.method,e);const a=r.ok?r.message:`${t.method} ${e} [${r.code||t.statusText}] ${r.message||t.statusText}`;return E(r,a,t.method,e,n,s)}function E(t,e,n,s,r,a){const o=r.get("message"),i=o===!1||(a==null?void 0:a.message)===!1?!1:(a==null?void 0:a.message)||o;if(i!==!1){const c=typeof i=="function"?i(t,n,s,e):e;c instanceof Error?r.showMessage(!0,c.message):c&&typeof c=="object"&&"message"in c?r.showMessage(!1,c.message):r.showMessage(!t.ok,c)}return t}class U{constructor(e){f(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!R(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return e.startsWith("/")?F(e):F(e,this.config.baseURL)}showMessage(e,n){this.config.messageHandler&&n&&this.config.messageHandler(e,n)}}class re{constructor(e=500){f(this,"ttl");f(this,"cache");this.cache={},this.ttl=Math.max(e,0)}getKey(e,n){const s=Object.keys(n||{}).sort().map(r=>`${r}#${n==null?void 0:n[r]}`);return e+s.join(",")}updateTTL(e){this.ttl=Math.max(e,0)}get(e){if(this.ttl===0)return null;const n=this.cache[e];return n?n.ttl<Date.now()?(delete this.cache[e],null):n.res:null}set(e,n){this.ttl!==0&&(this.cache[e]={ttl:Date.now()+this.ttl,res:n})}}function oe(t,e,n,s){if(e.ok&&!G(e.data)&&s){const r=_(s,"响应数据未能正确识别");return r.guard(e.data)||(console.error("ResponseCheckFaild",t,e.data),n.showMessage(!0,`${t} ${r.message}`),e.data=null),e}return e}class ie{constructor(e,n){f(this,"agent");f(this,"config");f(this,"cache");this.config=new U(n),this.agent=e,this.cache=new re(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async exec(e,n){return await this.agent(e,this.config,n)}async guard(e,n,s){return oe(e,n,this.config,s)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,n){const s=Object.assign({},n||null);return s.method="HEAD",this.guard(e,await this.exec(e,s),null)}async get(e,n,s){const r=Object.assign({},s||null);r.method="GET";const a=this.cache.getKey(e,r.params),o=this.cache.get(a);if(o)return this.guard(e,await o,n||null);const i=this.exec(e,r);return this.cache.set(a,i),this.guard(e,await i,n||null)}async post(e,n,s,r){const a=Object.assign({},r||null);return a.method="POST",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async del(e,n,s){const r=Object.assign({},s||null);return r.method="DELETE",this.guard(e,await this.exec(e,r),n||null)}async put(e,n,s,r){const a=Object.assign({},r||null);return a.method="PUT",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async patch(e,n,s,r){const a=Object.assign({},r||null);return a.method="PATCH",a.body=n,this.guard(e,await this.exec(e,a),s||null)}}const ce="1.6.1";exports.Et=z;exports.NetRequestHandler=ie;exports.RequestGlobalConfig=U;exports.Support=b;exports.U=R;exports.Vt=M;exports.convertOptions=H;exports.getResponseRulesDescription=X;exports.handleResponse=ae;exports.he=J;exports.retryRequest=A;exports.version=ce;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "1.5.6";
1
+ export declare const version = "1.6.1";
package/dist/wx.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./version-nbk4F2gf.cjs"),l=async function(t,n,r){return s.handleResponse(await s.retryRequest(f,t,n,r),t,n,r)},f=async function(t,n,r){const e=await s.convertOptions(t,n,r),u=e.method==="PATCH"?"POST":e.method,a=s.Ct(e.url,e.params);return globalThis.wx?new Promise(i=>{wx.request({url:a,data:e.body,header:e.headers,method:u,dataType:"string",responseType:"text",fail(){i({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){i({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:e.method==="HEAD"?"":p(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};function p(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&"TextDecoder"in globalThis?new TextDecoder().decode(t):JSON.stringify(t)}function d(t){return new s.NetRequestHandler(l,t)}const o=d(),g=o.setConfig,h=o.head,y=o.get,T=o.post,b=o.del,x=o.put;exports.version=s.version;exports.NetRequest=d;exports.del=b;exports.get=y;exports.head=h;exports.post=T;exports.put=x;exports.setGlobalConfig=g;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./version-yl6932gU.cjs"),p=async function(t,r,n){return e.handleResponse(await e.retryRequest(l,t,r,n),t,r,n)},l=async function(t,r,n){const o=await e.convertOptions(t,r,n),u=o.method==="PATCH"?"POST":o.method,a=e.Et(o.url,o.params);return e.Support.wx?new Promise(d=>{wx.request({url:a,data:o.body,header:o.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:o.method==="HEAD"?"":f(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};function f(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.Support.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(p,t)}const s=i(),y=s.setConfig,g=s.head,h=s.get,x=s.post,w=s.del,T=s.put;exports.version=e.version;exports.NetRequest=i;exports.del=w;exports.get=h;exports.head=g;exports.post=x;exports.put=T;exports.setGlobalConfig=y;
package/dist/wx.js CHANGED
@@ -1,10 +1,10 @@
1
- import { h as d, r as i, c as f, C as l, N as p } from "./version-DCu7OI8o.js";
2
- import { v as A } from "./version-DCu7OI8o.js";
1
+ import { h as i, r as p, c as f, E as l, S as d, N as x } from "./version-D5ZPd9sj.js";
2
+ import { v as A } from "./version-D5ZPd9sj.js";
3
3
  const h = async function(t, o, r) {
4
- return d(await i(x, t, o, r), t, o, r);
5
- }, x = async function(t, o, r) {
4
+ return i(await p(y, t, o, r), t, o, r);
5
+ }, y = async function(t, o, r) {
6
6
  const e = await f(t, o, r), n = e.method === "PATCH" ? "POST" : e.method, a = l(e.url, e.params);
7
- return globalThis.wx ? new Promise((c) => {
7
+ return d.wx ? new Promise((c) => {
8
8
  wx.request({
9
9
  url: a,
10
10
  data: e.body,
@@ -28,7 +28,7 @@ const h = async function(t, o, r) {
28
28
  status: u.statusCode,
29
29
  statusText: u.statusCode + "",
30
30
  headers: { ...u.header },
31
- body: e.method === "HEAD" ? "" : y(u.data)
31
+ body: e.method === "HEAD" ? "" : m(u.data)
32
32
  });
33
33
  }
34
34
  });
@@ -40,20 +40,20 @@ const h = async function(t, o, r) {
40
40
  body: "NotFound namespace of wx"
41
41
  };
42
42
  };
43
- function y(t) {
44
- return typeof t == "string" ? t : t instanceof ArrayBuffer && "TextDecoder" in globalThis ? new TextDecoder().decode(t) : JSON.stringify(t);
45
- }
46
43
  function m(t) {
47
- return new p(h, t);
44
+ return typeof t == "string" ? t : t instanceof ArrayBuffer && d.TextDecoder ? new TextDecoder().decode(t) : JSON.stringify(t);
45
+ }
46
+ function w(t) {
47
+ return new x(h, t);
48
48
  }
49
- const s = m(), g = s.setConfig, w = s.head, b = s.get, q = s.post, C = s.del, N = s.put;
49
+ const s = w(), g = s.setConfig, q = s.head, N = s.get, R = s.post, b = s.del, S = s.put;
50
50
  export {
51
- m as NetRequest,
52
- C as del,
53
- b as get,
54
- w as head,
55
- q as post,
56
- N as put,
51
+ w as NetRequest,
52
+ b as del,
53
+ N as get,
54
+ q as head,
55
+ R as post,
56
+ S as put,
57
57
  g as setGlobalConfig,
58
58
  A as version
59
59
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "1.5.6",
3
+ "version": "1.6.1",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -67,21 +67,21 @@
67
67
  "@types/node": "18.19.5",
68
68
  "@typescript-eslint/eslint-plugin": "^6.21.0",
69
69
  "@typescript-eslint/parser": "^6.21.0",
70
- "@vitest/browser": "^1.3.1",
71
- "@vitest/coverage-istanbul": "^1.3.1",
70
+ "@vitest/browser": "^1.4.0",
71
+ "@vitest/coverage-istanbul": "^1.4.0",
72
72
  "eslint": "^8.57.0",
73
73
  "eslint-config-prettier": "^9.1.0",
74
74
  "eslint-plugin-prettier": "^5.1.3",
75
75
  "happy-dom": "^12.10.3",
76
76
  "lint-staged": "^14.0.1",
77
- "msw": "^2.2.3",
77
+ "msw": "^2.2.13",
78
78
  "rimraf": "^5.0.5",
79
- "simple-git-hooks": "^2.10.0",
79
+ "simple-git-hooks": "^2.11.1",
80
80
  "typescript": "~5.2.2",
81
- "vite": "^5.1.6",
82
- "vitest": "^1.3.1"
81
+ "vite": "^5.2.8",
82
+ "vitest": "^1.4.0"
83
83
  },
84
84
  "dependencies": {
85
- "@seayoo-web/utils": "^1.16.1"
85
+ "@seayoo-web/utils": "^1.16.3"
86
86
  }
87
87
  }