@citruslime/vue-utils 2.0.4-beta.1 → 2.0.4-beta.3

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.
@@ -1,313 +1,315 @@
1
- import { replacePlaceholders as X } from "@citruslime/utils";
2
- import { shallowRef as E, readonly as W, toRef as ae, ref as ie, customRef as le, toValue as P, getCurrentScope as se, onScopeDispose as ue, watch as M, nextTick as Y, isRef as te, computed as ce } from "vue";
3
- const Oe = [
1
+ import { replacePlaceholders as Y } from "@citruslime/utils";
2
+ import { shallowRef as O, shallowReadonly as ae, toRef as le, readonly as z, ref as se, customRef as ue, toValue as E, getCurrentScope as ce, onScopeDispose as fe, watch as _, nextTick as Z, isRef as ne, computed as de } from "vue";
3
+ const Pe = [
4
4
  "GET",
5
5
  "POST",
6
6
  "PUT",
7
7
  "DELETE"
8
8
  ];
9
- function Ee(e, t, i = null, s = null) {
9
+ function De(e, t, a = null, c = null, h = null) {
10
10
  return {
11
11
  url: e,
12
12
  type: t,
13
- headers: i ?? ne,
14
- hasBody: fe(t, s)
13
+ headers: a ?? oe,
14
+ hasBody: pe(t, c),
15
+ options: h ?? {}
15
16
  };
16
17
  }
17
- function ne() {
18
+ function oe() {
18
19
  return {
19
20
  accept: "application/json",
20
21
  "content-type": "application/json"
21
22
  };
22
23
  }
23
- function fe(e, t) {
24
+ function pe(e, t) {
24
25
  return !!(t === null && (e === "PUT" || e === "POST") || t);
25
26
  }
26
- function oe(e) {
27
- return se() ? (ue(e), !0) : !1;
27
+ function re(e) {
28
+ return ce() ? (fe(e), !0) : !1;
28
29
  }
30
+ // @__NO_SIDE_EFFECTS__
29
31
  function I() {
30
- const e = /* @__PURE__ */ new Set(), t = (o) => {
31
- e.delete(o);
32
+ const e = /* @__PURE__ */ new Set(), t = (l) => {
33
+ e.delete(l);
32
34
  };
33
35
  return {
34
- on: (o) => {
35
- e.add(o);
36
- const n = () => t(o);
37
- return oe(n), {
36
+ on: (l) => {
37
+ e.add(l);
38
+ const n = () => t(l);
39
+ return re(n), {
38
40
  off: n
39
41
  };
40
42
  },
41
43
  off: t,
42
- trigger: (...o) => Promise.all(Array.from(e).map((n) => n(...o))),
44
+ trigger: (...l) => Promise.all(Array.from(e).map((n) => n(...l))),
43
45
  clear: () => {
44
46
  e.clear();
45
47
  }
46
48
  };
47
49
  }
48
- const re = typeof window < "u" && typeof document < "u";
50
+ const ie = typeof window < "u" && typeof document < "u";
49
51
  typeof WorkerGlobalScope < "u" && globalThis instanceof WorkerGlobalScope;
50
- const de = () => {
52
+ const he = () => {
51
53
  };
52
54
  function L(...e) {
53
55
  if (e.length !== 1)
54
- return ae(...e);
56
+ return le(...e);
55
57
  const t = e[0];
56
- return typeof t == "function" ? W(le(() => ({ get: t, set: de }))) : ie(t);
58
+ return typeof t == "function" ? z(ue(() => ({ get: t, set: he }))) : se(t);
57
59
  }
58
- function Z(e, t = !1, i = "Timeout") {
59
- return new Promise((s, y) => {
60
- setTimeout(t ? () => y(i) : s, e);
60
+ function ee(e, t = !1, a = "Timeout") {
61
+ return new Promise((c, h) => {
62
+ setTimeout(t ? () => h(a) : c, e);
61
63
  });
62
64
  }
63
- function pe(e, ...t) {
64
- return t.some((i) => i in e);
65
+ function ye(e, ...t) {
66
+ return t.some((a) => a in e);
65
67
  }
66
- function z(e, t = !1) {
67
- function i(r, { flush: c = "sync", deep: a = !1, timeout: p, throwOnTimeout: b } = {}) {
68
- let h = null;
69
- const D = [new Promise((F) => {
70
- h = M(
68
+ function Q(e, t = !1) {
69
+ function a(o, { flush: u = "sync", deep: m = !1, timeout: i, throwOnTimeout: b } = {}) {
70
+ let y = null;
71
+ const P = [new Promise((w) => {
72
+ y = _(
71
73
  e,
72
- (w) => {
73
- r(w) !== t && (h ? h() : Y(() => h == null ? void 0 : h()), F(w));
74
+ (v) => {
75
+ o(v) !== t && (y ? y() : Z(() => y?.()), w(v));
74
76
  },
75
77
  {
76
- flush: c,
77
- deep: a,
78
+ flush: u,
79
+ deep: m,
78
80
  immediate: !0
79
81
  }
80
82
  );
81
83
  })];
82
- return p != null && D.push(
83
- Z(p, b).then(() => P(e)).finally(() => h == null ? void 0 : h())
84
- ), Promise.race(D);
84
+ return i != null && P.push(
85
+ ee(i, b).then(() => E(e)).finally(() => y?.())
86
+ ), Promise.race(P);
85
87
  }
86
- function s(r, c) {
87
- if (!te(r))
88
- return i((w) => w === r, c);
89
- const { flush: a = "sync", deep: p = !1, timeout: b, throwOnTimeout: h } = c ?? {};
88
+ function c(o, u) {
89
+ if (!ne(o))
90
+ return a((v) => v === o, u);
91
+ const { flush: m = "sync", deep: i = !1, timeout: b, throwOnTimeout: y } = u ?? {};
90
92
  let T = null;
91
- const F = [new Promise((w) => {
92
- T = M(
93
- [e, r],
94
- ([O, j]) => {
95
- t !== (O === j) && (T ? T() : Y(() => T == null ? void 0 : T()), w(O));
93
+ const w = [new Promise((v) => {
94
+ T = _(
95
+ [e, o],
96
+ ([J, D]) => {
97
+ t !== (J === D) && (T ? T() : Z(() => T?.()), v(J));
96
98
  },
97
99
  {
98
- flush: a,
99
- deep: p,
100
+ flush: m,
101
+ deep: i,
100
102
  immediate: !0
101
103
  }
102
104
  );
103
105
  })];
104
- return b != null && F.push(
105
- Z(b, h).then(() => P(e)).finally(() => (T == null || T(), P(e)))
106
- ), Promise.race(F);
106
+ return b != null && w.push(
107
+ ee(b, y).then(() => E(e)).finally(() => (T?.(), E(e)))
108
+ ), Promise.race(w);
107
109
  }
108
- function y(r) {
109
- return i((c) => !!c, r);
110
+ function h(o) {
111
+ return a((u) => !!u, o);
110
112
  }
111
- function o(r) {
112
- return s(null, r);
113
+ function l(o) {
114
+ return c(null, o);
113
115
  }
114
- function n(r) {
115
- return s(void 0, r);
116
+ function n(o) {
117
+ return c(void 0, o);
116
118
  }
117
- function d(r) {
118
- return i(Number.isNaN, r);
119
+ function r(o) {
120
+ return a(Number.isNaN, o);
119
121
  }
120
- function g(r, c) {
121
- return i((a) => {
122
- const p = Array.from(a);
123
- return p.includes(r) || p.includes(P(r));
124
- }, c);
122
+ function p(o, u) {
123
+ return a((m) => {
124
+ const i = Array.from(m);
125
+ return i.includes(o) || i.includes(E(o));
126
+ }, u);
125
127
  }
126
- function l(r) {
127
- return m(1, r);
128
+ function g(o) {
129
+ return s(1, o);
128
130
  }
129
- function m(r = 1, c) {
130
- let a = -1;
131
- return i(() => (a += 1, a >= r), c);
131
+ function s(o = 1, u) {
132
+ let m = -1;
133
+ return a(() => (m += 1, m >= o), u);
132
134
  }
133
- return Array.isArray(P(e)) ? {
134
- toMatch: i,
135
- toContains: g,
136
- changed: l,
137
- changedTimes: m,
135
+ return Array.isArray(E(e)) ? {
136
+ toMatch: a,
137
+ toContains: p,
138
+ changed: g,
139
+ changedTimes: s,
138
140
  get not() {
139
- return z(e, !t);
141
+ return Q(e, !t);
140
142
  }
141
143
  } : {
142
- toMatch: i,
143
- toBe: s,
144
- toBeTruthy: y,
145
- toBeNull: o,
146
- toBeNaN: d,
144
+ toMatch: a,
145
+ toBe: c,
146
+ toBeTruthy: h,
147
+ toBeNull: l,
148
+ toBeNaN: r,
147
149
  toBeUndefined: n,
148
- changed: l,
149
- changedTimes: m,
150
+ changed: g,
151
+ changedTimes: s,
150
152
  get not() {
151
- return z(e, !t);
153
+ return Q(e, !t);
152
154
  }
153
155
  };
154
156
  }
155
- function he(e) {
156
- return z(e);
157
+ function me(e) {
158
+ return Q(e);
157
159
  }
158
- function ye(e, t, i = {}) {
160
+ function Te(e, t, a = {}) {
159
161
  const {
160
- immediate: s = !0,
161
- immediateCallback: y = !1
162
- } = i, o = E(!1);
163
- let n = null;
164
- function d() {
165
- n && (clearTimeout(n), n = null);
162
+ immediate: c = !0,
163
+ immediateCallback: h = !1
164
+ } = a, l = O(!1);
165
+ let n;
166
+ function r() {
167
+ n && (clearTimeout(n), n = void 0);
166
168
  }
167
- function g() {
168
- o.value = !1, d();
169
+ function p() {
170
+ l.value = !1, r();
169
171
  }
170
- function l(...m) {
171
- y && e(), d(), o.value = !0, n = setTimeout(() => {
172
- o.value = !1, n = null, e(...m);
173
- }, P(t));
172
+ function g(...s) {
173
+ h && e(), r(), l.value = !0, n = setTimeout(() => {
174
+ l.value = !1, n = void 0, e(...s);
175
+ }, E(t));
174
176
  }
175
- return s && (o.value = !0, re && l()), oe(g), {
176
- isPending: W(o),
177
- start: l,
178
- stop: g
177
+ return c && (l.value = !0, ie && g()), re(p), {
178
+ isPending: ae(l),
179
+ start: g,
180
+ stop: p
179
181
  };
180
182
  }
181
- const me = re ? window : void 0, Te = {
183
+ const ve = ie ? window : void 0, ge = {
182
184
  json: "application/json",
183
185
  text: "text/plain"
184
186
  };
185
- function ee(e) {
186
- return e && pe(e, "immediate", "refetch", "initialData", "timeout", "beforeFetch", "afterFetch", "onFetchError", "fetch", "updateDataOnError");
187
+ function te(e) {
188
+ return e && ye(e, "immediate", "refetch", "initialData", "timeout", "beforeFetch", "afterFetch", "onFetchError", "fetch", "updateDataOnError");
187
189
  }
188
190
  function V(e) {
189
191
  return typeof Headers < "u" && e instanceof Headers ? Object.fromEntries(e.entries()) : e;
190
192
  }
191
- function ve(e, ...t) {
192
- var i;
193
- const s = typeof AbortController == "function";
194
- let y = {}, o = {
193
+ function be(e, ...t) {
194
+ var a, c;
195
+ const h = typeof AbortController == "function";
196
+ let l = {}, n = {
195
197
  immediate: !0,
196
198
  refetch: !1,
197
199
  timeout: 0,
198
200
  updateDataOnError: !1
199
201
  };
200
- const n = {
202
+ const r = {
201
203
  method: "GET",
202
204
  type: "text",
203
205
  payload: void 0
204
206
  };
205
- t.length > 0 && (ee(t[0]) ? o = { ...o, ...t[0] } : y = t[0]), t.length > 1 && ee(t[1]) && (o = { ...o, ...t[1] });
207
+ t.length > 0 && (te(t[0]) ? n = { ...n, ...t[0] } : l = t[0]), t.length > 1 && te(t[1]) && (n = { ...n, ...t[1] });
206
208
  const {
207
- fetch: d = (i = me) == null ? void 0 : i.fetch,
209
+ fetch: p = (c = (a = ve) == null ? void 0 : a.fetch) != null ? c : globalThis?.fetch,
208
210
  initialData: g,
209
- timeout: l
210
- } = o, m = I(), r = I(), c = I(), a = E(!1), p = E(!1), b = E(!1), h = E(null), T = E(null), D = E(null), F = E(g || null), w = ce(() => s && p.value);
211
- let O, j;
212
- const _ = () => {
213
- s && (O == null || O.abort(), O = new AbortController(), O.signal.onabort = () => b.value = !0, y = {
214
- ...y,
215
- signal: O.signal
211
+ timeout: s
212
+ } = n, o = /* @__PURE__ */ I(), u = /* @__PURE__ */ I(), m = /* @__PURE__ */ I(), i = O(!1), b = O(!1), y = O(!1), T = O(null), P = O(null), w = O(null), v = O(g || null), J = de(() => h && b.value);
213
+ let D, N;
214
+ const M = (f) => {
215
+ h && (D?.abort(f), D = new AbortController(), D.signal.onabort = () => y.value = !0, l = {
216
+ ...l,
217
+ signal: D.signal
216
218
  });
217
219
  }, $ = (f) => {
218
- p.value = f, a.value = !f;
220
+ b.value = f, i.value = !f;
219
221
  };
220
- l && (j = ye(_, l, { immediate: !1 }));
222
+ s && (N = Te(M, s, { immediate: !1 }));
221
223
  let K = 0;
222
- const H = async (f = !1) => {
223
- var v, N;
224
- _(), $(!0), D.value = null, h.value = null, b.value = !1, K += 1;
224
+ const B = async (f = !1) => {
225
+ var F, x;
226
+ M(), $(!0), w.value = null, T.value = null, y.value = !1, K += 1;
225
227
  const U = K, S = {
226
- method: n.method,
228
+ method: r.method,
227
229
  headers: {}
228
- }, x = P(n.payload);
229
- if (x) {
230
- const u = V(S.headers), G = Object.getPrototypeOf(x);
231
- !n.payloadType && x && (G === Object.prototype || Array.isArray(G)) && !(x instanceof FormData) && (n.payloadType = "json"), n.payloadType && (u["Content-Type"] = (v = Te[n.payloadType]) != null ? v : n.payloadType), S.body = n.payloadType === "json" ? JSON.stringify(x) : x;
230
+ }, H = E(r.payload);
231
+ if (H) {
232
+ const d = V(S.headers), G = Object.getPrototypeOf(H);
233
+ !r.payloadType && H && (G === Object.prototype || Array.isArray(G)) && !(H instanceof FormData) && (r.payloadType = "json"), r.payloadType && (d["Content-Type"] = (F = ge[r.payloadType]) != null ? F : r.payloadType), S.body = r.payloadType === "json" ? JSON.stringify(H) : H;
232
234
  }
233
- let R = !1;
234
- const C = {
235
- url: P(e),
235
+ let X = !1;
236
+ const A = {
237
+ url: E(e),
236
238
  options: {
237
239
  ...S,
238
- ...y
240
+ ...l
239
241
  },
240
242
  cancel: () => {
241
- R = !0;
243
+ X = !0;
242
244
  }
243
245
  };
244
- if (o.beforeFetch && Object.assign(C, await o.beforeFetch(C)), R || !d)
246
+ if (n.beforeFetch && Object.assign(A, await n.beforeFetch(A)), X || !p)
245
247
  return $(!1), Promise.resolve(null);
246
- let B = null;
247
- return j && j.start(), d(
248
- C.url,
248
+ let C = null;
249
+ return N && N.start(), p(
250
+ A.url,
249
251
  {
250
252
  ...S,
251
- ...C.options,
253
+ ...A.options,
252
254
  headers: {
253
255
  ...V(S.headers),
254
- ...V((N = C.options) == null ? void 0 : N.headers)
256
+ ...V((x = A.options) == null ? void 0 : x.headers)
255
257
  }
256
258
  }
257
- ).then(async (u) => {
258
- if (T.value = u, h.value = u.status, B = await u.clone()[n.type](), !u.ok)
259
- throw F.value = g || null, new Error(u.statusText);
260
- return o.afterFetch && ({ data: B } = await o.afterFetch({
261
- data: B,
262
- response: u,
263
- context: C,
264
- execute: H
265
- })), F.value = B, m.trigger(u), u;
266
- }).catch(async (u) => {
267
- let G = u.message || u.name;
268
- if (o.onFetchError && ({ error: G, data: B } = await o.onFetchError({
269
- data: B,
270
- error: u,
271
- response: T.value,
272
- context: C,
273
- execute: H
274
- })), D.value = G, o.updateDataOnError && (F.value = B), r.trigger(u), f)
275
- throw u;
259
+ ).then(async (d) => {
260
+ if (P.value = d, T.value = d.status, C = await d.clone()[r.type](), !d.ok)
261
+ throw v.value = g || null, new Error(d.statusText);
262
+ return n.afterFetch && ({ data: C } = await n.afterFetch({
263
+ data: C,
264
+ response: d,
265
+ context: A,
266
+ execute: B
267
+ })), v.value = C, o.trigger(d), d;
268
+ }).catch(async (d) => {
269
+ let G = d.message || d.name;
270
+ if (n.onFetchError && ({ error: G, data: C } = await n.onFetchError({
271
+ data: C,
272
+ error: d,
273
+ response: P.value,
274
+ context: A,
275
+ execute: B
276
+ })), w.value = G, n.updateDataOnError && (v.value = C), u.trigger(d), f)
277
+ throw d;
276
278
  return null;
277
279
  }).finally(() => {
278
- U === K && $(!1), j && j.stop(), c.trigger(null);
280
+ U === K && $(!1), N && N.stop(), m.trigger(null);
279
281
  });
280
- }, Q = L(o.refetch);
281
- M(
282
+ }, R = L(n.refetch);
283
+ _(
282
284
  [
283
- Q,
285
+ R,
284
286
  L(e)
285
287
  ],
286
- ([f]) => f && H(),
288
+ ([f]) => f && B(),
287
289
  { deep: !0 }
288
290
  );
289
- const J = {
290
- isFinished: W(a),
291
- isFetching: W(p),
292
- statusCode: h,
293
- response: T,
294
- error: D,
295
- data: F,
296
- canAbort: w,
297
- aborted: b,
298
- abort: _,
299
- execute: H,
300
- onFetchResponse: m.on,
301
- onFetchError: r.on,
302
- onFetchFinally: c.on,
291
+ const W = {
292
+ isFinished: z(i),
293
+ isFetching: z(b),
294
+ statusCode: T,
295
+ response: P,
296
+ error: w,
297
+ data: v,
298
+ canAbort: J,
299
+ aborted: y,
300
+ abort: M,
301
+ execute: B,
302
+ onFetchResponse: o.on,
303
+ onFetchError: u.on,
304
+ onFetchFinally: m.on,
303
305
  // method
304
- get: A("GET"),
305
- put: A("PUT"),
306
- post: A("POST"),
307
- delete: A("DELETE"),
308
- patch: A("PATCH"),
309
- head: A("HEAD"),
310
- options: A("OPTIONS"),
306
+ get: j("GET"),
307
+ put: j("PUT"),
308
+ post: j("POST"),
309
+ delete: j("DELETE"),
310
+ patch: j("PATCH"),
311
+ head: j("HEAD"),
312
+ options: j("OPTIONS"),
311
313
  // type
312
314
  json: k("json"),
313
315
  text: k("text"),
@@ -315,18 +317,18 @@ function ve(e, ...t) {
315
317
  arrayBuffer: k("arrayBuffer"),
316
318
  formData: k("formData")
317
319
  };
318
- function A(f) {
319
- return (v, N) => {
320
- if (!p.value)
321
- return n.method = f, n.payload = v, n.payloadType = N, te(n.payload) && M(
320
+ function j(f) {
321
+ return (F, x) => {
322
+ if (!b.value)
323
+ return r.method = f, r.payload = F, r.payloadType = x, ne(r.payload) && _(
322
324
  [
323
- Q,
324
- L(n.payload)
325
+ R,
326
+ L(r.payload)
325
327
  ],
326
- ([U]) => U && H(),
328
+ ([U]) => U && B(),
327
329
  { deep: !0 }
328
330
  ), {
329
- ...J,
331
+ ...W,
330
332
  then(U, S) {
331
333
  return q().then(U, S);
332
334
  }
@@ -334,79 +336,83 @@ function ve(e, ...t) {
334
336
  };
335
337
  }
336
338
  function q() {
337
- return new Promise((f, v) => {
338
- he(a).toBe(!0).then(() => f(J)).catch(v);
339
+ return new Promise((f, F) => {
340
+ me(i).toBe(!0).then(() => f(W)).catch(F);
339
341
  });
340
342
  }
341
343
  function k(f) {
342
344
  return () => {
343
- if (!p.value)
344
- return n.type = f, {
345
- ...J,
346
- then(v, N) {
347
- return q().then(v, N);
345
+ if (!b.value)
346
+ return r.type = f, {
347
+ ...W,
348
+ then(F, x) {
349
+ return q().then(F, x);
348
350
  }
349
351
  };
350
352
  };
351
353
  }
352
- return o.immediate && Promise.resolve().then(() => H()), {
353
- ...J,
354
- then(f, v) {
355
- return q().then(f, v);
354
+ return n.immediate && Promise.resolve().then(() => B()), {
355
+ ...W,
356
+ then(f, F) {
357
+ return q().then(f, F);
356
358
  }
357
359
  };
358
360
  }
359
- function Pe(e, t, i = "/api/") {
360
- const s = {};
361
- return Object.keys(e).forEach((o) => {
362
- s[o] = (...n) => {
363
- const d = e[o], g = d.type;
364
- let l = d.url;
365
- l.startsWith("http") || (l = `${i}${l}`), d.hasBody ? l = X(l, ...n.splice(1)) : l = X(l, ...n);
366
- const m = {
367
- ...ne(),
368
- ...d.headers()
361
+ function je(e, t, a = "/api/", c) {
362
+ const h = {};
363
+ return Object.keys(e).forEach((n) => {
364
+ h[n] = (...r) => {
365
+ const p = e[n], g = p.type;
366
+ let s = p.url;
367
+ s.startsWith("http") || (s = `${a}${s}`), p.hasBody ? s = Y(s, ...r.splice(1)) : s = Y(s, ...r);
368
+ const o = {
369
+ ...oe(),
370
+ ...p.headers()
369
371
  };
370
- ge(m);
371
- const r = ve(
372
- l,
372
+ Fe(o);
373
+ const u = be(
374
+ s,
373
375
  {
376
+ ...p.options,
374
377
  method: g
375
378
  },
376
379
  {
377
380
  immediate: !1,
378
- beforeFetch({ options: a }) {
379
- return a.headers = {
380
- ...a.headers,
381
- ...m
382
- }, d.hasBody && n.length && (a.body = JSON.stringify(n[0])), {
383
- options: a
381
+ beforeFetch({ options: i }) {
382
+ return i.headers = {
383
+ ...i.headers,
384
+ ...o
385
+ }, p.hasBody && r.length && (i.body = JSON.stringify(r[0])), {
386
+ options: i
384
387
  };
385
388
  },
386
- onFetchError(a) {
387
- return a != null && a.response && t(a), a;
389
+ onFetchError(i) {
390
+ return i?.response && t(i), i;
391
+ },
392
+ afterFetch(i) {
393
+ return c && c(i, p), i;
388
394
  }
389
395
  }
390
396
  );
391
397
  return {
392
- ...Fe(m) === "application/json" ? r.json() : r.text()
398
+ ...we(o) === "application/json" ? u.json() : u.text()
393
399
  };
394
400
  };
395
- }), s;
401
+ }), h;
396
402
  }
397
- function ge(e) {
403
+ function Fe(e) {
398
404
  e["content-type"] === "multipart/form-data" && delete e["content-type"];
399
405
  }
400
- function Fe(e) {
406
+ function we(e) {
401
407
  return e.accept ?? "*/*";
402
408
  }
403
- function De(e) {
409
+ function Se(e) {
404
410
  return JSON.parse(JSON.stringify(e));
405
411
  }
406
412
  export {
407
- De as copy,
408
- Ee as createEndpoint,
409
- ne as getDefaultHeaders,
410
- Oe as requestTypes,
411
- Pe as useApi
413
+ Se as copy,
414
+ De as createEndpoint,
415
+ oe as getDefaultHeaders,
416
+ Pe as requestTypes,
417
+ je as useApi
412
418
  };
@@ -1 +1 @@
1
- (function(m,V){typeof exports=="object"&&typeof module<"u"?V(exports,require("@citruslime/utils"),require("vue")):typeof define=="function"&&define.amd?define(["exports","@citruslime/utils","vue"],V):(m=typeof globalThis<"u"?globalThis:m||self,V(m.CitrusLimeVueUtils={},m.CLUtils,m.Vue))})(this,function(m,V,t){"use strict";const te=["GET","POST","PUT","DELETE"];function ne(e,n,l=null,u=null){return{url:e,type:n,headers:l??J,hasBody:oe(n,u)}}function J(){return{accept:"application/json","content-type":"application/json"}}function oe(e,n){return!!(n===null&&(e==="PUT"||e==="POST")||n)}function z(e){return t.getCurrentScope()?(t.onScopeDispose(e),!0):!1}function M(){const e=new Set,n=r=>{e.delete(r)};return{on:r=>{e.add(r);const o=()=>n(r);return z(o),{off:o}},off:n,trigger:(...r)=>Promise.all(Array.from(e).map(o=>o(...r))),clear:()=>{e.clear()}}}const Q=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const re=()=>{};function W(...e){if(e.length!==1)return t.toRef(...e);const n=e[0];return typeof n=="function"?t.readonly(t.customRef(()=>({get:n,set:re}))):t.ref(n)}function X(e,n=!1,l="Timeout"){return new Promise((u,T)=>{setTimeout(n?()=>T(l):u,e)})}function ie(e,...n){return n.some(l=>l in e)}function v(e,n=!1){function l(i,{flush:f="sync",deep:a=!1,timeout:h,throwOnTimeout:E}={}){let y=null;const j=[new Promise(O=>{y=t.watch(e,P=>{i(P)!==n&&(y?y():t.nextTick(()=>y==null?void 0:y()),O(P))},{flush:f,deep:a,immediate:!0})})];return h!=null&&j.push(X(h,E).then(()=>t.toValue(e)).finally(()=>y==null?void 0:y())),Promise.race(j)}function u(i,f){if(!t.isRef(i))return l(P=>P===i,f);const{flush:a="sync",deep:h=!1,timeout:E,throwOnTimeout:y}=f??{};let g=null;const O=[new Promise(P=>{g=t.watch([e,i],([D,S])=>{n!==(D===S)&&(g?g():t.nextTick(()=>g==null?void 0:g()),P(D))},{flush:a,deep:h,immediate:!0})})];return E!=null&&O.push(X(E,y).then(()=>t.toValue(e)).finally(()=>(g==null||g(),t.toValue(e)))),Promise.race(O)}function T(i){return l(f=>!!f,i)}function r(i){return u(null,i)}function o(i){return u(void 0,i)}function p(i){return l(Number.isNaN,i)}function F(i,f){return l(a=>{const h=Array.from(a);return h.includes(i)||h.includes(t.toValue(i))},f)}function s(i){return w(1,i)}function w(i=1,f){let a=-1;return l(()=>(a+=1,a>=i),f)}return Array.isArray(t.toValue(e))?{toMatch:l,toContains:F,changed:s,changedTimes:w,get not(){return v(e,!n)}}:{toMatch:l,toBe:u,toBeTruthy:T,toBeNull:r,toBeNaN:p,toBeUndefined:o,changed:s,changedTimes:w,get not(){return v(e,!n)}}}function ae(e){return v(e)}function le(e,n,l={}){const{immediate:u=!0,immediateCallback:T=!1}=l,r=t.shallowRef(!1);let o=null;function p(){o&&(clearTimeout(o),o=null)}function F(){r.value=!1,p()}function s(...w){T&&e(),p(),r.value=!0,o=setTimeout(()=>{r.value=!1,o=null,e(...w)},t.toValue(n))}return u&&(r.value=!0,Q&&s()),z(F),{isPending:t.readonly(r),start:s,stop:F}}const se=Q?window:void 0,ue={json:"application/json",text:"text/plain"};function Y(e){return e&&ie(e,"immediate","refetch","initialData","timeout","beforeFetch","afterFetch","onFetchError","fetch","updateDataOnError")}function L(e){return typeof Headers<"u"&&e instanceof Headers?Object.fromEntries(e.entries()):e}function ce(e,...n){var l;const u=typeof AbortController=="function";let T={},r={immediate:!0,refetch:!1,timeout:0,updateDataOnError:!1};const o={method:"GET",type:"text",payload:void 0};n.length>0&&(Y(n[0])?r={...r,...n[0]}:T=n[0]),n.length>1&&Y(n[1])&&(r={...r,...n[1]});const{fetch:p=(l=se)==null?void 0:l.fetch,initialData:F,timeout:s}=r,w=M(),i=M(),f=M(),a=t.shallowRef(!1),h=t.shallowRef(!1),E=t.shallowRef(!1),y=t.shallowRef(null),g=t.shallowRef(null),j=t.shallowRef(null),O=t.shallowRef(F||null),P=t.computed(()=>u&&h.value);let D,S;const _=()=>{u&&(D==null||D.abort(),D=new AbortController,D.signal.onabort=()=>E.value=!0,T={...T,signal:D.signal})},K=d=>{h.value=d,a.value=!d};s&&(S=le(_,s,{immediate:!1}));let $=0;const N=async(d=!1)=>{var b,U;_(),K(!0),j.value=null,y.value=null,E.value=!1,$+=1;const x=$,C={method:o.method,headers:{}},k=t.toValue(o.payload);if(k){const c=L(C.headers),G=Object.getPrototypeOf(k);!o.payloadType&&k&&(G===Object.prototype||Array.isArray(G))&&!(k instanceof FormData)&&(o.payloadType="json"),o.payloadType&&(c["Content-Type"]=(b=ue[o.payloadType])!=null?b:o.payloadType),C.body=o.payloadType==="json"?JSON.stringify(k):k}let ee=!1;const B={url:t.toValue(e),options:{...C,...T},cancel:()=>{ee=!0}};if(r.beforeFetch&&Object.assign(B,await r.beforeFetch(B)),ee||!p)return K(!1),Promise.resolve(null);let H=null;return S&&S.start(),p(B.url,{...C,...B.options,headers:{...L(C.headers),...L((U=B.options)==null?void 0:U.headers)}}).then(async c=>{if(g.value=c,y.value=c.status,H=await c.clone()[o.type](),!c.ok)throw O.value=F||null,new Error(c.statusText);return r.afterFetch&&({data:H}=await r.afterFetch({data:H,response:c,context:B,execute:N})),O.value=H,w.trigger(c),c}).catch(async c=>{let G=c.message||c.name;if(r.onFetchError&&({error:G,data:H}=await r.onFetchError({data:H,error:c,response:g.value,context:B,execute:N})),j.value=G,r.updateDataOnError&&(O.value=H),i.trigger(c),d)throw c;return null}).finally(()=>{x===$&&K(!1),S&&S.stop(),f.trigger(null)})},Z=W(r.refetch);t.watch([Z,W(e)],([d])=>d&&N(),{deep:!0});const q={isFinished:t.readonly(a),isFetching:t.readonly(h),statusCode:y,response:g,error:j,data:O,canAbort:P,aborted:E,abort:_,execute:N,onFetchResponse:w.on,onFetchError:i.on,onFetchFinally:f.on,get:A("GET"),put:A("PUT"),post:A("POST"),delete:A("DELETE"),patch:A("PATCH"),head:A("HEAD"),options:A("OPTIONS"),json:R("json"),text:R("text"),blob:R("blob"),arrayBuffer:R("arrayBuffer"),formData:R("formData")};function A(d){return(b,U)=>{if(!h.value)return o.method=d,o.payload=b,o.payloadType=U,t.isRef(o.payload)&&t.watch([Z,W(o.payload)],([x])=>x&&N(),{deep:!0}),{...q,then(x,C){return I().then(x,C)}}}}function I(){return new Promise((d,b)=>{ae(a).toBe(!0).then(()=>d(q)).catch(b)})}function R(d){return()=>{if(!h.value)return o.type=d,{...q,then(b,U){return I().then(b,U)}}}}return r.immediate&&Promise.resolve().then(()=>N()),{...q,then(d,b){return I().then(d,b)}}}function fe(e,n,l="/api/"){const u={};return Object.keys(e).forEach(r=>{u[r]=(...o)=>{const p=e[r],F=p.type;let s=p.url;s.startsWith("http")||(s=`${l}${s}`),p.hasBody?s=V.replacePlaceholders(s,...o.splice(1)):s=V.replacePlaceholders(s,...o);const w={...J(),...p.headers()};de(w);const i=ce(s,{method:F},{immediate:!1,beforeFetch({options:a}){return a.headers={...a.headers,...w},p.hasBody&&o.length&&(a.body=JSON.stringify(o[0])),{options:a}},onFetchError(a){return a!=null&&a.response&&n(a),a}});return{...pe(w)==="application/json"?i.json():i.text()}}}),u}function de(e){e["content-type"]==="multipart/form-data"&&delete e["content-type"]}function pe(e){return e.accept??"*/*"}function he(e){return JSON.parse(JSON.stringify(e))}m.copy=he,m.createEndpoint=ne,m.getDefaultHeaders=J,m.requestTypes=te,m.useApi=fe,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
1
+ (function(T,H){typeof exports=="object"&&typeof module<"u"?H(exports,require("@citruslime/utils"),require("vue")):typeof define=="function"&&define.amd?define(["exports","@citruslime/utils","vue"],H):(T=typeof globalThis<"u"?globalThis:T||self,H(T.CitrusLimeVueUtils={},T.CLUtils,T.Vue))})(this,(function(T,H,t){"use strict";const ne=["GET","POST","PUT","DELETE"];function oe(e,n,l=null,f=null,y=null){return{url:e,type:n,headers:l??J,hasBody:re(n,f),options:y??{}}}function J(){return{accept:"application/json","content-type":"application/json"}}function re(e,n){return!!(n===null&&(e==="PUT"||e==="POST")||n)}function Q(e){return t.getCurrentScope()?(t.onScopeDispose(e),!0):!1}function M(){const e=new Set,n=s=>{e.delete(s)};return{on:s=>{e.add(s);const o=()=>n(s);return Q(o),{off:o}},off:n,trigger:(...s)=>Promise.all(Array.from(e).map(o=>o(...s))),clear:()=>{e.clear()}}}const X=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const ie=()=>{};function W(...e){if(e.length!==1)return t.toRef(...e);const n=e[0];return typeof n=="function"?t.readonly(t.customRef(()=>({get:n,set:ie}))):t.ref(n)}function Y(e,n=!1,l="Timeout"){return new Promise((f,y)=>{setTimeout(n?()=>y(l):f,e)})}function ae(e,...n){return n.some(l=>l in e)}function _(e,n=!1){function l(r,{flush:c="sync",deep:w=!1,timeout:a,throwOnTimeout:O}={}){let m=null;const D=[new Promise(P=>{m=t.watch(e,b=>{r(b)!==n&&(m?m():t.nextTick(()=>m?.()),P(b))},{flush:c,deep:w,immediate:!0})})];return a!=null&&D.push(Y(a,O).then(()=>t.toValue(e)).finally(()=>m?.())),Promise.race(D)}function f(r,c){if(!t.isRef(r))return l(b=>b===r,c);const{flush:w="sync",deep:a=!1,timeout:O,throwOnTimeout:m}=c??{};let g=null;const P=[new Promise(b=>{g=t.watch([e,r],([G,j])=>{n!==(G===j)&&(g?g():t.nextTick(()=>g?.()),b(G))},{flush:w,deep:a,immediate:!0})})];return O!=null&&P.push(Y(O,m).then(()=>t.toValue(e)).finally(()=>(g?.(),t.toValue(e)))),Promise.race(P)}function y(r){return l(c=>!!c,r)}function s(r){return f(null,r)}function o(r){return f(void 0,r)}function i(r){return l(Number.isNaN,r)}function h(r,c){return l(w=>{const a=Array.from(w);return a.includes(r)||a.includes(t.toValue(r))},c)}function F(r){return u(1,r)}function u(r=1,c){let w=-1;return l(()=>(w+=1,w>=r),c)}return Array.isArray(t.toValue(e))?{toMatch:l,toContains:h,changed:F,changedTimes:u,get not(){return _(e,!n)}}:{toMatch:l,toBe:f,toBeTruthy:y,toBeNull:s,toBeNaN:i,toBeUndefined:o,changed:F,changedTimes:u,get not(){return _(e,!n)}}}function le(e){return _(e)}function se(e,n,l={}){const{immediate:f=!0,immediateCallback:y=!1}=l,s=t.shallowRef(!1);let o;function i(){o&&(clearTimeout(o),o=void 0)}function h(){s.value=!1,i()}function F(...u){y&&e(),i(),s.value=!0,o=setTimeout(()=>{s.value=!1,o=void 0,e(...u)},t.toValue(n))}return f&&(s.value=!0,X&&F()),Q(h),{isPending:t.shallowReadonly(s),start:F,stop:h}}const ue=X?window:void 0,ce={json:"application/json",text:"text/plain"};function Z(e){return e&&ae(e,"immediate","refetch","initialData","timeout","beforeFetch","afterFetch","onFetchError","fetch","updateDataOnError")}function L(e){return typeof Headers<"u"&&e instanceof Headers?Object.fromEntries(e.entries()):e}function fe(e,...n){var l,f;const y=typeof AbortController=="function";let s={},o={immediate:!0,refetch:!1,timeout:0,updateDataOnError:!1};const i={method:"GET",type:"text",payload:void 0};n.length>0&&(Z(n[0])?o={...o,...n[0]}:s=n[0]),n.length>1&&Z(n[1])&&(o={...o,...n[1]});const{fetch:h=(f=(l=ue)==null?void 0:l.fetch)!=null?f:globalThis?.fetch,initialData:F,timeout:u}=o,r=M(),c=M(),w=M(),a=t.shallowRef(!1),O=t.shallowRef(!1),m=t.shallowRef(!1),g=t.shallowRef(null),D=t.shallowRef(null),P=t.shallowRef(null),b=t.shallowRef(F||null),G=t.computed(()=>y&&O.value);let j,U;const K=d=>{y&&(j?.abort(d),j=new AbortController,j.signal.onabort=()=>m.value=!0,s={...s,signal:j.signal})},$=d=>{O.value=d,a.value=!d};u&&(U=se(K,u,{immediate:!1}));let I=0;const V=async(d=!1)=>{var E,x;K(),$(!0),P.value=null,g.value=null,m.value=!1,I+=1;const R=I,C={method:i.method,headers:{}},N=t.toValue(i.payload);if(N){const p=L(C.headers),v=Object.getPrototypeOf(N);!i.payloadType&&N&&(v===Object.prototype||Array.isArray(v))&&!(N instanceof FormData)&&(i.payloadType="json"),i.payloadType&&(p["Content-Type"]=(E=ce[i.payloadType])!=null?E:i.payloadType),C.body=i.payloadType==="json"?JSON.stringify(N):N}let te=!1;const A={url:t.toValue(e),options:{...C,...s},cancel:()=>{te=!0}};if(o.beforeFetch&&Object.assign(A,await o.beforeFetch(A)),te||!h)return $(!1),Promise.resolve(null);let B=null;return U&&U.start(),h(A.url,{...C,...A.options,headers:{...L(C.headers),...L((x=A.options)==null?void 0:x.headers)}}).then(async p=>{if(D.value=p,g.value=p.status,B=await p.clone()[i.type](),!p.ok)throw b.value=F||null,new Error(p.statusText);return o.afterFetch&&({data:B}=await o.afterFetch({data:B,response:p,context:A,execute:V})),b.value=B,r.trigger(p),p}).catch(async p=>{let v=p.message||p.name;if(o.onFetchError&&({error:v,data:B}=await o.onFetchError({data:B,error:p,response:D.value,context:A,execute:V})),P.value=v,o.updateDataOnError&&(b.value=B),c.trigger(p),d)throw p;return null}).finally(()=>{R===I&&$(!1),U&&U.stop(),w.trigger(null)})},ee=W(o.refetch);t.watch([ee,W(e)],([d])=>d&&V(),{deep:!0});const q={isFinished:t.readonly(a),isFetching:t.readonly(O),statusCode:g,response:D,error:P,data:b,canAbort:G,aborted:m,abort:K,execute:V,onFetchResponse:r.on,onFetchError:c.on,onFetchFinally:w.on,get:S("GET"),put:S("PUT"),post:S("POST"),delete:S("DELETE"),patch:S("PATCH"),head:S("HEAD"),options:S("OPTIONS"),json:k("json"),text:k("text"),blob:k("blob"),arrayBuffer:k("arrayBuffer"),formData:k("formData")};function S(d){return(E,x)=>{if(!O.value)return i.method=d,i.payload=E,i.payloadType=x,t.isRef(i.payload)&&t.watch([ee,W(i.payload)],([R])=>R&&V(),{deep:!0}),{...q,then(R,C){return z().then(R,C)}}}}function z(){return new Promise((d,E)=>{le(a).toBe(!0).then(()=>d(q)).catch(E)})}function k(d){return()=>{if(!O.value)return i.type=d,{...q,then(E,x){return z().then(E,x)}}}}return o.immediate&&Promise.resolve().then(()=>V()),{...q,then(d,E){return z().then(d,E)}}}function de(e,n,l="/api/",f){const y={};return Object.keys(e).forEach(o=>{y[o]=(...i)=>{const h=e[o],F=h.type;let u=h.url;u.startsWith("http")||(u=`${l}${u}`),h.hasBody?u=H.replacePlaceholders(u,...i.splice(1)):u=H.replacePlaceholders(u,...i);const r={...J(),...h.headers()};pe(r);const c=fe(u,{...h.options,method:F},{immediate:!1,beforeFetch({options:a}){return a.headers={...a.headers,...r},h.hasBody&&i.length&&(a.body=JSON.stringify(i[0])),{options:a}},onFetchError(a){return a?.response&&n(a),a},afterFetch(a){return f&&f(a,h),a}});return{...he(r)==="application/json"?c.json():c.text()}}}),y}function pe(e){e["content-type"]==="multipart/form-data"&&delete e["content-type"]}function he(e){return e.accept??"*/*"}function ye(e){return JSON.parse(JSON.stringify(e))}T.copy=ye,T.createEndpoint=oe,T.getDefaultHeaders=J,T.requestTypes=ne,T.useApi=de,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})}));
@@ -4,6 +4,7 @@ export interface Endpoint {
4
4
  type: typeof requestTypes[number];
5
5
  headers: () => HeadersInit;
6
6
  hasBody: boolean;
7
+ options: RequestInit;
7
8
  }
8
9
  /**
9
10
  * Creates an endpoint object, using the provided values.
@@ -12,9 +13,10 @@ export interface Endpoint {
12
13
  * @param type The type of HTTP request to make.
13
14
  * @param headers The headers this request will use.
14
15
  * @param hasBody Determines whether or not an endpoint should have a body.
16
+ * @param options The options to pass to the useFetch composable.
15
17
  * @returns The created Endpoint object.
16
18
  */
17
- export declare function createEndpoint(url: string, type: typeof requestTypes[number], headers?: (() => HeadersInit) | null, hasBody?: boolean | null): Endpoint;
19
+ export declare function createEndpoint(url: string, type: typeof requestTypes[number], headers?: (() => HeadersInit) | null, hasBody?: boolean | null, options?: RequestInit | null): Endpoint;
18
20
  /**
19
21
  * Gets a set of default headers.
20
22
  *
@@ -7,10 +7,14 @@ export type ApiRequest<TResponseModel> = ReturnType<typeof useFetch<TResponseMod
7
7
  * @param endpoints The endpoints provided to build with the factory.
8
8
  * @param handleFetchErrorResponse The error handler for the api factory.
9
9
  * @param prefix The prefix to append to the url (defaults to '/api/').
10
+ * @param handleAfterFetchResponse The optional after fetch response handler for the api factory.
10
11
  * @returns An API object containing request methods.
11
12
  */
12
13
  export declare function useApi<TEndpoint extends Record<keyof TEndpoint, Endpoint>>(endpoints: TEndpoint, handleFetchErrorResponse: (context: {
13
14
  data: unknown;
14
15
  response: Response | null;
15
16
  error: unknown;
16
- }) => void, prefix?: string): Record<keyof TEndpoint, <TResponseModel>(...values: unknown[]) => ApiRequest<TResponseModel>>;
17
+ }) => void, prefix?: string, handleAfterFetchResponse?: (context: {
18
+ data: unknown;
19
+ response: Response;
20
+ }, endPoint: Endpoint) => void): Record<keyof TEndpoint, <TResponseModel>(...values: unknown[]) => ApiRequest<TResponseModel>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@citruslime/vue-utils",
3
- "version": "2.0.4-beta.1",
3
+ "version": "2.0.4-beta.3",
4
4
  "type": "module",
5
5
  "author": {
6
6
  "name": "Citrus-Lime Ltd",
@@ -29,8 +29,8 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@citruslime/utils": "2.0.7-beta.2",
32
- "@vueuse/core": "^13.0.0",
33
- "vue": "^3.5.13"
32
+ "@vueuse/core": "^13.7.0",
33
+ "vue": "^3.5.19"
34
34
  },
35
35
  "scripts": {
36
36
  "build": "run-p build-source build-types",