@net-vert/core 0.5.1 → 1.2.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/dist/index.js CHANGED
@@ -1,338 +1,698 @@
1
- import E from "localforage";
2
- import { TaskQueue as j } from "id-queue";
3
- const k = {
4
- get: (t, e) => ({
5
- url: t,
6
- method: "get",
7
- ...e,
8
- params: e == null ? void 0 : e.params
9
- }),
10
- post: (t, e, r) => ({
11
- url: t,
12
- method: "post",
13
- data: e,
14
- headers: { "Content-Type": "application/json", ...r == null ? void 0 : r.headers },
15
- ...r
16
- }),
17
- delete: (t, e) => ({
18
- url: t,
19
- method: "delete",
20
- ...e
21
- }),
22
- put: (t, e, r) => ({
23
- url: t,
24
- method: "put",
25
- data: e,
26
- headers: { "Content-Type": "application/json", ...r == null ? void 0 : r.headers },
27
- ...r
28
- }),
29
- request: (t) => t
1
+ var D = Object.defineProperty;
2
+ var F = (r, e, t) => e in r ? D(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
3
+ var l = (r, e, t) => F(r, typeof e != "symbol" ? e + "" : e, t);
4
+ import { TaskQueue as $ } from "id-queue";
5
+ var w = /* @__PURE__ */ ((r) => (r.GET = "get", r.POST = "post", r.PUT = "put", r.DELETE = "delete", r))(w || {}), y = /* @__PURE__ */ ((r) => (r.CACHE = "cache", r.RETRY = "retry", r.IDEMPOTENT = "idempotent", r.CONCURRENT = "concurrent", r.SYNC = "sync", r))(y || {});
6
+ const v = "default", E = {
7
+ retries: 3,
8
+ delay: 0,
9
+ retryCondition: () => !0
10
+ }, T = (r) => {
11
+ const e = { ...E, ...r };
12
+ return Object.assign(async ({ config: n, next: s }) => {
13
+ let o = 0, i;
14
+ for (; o <= e.retries; )
15
+ try {
16
+ return await s();
17
+ } catch (a) {
18
+ if (i = a, o === e.retries)
19
+ throw a;
20
+ const c = {
21
+ config: n,
22
+ lastResponse: a,
23
+ attempt: o
24
+ };
25
+ if (!e.retryCondition(c))
26
+ throw a;
27
+ o++;
28
+ const u = typeof e.delay == "function" ? e.delay(c) : e.delay;
29
+ u > 0 && await new Promise((h) => setTimeout(h, u));
30
+ }
31
+ throw i;
32
+ }, { __middlewareType: y.RETRY });
33
+ }, q = () => {
34
+ const r = /* @__PURE__ */ new Map();
35
+ return { getPromise: (o) => r.get(o), setPromise: (o, i) => {
36
+ r.set(o, i), i.finally(() => r.delete(o));
37
+ }, delPromise: (o) => r.delete(o), clearCache: () => r.clear() };
38
+ }, R = (r) => {
39
+ const { config: e } = r, { method: t, url: n, data: s } = e;
40
+ return [t, n, JSON.stringify(s)].join("|");
41
+ }, B = {
42
+ key: R
43
+ }, _ = (r) => {
44
+ const e = { ...B, ...r }, t = q();
45
+ return Object.assign(({ config: s, next: o }) => {
46
+ const i = e.key({ config: s }), a = t.getPromise(i);
47
+ if (a)
48
+ return a;
49
+ const c = o();
50
+ return t.setPromise(i, c), c;
51
+ }, {
52
+ __middlewareType: y.IDEMPOTENT,
53
+ promiseCache: t
54
+ });
30
55
  };
31
- function T(t) {
32
- const e = {};
33
- return Object.keys(k).forEach(
34
- (r) => {
35
- e[r] = (...o) => {
36
- const n = k[r](...o);
37
- return t(n);
38
- };
56
+ class K {
57
+ constructor(e = 4) {
58
+ l(this, "parallelCount");
59
+ l(this, "tasks");
60
+ l(this, "runningCount");
61
+ this.parallelCount = e, this.tasks = new $(), this.runningCount = 0;
62
+ }
63
+ // 加入
64
+ add(e, t) {
65
+ return new Promise((n, s) => {
66
+ this.tasks.enqueue(e, {
67
+ task: t,
68
+ resolve: n,
69
+ reject: s
70
+ }), this._run();
71
+ });
72
+ }
73
+ // 删除
74
+ remove(e) {
75
+ this.tasks.remove(e);
76
+ }
77
+ execute(e) {
78
+ const { task: t, resolve: n, reject: s } = e;
79
+ return t().then(n).catch(s).finally(() => {
80
+ this.runningCount--, this._run();
81
+ });
82
+ }
83
+ _run() {
84
+ for (; this.runningCount < this.parallelCount && this.tasks.size > 0; ) {
85
+ const e = this.tasks.dequeue();
86
+ this.runningCount++, this.execute(e);
39
87
  }
40
- ), e;
88
+ }
41
89
  }
42
- const M = "default", z = () => `${Date.now()}_${Math.random().toString().slice(2, 8)}`, I = /* @__PURE__ */ new Map(), Z = (t, e = M) => {
43
- I.set(e, T(t));
44
- }, v = (t = M) => {
45
- const e = I.get(t);
46
- if (!e) throw new Error(`Requestor实例 ${t} 未注册`);
47
- return e;
90
+ let A = 0;
91
+ const J = {
92
+ parallelCount: 4,
93
+ createId: () => A++
94
+ }, z = (r) => {
95
+ const { parallelCount: e, createId: t } = { ...J, ...r }, n = new K(e);
96
+ return Object.assign(({ config: o, next: i }) => {
97
+ const a = t({ config: o });
98
+ return n.add(a, () => i());
99
+ }, { __middlewareType: y.CONCURRENT, pool: n });
100
+ }, b = /* @__PURE__ */ new Map(), g = (r, e) => {
101
+ b.set(e, r);
48
102
  };
49
- class O {
50
- has(e) {
51
- return !!this.get(e);
52
- }
53
- // 获取缓存
54
- get(e) {
55
- const r = localStorage.getItem(e);
56
- if (r)
103
+ function G(r) {
104
+ const e = b.get(r);
105
+ if (!e)
106
+ throw new Error(`Store实例 ${String(r)} 未注册`);
107
+ return e;
108
+ }
109
+ class U {
110
+ constructor() {
111
+ l(this, "store", /* @__PURE__ */ new Map());
112
+ }
113
+ getItem(e) {
114
+ return this.store.get(e);
115
+ }
116
+ setItem(e, t) {
117
+ return this.store.set(e, t), t;
118
+ }
119
+ removeItem(e) {
120
+ this.store.delete(e);
121
+ }
122
+ clear() {
123
+ this.store.clear();
124
+ }
125
+ length() {
126
+ return this.store.size;
127
+ }
128
+ key(e) {
129
+ return Array.from(this.store.keys())[e];
130
+ }
131
+ keys() {
132
+ return Array.from(this.store.keys());
133
+ }
134
+ iterate(e) {
135
+ let t = 0;
136
+ for (const [n, s] of this.store.entries())
137
+ e(s, n, t), t++;
138
+ }
139
+ }
140
+ const Y = (r) => !!r && (typeof r == "object" || typeof r == "function") && typeof r.then == "function", N = (r) => typeof window < "u" ? r() : {
141
+ getItem() {
142
+ return null;
143
+ },
144
+ setItem() {
145
+ },
146
+ removeItem() {
147
+ },
148
+ clear() {
149
+ },
150
+ key() {
151
+ return null;
152
+ },
153
+ get length() {
154
+ return 0;
155
+ }
156
+ }, d = N(() => window.localStorage);
157
+ class M {
158
+ constructor() {
159
+ }
160
+ getItem(e) {
161
+ const t = String(e), n = d.getItem(t);
162
+ if (n !== null)
57
163
  try {
58
- return JSON.parse(r);
59
- } catch (o) {
60
- console.error("Error parsing cached data", o);
164
+ return JSON.parse(n);
165
+ } catch (s) {
166
+ console.error(`Failed to parse value for key: ${t}`, s);
61
167
  return;
62
168
  }
63
169
  }
64
- // 设置缓存
65
- set(e, r) {
170
+ setItem(e, t) {
171
+ const n = String(e);
66
172
  try {
67
- const o = JSON.stringify(r);
68
- localStorage.setItem(e, o);
69
- } catch (o) {
70
- console.error("Error saving data to localStorage", o);
173
+ d.setItem(n, JSON.stringify(t));
174
+ } catch (s) {
175
+ throw console.error(`Failed to set value for key: ${n}`, s), s;
71
176
  }
72
- return r;
177
+ return t;
73
178
  }
74
- // 删除缓存
75
- remove(e) {
76
- localStorage.removeItem(e);
179
+ removeItem(e) {
180
+ const t = String(e);
181
+ d.removeItem(t);
77
182
  }
78
- // 清空所有缓存
79
183
  clear() {
80
- localStorage.clear();
184
+ d.clear();
81
185
  }
82
- }
83
- const H = new O(), U = ({ persist: t, name: e, sync: r }) => {
84
- if (t && r)
85
- return H;
86
- if (t) {
87
- const o = E.createInstance({
88
- name: e
89
- // driver: sync
90
- // ?undefined
91
- // :localforage.LOCALSTORAGE,
92
- });
93
- return {
94
- has: (n) => o.keys().then((s) => s.includes(n)),
95
- get: (n) => o.getItem(n),
96
- set: (n, s) => o.setItem(n, s),
97
- remove: (n) => o.removeItem(n),
98
- clear: () => o.clear()
99
- };
100
- } else {
101
- const o = /* @__PURE__ */ new Map();
102
- return {
103
- has: (n) => o.has(n),
104
- get: (n) => o.get(n),
105
- set: (n, s) => o.set(n, s),
106
- remove: (n) => o.delete(n),
107
- clear: () => o.clear()
108
- };
109
- }
110
- }, _ = () => {
111
- const t = /* @__PURE__ */ new Map();
112
- return {
113
- getPromise: (s) => t.get(s),
114
- setPromise: (s, u) => {
115
- t.set(s, u);
116
- },
117
- delPromise: (s) => {
118
- t.delete(s);
119
- },
120
- clearCache: () => {
121
- t.clear();
186
+ length() {
187
+ return d.length;
188
+ }
189
+ key(e) {
190
+ return d.key(e);
191
+ }
192
+ keys() {
193
+ const e = [];
194
+ for (let t = 0; t < d.length; t++) {
195
+ const n = d.key(t);
196
+ n && e.push(n);
122
197
  }
123
- };
124
- }, A = (t, e) => ({
125
- value: t,
126
- expiresAt: Date.now() + e
127
- }), x = (t) => t.expiresAt > Date.now(), J = {
128
- key: (t) => t.url,
129
- persist: !1,
130
- duration: 1 / 0,
131
- sync: !1
132
- }, S = (t) => {
133
- const e = { ...J, ...t }, { name: r, persist: o, sync: n } = e, s = U({ persist: o, name: r, sync: n }), { getPromise: u, setPromise: P, delPromise: g } = _();
134
- function l(a, h) {
135
- const { isValid: i } = e, f = s.get(a);
136
- let C = !1;
137
- if (f && x(f)) {
198
+ return e;
199
+ }
200
+ iterate(e) {
201
+ this.keys().forEach((t, n) => {
202
+ const s = this.getItem(t);
203
+ s !== void 0 && e(s, t, n);
204
+ });
205
+ }
206
+ }
207
+ const m = N(() => window.sessionStorage);
208
+ class X {
209
+ constructor() {
210
+ }
211
+ getItem(e) {
212
+ const t = String(e), n = m.getItem(t);
213
+ if (n !== null)
138
214
  try {
139
- C = (i == null ? void 0 : i({
140
- key: a,
141
- config: h,
142
- cachedData: f
143
- })) ?? !0;
144
- } catch (c) {
145
- console.error(`校验异常 ${a}`, c);
215
+ return JSON.parse(n);
216
+ } catch (s) {
217
+ console.error(`Failed to parse value for key: ${t}`, s);
218
+ return;
146
219
  }
147
- !C && s.remove(a);
220
+ }
221
+ setItem(e, t) {
222
+ const n = String(e);
223
+ try {
224
+ m.setItem(n, JSON.stringify(t));
225
+ } catch (s) {
226
+ throw console.error(`Failed to set value for key: ${n}`, s), s;
148
227
  }
149
- return { shouldUseCache: C, cachedData: f };
228
+ return t;
150
229
  }
151
- async function d(a, h) {
152
- const { isValid: i } = e, f = await s.get(a);
153
- let C = !1;
154
- if (f && x(f)) {
155
- try {
156
- C = await (i == null ? void 0 : i({
157
- key: a,
158
- config: h,
159
- cachedData: f
160
- })) ?? !0;
161
- } catch (c) {
162
- console.error(`校验异常 ${a}`, c);
163
- }
164
- !C && s.remove(a);
230
+ removeItem(e) {
231
+ const t = String(e);
232
+ m.removeItem(t);
233
+ }
234
+ clear() {
235
+ m.clear();
236
+ }
237
+ length() {
238
+ return m.length;
239
+ }
240
+ key(e) {
241
+ return m.key(e);
242
+ }
243
+ keys() {
244
+ const e = [];
245
+ for (let t = 0; t < m.length; t++) {
246
+ const n = m.key(t);
247
+ n && e.push(n);
165
248
  }
166
- return { shouldUseCache: C, cachedData: f };
167
- }
168
- const p = {
169
- get(a, h) {
170
- function i(c, y, ...m) {
171
- const q = Reflect.apply(a[h], a, m).then(async (w) => {
172
- const R = typeof e.duration == "number" ? e.duration : e.duration({
173
- key: c,
174
- config: y,
175
- response: w
176
- });
177
- return s.set(c, A(w, R)), w;
178
- }).finally(() => {
179
- g(c);
180
- });
181
- return P(c, q), q;
182
- }
183
- return n ? (...c) => {
184
- const y = k[h](...c), m = e.key(y), q = u(m);
185
- if (q)
186
- return q;
187
- const { shouldUseCache: w, cachedData: R } = l(m, y);
188
- return w ? R.value : i(m, y, ...c);
189
- } : (...c) => {
190
- const y = k[h](...c), m = e.key(y), q = u(m);
191
- if (q)
192
- return q;
193
- const w = (async () => {
194
- try {
195
- const { shouldUseCache: R, cachedData: D } = await d(m, y);
196
- return R ? D.value : await i(m, y, ...c);
197
- } finally {
198
- g(m);
199
- }
200
- })();
201
- return P(m, w), w;
202
- };
249
+ return e;
250
+ }
251
+ iterate(e) {
252
+ this.keys().forEach((t, n) => {
253
+ const s = this.getItem(t);
254
+ s !== void 0 && e(s, t, n);
255
+ });
256
+ }
257
+ }
258
+ class Z {
259
+ constructor(e, t) {
260
+ l(this, "dbName");
261
+ l(this, "storeName");
262
+ l(this, "dbPromise", null);
263
+ l(this, "DB_VERSION", 1);
264
+ this.dbName = e, this.storeName = t, this.initDB();
265
+ }
266
+ /**
267
+ * 初始化数据库连接
268
+ */
269
+ initDB() {
270
+ if (typeof window > "u" || !window.indexedDB) {
271
+ console.warn("IndexedDB is not available");
272
+ return;
203
273
  }
204
- };
205
- return {
206
- requestor: new Proxy(v(), p),
207
- store: s
208
- };
209
- }, N = (t) => {
210
- const { method: e, url: r, params: o, data: n } = t;
211
- return [e, r, JSON.stringify(o), JSON.stringify(n)].join("|");
212
- }, b = {
213
- key: N,
214
- duration: 1e3
215
- }, F = (t) => {
216
- const e = { ...b, ...t }, {
217
- requestor: r,
218
- store: o
219
- } = S({
220
- ...e,
221
- persist: !1
222
- });
223
- return {
224
- requestor: r,
225
- store: o
226
- };
227
- }, L = {
228
- retries: 3,
229
- delay: 0,
230
- retryCondition: () => !0
231
- }, $ = (t) => {
232
- const { retries: e, delay: r, retryCondition: o } = { ...L, ...t }, n = {
233
- get(s, u) {
234
- return (...g) => {
235
- let l = 0;
236
- const d = () => Reflect.apply(s[u], s, g).catch((p) => {
237
- if (l < e && o(p)) {
238
- l++;
239
- const a = typeof r == "function" ? r(l) : r;
240
- return new Promise((h) => {
241
- setTimeout(() => h(d()), a);
242
- });
243
- }
244
- return Promise.reject(p);
245
- });
246
- return d();
274
+ this.dbPromise = new Promise((e, t) => {
275
+ const n = indexedDB.open(this.dbName, this.DB_VERSION);
276
+ n.onerror = () => {
277
+ t(new Error(`Failed to open database: ${this.dbName}`));
278
+ }, n.onsuccess = () => {
279
+ e(n.result);
280
+ }, n.onupgradeneeded = (s) => {
281
+ const o = s.target.result;
282
+ o.objectStoreNames.contains(this.storeName) || o.createObjectStore(this.storeName);
283
+ };
284
+ });
285
+ }
286
+ /**
287
+ * 获取数据库实例
288
+ */
289
+ async getDB() {
290
+ if (!this.dbPromise)
291
+ throw new Error("IndexedDB is not initialized");
292
+ return this.dbPromise;
293
+ }
294
+ /**
295
+ * 执行事务
296
+ */
297
+ async withStore(e, t) {
298
+ const n = await this.getDB();
299
+ return new Promise((s, o) => {
300
+ const i = n.transaction([this.storeName], e).objectStore(this.storeName), a = t(i);
301
+ a.onsuccess = () => {
302
+ s(a.result);
303
+ }, a.onerror = () => {
304
+ o(a.error);
247
305
  };
306
+ });
307
+ }
308
+ async getItem(e) {
309
+ try {
310
+ const t = await this.withStore("readonly", (n) => n.get(String(e)));
311
+ return t === void 0 ? void 0 : t;
312
+ } catch (t) {
313
+ console.error(`Failed to get value for key: ${String(e)}`, t);
314
+ return;
248
315
  }
249
- };
316
+ }
317
+ async setItem(e, t) {
318
+ try {
319
+ return await this.withStore("readwrite", (n) => n.put(t, String(e))), t;
320
+ } catch (n) {
321
+ throw console.error(`Failed to set value for key: ${String(e)}`, n), n;
322
+ }
323
+ }
324
+ async removeItem(e) {
325
+ try {
326
+ await this.withStore("readwrite", (t) => t.delete(String(e)));
327
+ } catch (t) {
328
+ throw console.error(`Failed to remove value for key: ${String(e)}`, t), t;
329
+ }
330
+ }
331
+ async clear() {
332
+ try {
333
+ await this.withStore("readwrite", (e) => e.clear());
334
+ } catch (e) {
335
+ throw console.error("Failed to clear storage", e), e;
336
+ }
337
+ }
338
+ async length() {
339
+ try {
340
+ return await this.withStore("readonly", (e) => e.count());
341
+ } catch (e) {
342
+ return console.error("Failed to get storage length", e), 0;
343
+ }
344
+ }
345
+ async key(e) {
346
+ try {
347
+ return (await this.withStore("readonly", (t) => t.getAllKeys()))[e];
348
+ } catch (t) {
349
+ console.error("Failed to get key", t);
350
+ return;
351
+ }
352
+ }
353
+ async keys() {
354
+ try {
355
+ return await this.withStore("readonly", (e) => e.getAllKeys());
356
+ } catch (e) {
357
+ return console.error("Failed to get all keys", e), [];
358
+ }
359
+ }
360
+ async iterate(e) {
361
+ try {
362
+ const t = (await this.getDB()).transaction([this.storeName], "readonly").objectStore(this.storeName).openCursor();
363
+ return new Promise((n, s) => {
364
+ let o = 0;
365
+ t.onsuccess = (i) => {
366
+ const a = i.target.result;
367
+ if (a) {
368
+ const c = a.key, u = a.value;
369
+ e(u, c, o), o++, a.continue();
370
+ } else
371
+ n();
372
+ }, t.onerror = () => {
373
+ s(t.error);
374
+ };
375
+ });
376
+ } catch (t) {
377
+ console.error("Failed to iterate storage", t);
378
+ }
379
+ }
380
+ }
381
+ const f = {
382
+ memory: "memory",
383
+ local: "local",
384
+ session: "session",
385
+ indexeddb: "indexeddb"
386
+ };
387
+ function x(r, e) {
388
+ Object.assign(r, e);
389
+ }
390
+ function H(r) {
391
+ return x(r, {
392
+ async getItemOrDefault(e, t) {
393
+ const n = await this.getItem(e);
394
+ return n !== null ? n : t;
395
+ },
396
+ async hasItem(e) {
397
+ return await this.getItem(e) !== null;
398
+ },
399
+ async removeItems(e) {
400
+ await Promise.all(e.map((t) => this.removeItem(t)));
401
+ },
402
+ async getItems(e) {
403
+ return await Promise.all(e.map((t) => this.getItem(t)));
404
+ }
405
+ }), r;
406
+ }
407
+ function L(r) {
408
+ return x(r, {
409
+ getItemOrDefault(e, t) {
410
+ const n = this.getItem(e);
411
+ return n !== null ? n : t;
412
+ },
413
+ hasItem(e) {
414
+ return this.getItem(e) !== null;
415
+ },
416
+ removeItems(e) {
417
+ e.forEach((t) => this.removeItem(t));
418
+ },
419
+ getItems(e) {
420
+ return e.map((t) => this.getItem(t));
421
+ }
422
+ }), r;
423
+ }
424
+ function Q(r) {
425
+ const e = r.getItem("");
426
+ return Y(e) ? H(r) : L(r);
427
+ }
428
+ function p(r, ...e) {
429
+ const t = G(r);
430
+ let n;
431
+ try {
432
+ n = new t(...e);
433
+ } catch {
434
+ n = t(...e);
435
+ }
436
+ return Q(n);
437
+ }
438
+ g(U, f.memory);
439
+ g(M, f.local);
440
+ g(X, f.session);
441
+ g(Z, f.indexeddb);
442
+ function I(r, e) {
250
443
  return {
251
- requestor: new Proxy(v(), n)
444
+ value: r,
445
+ expireAt: Date.now() + e
252
446
  };
447
+ }
448
+ function k(r, e = Date.now()) {
449
+ return r.expireAt <= e;
450
+ }
451
+ function P(r, e = Date.now()) {
452
+ return k(r, e) ? void 0 : r.value;
453
+ }
454
+ const W = (r) => {
455
+ const { config: e } = r, { method: t, url: n, data: s } = e;
456
+ return [t, n, JSON.stringify(s)].join("|");
457
+ }, ee = () => !0, S = 24 * 60 * 60 * 1e3, te = {
458
+ key: W,
459
+ duration: S,
460
+ isValid: ee,
461
+ store: f.memory
462
+ // 默认不持久化,使用内存存储
253
463
  };
254
- class Q {
255
- constructor(e = 4) {
256
- this.parallelCount = e, this.tasks = new j(), this.runningCount = 0;
257
- }
258
- // 加入
259
- add(e, r) {
260
- return new Promise((o, n) => {
261
- this.tasks.enqueue(e, {
262
- task: r,
263
- resolve: o,
264
- reject: n
265
- }), this._run();
464
+ let re = class {
465
+ constructor(e) {
466
+ l(this, "store");
467
+ return typeof e == "string" ? this.store = p(e) : (g(e.factory, e.key), this.store = p(e.key)), new Proxy(this, {
468
+ get(t, n) {
469
+ if (n in t)
470
+ return t[n];
471
+ const s = t.store[n];
472
+ return typeof s == "function" ? s.bind(t.store) : s;
473
+ }
266
474
  });
267
475
  }
268
- // 删除
269
- remove(e) {
270
- this.tasks.remove(e);
476
+ /**
477
+ * 设置缓存(自动包装成 ExpirableValue)
478
+ * @param key 缓存 key
479
+ * @param value 要缓存的值
480
+ * @param duration 过期时长(毫秒),默认 24 小时
481
+ */
482
+ setCache(e, t, n = S) {
483
+ const s = I(t, n);
484
+ this.store.setItem(e, s);
271
485
  }
272
- execute(e) {
273
- const { task: r, resolve: o, reject: n } = e;
274
- return r().then(o).catch(n).finally(() => {
275
- this.runningCount--, this._run();
276
- });
486
+ /**
487
+ * 获取缓存值(检查过期,如果过期返回 undefined)
488
+ * @param key 缓存 key
489
+ * @returns 未过期返回值,已过期返回 undefined
490
+ */
491
+ async getCache(e) {
492
+ const t = await this.store.getItem(e);
493
+ if (t)
494
+ return P(t);
277
495
  }
278
- _run() {
279
- for (; this.runningCount < this.parallelCount && this.tasks.size > 0; ) {
280
- const e = this.tasks.dequeue();
281
- this.runningCount++, this.execute(e);
496
+ /**
497
+ * 检查是否有有效的缓存(未过期)
498
+ * @param key 缓存 key
499
+ * @returns true 表示有有效缓存,false 表示无缓存或已过期
500
+ */
501
+ async hasValidCache(e) {
502
+ const t = await this.store.getItem(e);
503
+ return t ? !k(t) : !1;
504
+ }
505
+ };
506
+ const ne = re, se = (r) => {
507
+ const e = { ...te, ...r }, t = new ne(e.store), n = (o) => typeof e.duration == "function" ? e.duration(o) : e.duration;
508
+ return Object.assign(async ({ config: o, next: i }) => {
509
+ const a = e.key({ config: o }), c = await t.getCache(a);
510
+ if (c) {
511
+ if (await e.isValid({
512
+ key: a,
513
+ config: o,
514
+ cachedData: c
515
+ })) return c;
516
+ t.removeItem(a);
282
517
  }
518
+ const u = await i(), h = n({ key: a, config: o, cachedData: c, response: u }), C = I(u, h);
519
+ return t.setItem(a, C), u;
520
+ }, {
521
+ __middlewareType: y.CACHE,
522
+ storage: t
523
+ });
524
+ };
525
+ class oe {
526
+ constructor(e) {
527
+ l(this, "store");
528
+ return typeof e == "string" ? this.store = p(e) : (g(e.factory, e.key), this.store = p(e.key)), new Proxy(this, {
529
+ get(t, n) {
530
+ if (n in t)
531
+ return t[n];
532
+ const s = t.store[n];
533
+ return typeof s == "function" ? s.bind(t.store) : s;
534
+ }
535
+ });
536
+ }
537
+ /**
538
+ * 设置缓存(自动包装成 ExpirableValue)
539
+ * @param key 缓存 key
540
+ * @param value 要缓存的值
541
+ * @param duration 过期时长(毫秒),默认 24 小时
542
+ */
543
+ setCache(e, t, n = S) {
544
+ const s = I(t, n);
545
+ this.store.setItem(e, s);
546
+ }
547
+ /**
548
+ * 获取缓存值(检查过期,如果过期返回 undefined)
549
+ * @param key 缓存 key
550
+ * @returns 未过期返回值,已过期返回 undefined
551
+ */
552
+ getCache(e) {
553
+ const t = this.store.getItem(e);
554
+ if (t)
555
+ return P(t);
556
+ }
557
+ /**
558
+ * 检查是否有有效的缓存(未过期)
559
+ * @param key 缓存 key
560
+ * @returns true 表示有有效缓存,false 表示无缓存或已过期
561
+ */
562
+ hasValidCache(e) {
563
+ const t = this.store.getItem(e);
564
+ return t ? !k(t) : !1;
283
565
  }
284
566
  }
285
- const W = {
286
- parallelCount: 4,
287
- retries: 0,
288
- createId: () => z()
289
- }, Y = (t) => {
290
- const e = { ...W, ...t }, { parallelCount: r, createId: o, ...n } = e, s = new Q(r), { requestor: u = null } = n.retries > 0 ? $(n) : {}, P = {
291
- get(g, l) {
292
- return (...p) => {
293
- const a = k[l](...p), h = o(a), i = () => u ? Reflect.apply(u[l], u, p) : Reflect.apply(g[l], g, p);
294
- return s.add(h, i);
295
- };
567
+ const ae = oe, ie = (r) => {
568
+ const { config: e } = r, { method: t, url: n } = e;
569
+ return [t, n].join("|");
570
+ }, ce = {
571
+ suspense: !0,
572
+ key: ie,
573
+ duration: 24 * 60 * 60 * 1e3,
574
+ isValid: () => !0,
575
+ store: f.memory
576
+ };
577
+ function we(r) {
578
+ const e = { ...ce, ...r }, t = new ae(e.store), n = (o) => typeof e.duration == "function" ? e.duration(o) : e.duration;
579
+ return Object.assign(({ config: o, next: i }) => {
580
+ const a = e.key({ config: o }), c = t.getCache(a);
581
+ if (c) {
582
+ if (e.isValid({
583
+ key: a,
584
+ config: o,
585
+ cachedData: c
586
+ })) return c;
587
+ t.removeItem(a);
296
588
  }
589
+ if (e.suspense)
590
+ throw (e.wrapSuspense ? e.wrapSuspense({ key: a, config: o, p: i() }) : i()).then((h) => {
591
+ const C = n({ key: a, config: o, cachedData: c, response: h });
592
+ return t.setCache(a, h, C), h;
593
+ });
594
+ return i().then((u) => {
595
+ const h = n({ key: a, config: o, cachedData: c, response: u });
596
+ return t.setCache(a, u, h), u;
597
+ });
598
+ }, { __middlewareType: y.SYNC });
599
+ }
600
+ const V = /* @__PURE__ */ new Map(), pe = (r, e = v) => {
601
+ V.set(e, r);
602
+ }, ue = (r = v) => {
603
+ const e = V.get(r);
604
+ if (!e) throw new Error(`Requestor实例 ${String(r)} 未注册`);
605
+ return e;
606
+ }, O = {
607
+ get: (r, e) => ({
608
+ url: r,
609
+ method: w.GET,
610
+ ...e,
611
+ params: e == null ? void 0 : e.params
612
+ }),
613
+ post: (r, e, t) => ({
614
+ url: r,
615
+ method: w.POST,
616
+ data: e,
617
+ ...t
618
+ }),
619
+ delete: (r, e) => ({
620
+ url: r,
621
+ method: w.DELETE,
622
+ ...e
623
+ }),
624
+ put: (r, e, t) => ({
625
+ url: r,
626
+ method: w.PUT,
627
+ data: e,
628
+ ...t
629
+ }),
630
+ request: (r) => r
631
+ }, le = Object.keys(O);
632
+ function he(r, e, t) {
633
+ const n = {}, s = (o) => {
634
+ if (o === e.length)
635
+ return t(r);
636
+ const i = e[o];
637
+ return i({
638
+ config: r,
639
+ ctx: n,
640
+ next: () => s(o + 1)
641
+ });
297
642
  };
298
- return {
299
- requestor: new Proxy(v(), P),
300
- concurrentPool: s
301
- };
302
- }, B = {
303
- persist: !1,
304
- sync: !0
305
- }, G = (t) => {
306
- const e = { ...B, ...t }, { ...r } = e, {
307
- requestor: o,
308
- store: n
309
- } = S(r), s = {
310
- get(u, P) {
311
- return (...l) => {
312
- try {
313
- const d = Reflect.apply(u[P], u, l);
314
- if (d instanceof Promise)
315
- throw d;
316
- return d;
317
- } catch (d) {
318
- throw d;
319
- }
643
+ return s(0);
644
+ }
645
+ function de(r, e) {
646
+ const t = {}, n = e ?? [];
647
+ return le.forEach(
648
+ (s) => {
649
+ t[s] = (...o) => {
650
+ const i = O[s](...o);
651
+ return he(
652
+ i,
653
+ n,
654
+ r
655
+ );
320
656
  };
321
657
  }
322
- };
323
- return {
324
- requestor: new Proxy(o, s),
325
- store: n
326
- };
327
- }, K = {
328
- cacheRequestor: S,
329
- idempotencyRequestor: F,
330
- retryRequestor: $,
331
- concurrentPoolRequestor: Y,
332
- syncRequestor: G
333
- };
658
+ ), t;
659
+ }
660
+ function j(r) {
661
+ const { extensions: e, instanceKey: t } = r ?? {}, n = ue(t);
662
+ return de(
663
+ n,
664
+ e
665
+ );
666
+ }
667
+ function Ce(r) {
668
+ const { instanceKey: e, key: t, duration: n, isValid: s, store: o, ...i } = r;
669
+ return j({
670
+ instanceKey: e,
671
+ extensions: [
672
+ _(i),
673
+ se({ key: t, duration: n, isValid: s, store: o })
674
+ ]
675
+ });
676
+ }
677
+ function Ie(r) {
678
+ const { instanceKey: e, parallelCount: t, createId: n, retries: s, delay: o, retryCondition: i } = r;
679
+ return j({
680
+ instanceKey: e,
681
+ extensions: [
682
+ z({ parallelCount: t, createId: n }),
683
+ T({ retries: s, delay: o, retryCondition: i })
684
+ ]
685
+ });
686
+ }
334
687
  export {
335
- Z as inject,
336
- K as requestExtender,
337
- v as useRequestor
688
+ se as cache,
689
+ z as concurrent,
690
+ Ce as createCachedIdempotentRequestor,
691
+ Ie as createConcurrentRetryRequestor,
692
+ j as createRequestor,
693
+ _ as idempotent,
694
+ pe as inject,
695
+ T as retry,
696
+ we as sync,
697
+ ue as useRequestor
338
698
  };