@dismissible/react-client 0.2.0 → 0.3.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.
@@ -30,6 +30,8 @@ export interface DismissibleProps {
30
30
  cachePrefix?: string;
31
31
  /** Cache expiration time in milliseconds (default: never expires) */
32
32
  cacheExpiration?: number;
33
+ /** Ignore errors and display the component anyway (default: false) */
34
+ ignoreErrors?: boolean;
33
35
  }
34
36
  /**
35
37
  * A wrapper component that can be dismissed and hidden by users
@@ -44,6 +46,7 @@ export interface DismissibleProps {
44
46
  * @param enableCache - Enable localStorage caching
45
47
  * @param cachePrefix - Cache key prefix
46
48
  * @param cacheExpiration - Cache expiration time in milliseconds
49
+ * @param ignoreErrors - Ignore errors and display the component anyway
47
50
  * @returns JSX element or null if dismissed
48
51
  */
49
52
  export declare const Dismissible: React.FC<DismissibleProps>;
@@ -10,13 +10,21 @@ import { DismissibleProviderProps } from '../types/dismissible.types';
10
10
  * <App />
11
11
  * </DismissibleProvider>
12
12
  *
13
- * // With dynamic JWT function
13
+ * // With synchronous JWT function
14
14
  * <DismissibleProvider
15
15
  * jwt={() => getAccessToken()}
16
16
  * baseUrl="https://api.dismissible.io"
17
17
  * >
18
18
  * <App />
19
19
  * </DismissibleProvider>
20
+ *
21
+ * // With asynchronous JWT function
22
+ * <DismissibleProvider
23
+ * jwt={async () => await fetchAccessToken()}
24
+ * baseUrl="https://api.dismissible.io"
25
+ * >
26
+ * <App />
27
+ * </DismissibleProvider>
20
28
  * ```
21
29
  */
22
30
  export declare const DismissibleProvider: React.FC<DismissibleProviderProps>;
@@ -1,221 +1,273 @@
1
- import { jsx as I, jsxs as Q } from "react/jsx-runtime";
2
- import { createContext as te, useContext as re, useMemo as N, useRef as P, useState as q, useCallback as L, useEffect as J } from "react";
3
- const ne = /\{[^{}]+\}/g, se = () => {
1
+ var de = Object.defineProperty, he = Object.defineProperties;
2
+ var me = Object.getOwnPropertyDescriptors;
3
+ var k = Object.getOwnPropertySymbols;
4
+ var V = Object.prototype.hasOwnProperty, X = Object.prototype.propertyIsEnumerable;
5
+ var Q = (e, r, t) => r in e ? de(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t, y = (e, r) => {
6
+ for (var t in r || (r = {}))
7
+ V.call(r, t) && Q(e, t, r[t]);
8
+ if (k)
9
+ for (var t of k(r))
10
+ X.call(r, t) && Q(e, t, r[t]);
11
+ return e;
12
+ }, R = (e, r) => he(e, me(r));
13
+ var W = (e, r) => {
14
+ var t = {};
15
+ for (var n in e)
16
+ V.call(e, n) && r.indexOf(n) < 0 && (t[n] = e[n]);
17
+ if (e != null && k)
18
+ for (var n of k(e))
19
+ r.indexOf(n) < 0 && X.call(e, n) && (t[n] = e[n]);
20
+ return t;
21
+ };
22
+ var S = (e, r, t) => new Promise((n, i) => {
23
+ var s = (c) => {
24
+ try {
25
+ u(t.next(c));
26
+ } catch (h) {
27
+ i(h);
28
+ }
29
+ }, o = (c) => {
30
+ try {
31
+ u(t.throw(c));
32
+ } catch (h) {
33
+ i(h);
34
+ }
35
+ }, u = (c) => c.done ? n(c.value) : Promise.resolve(c.value).then(s, o);
36
+ u((t = t.apply(e, r)).next());
37
+ });
38
+ import { jsx as x, jsxs as oe } from "react/jsx-runtime";
39
+ import { createContext as ye, useContext as be, useMemo as B, useRef as M, useState as F, useCallback as Y, useEffect as Z } from "react";
40
+ const pe = /\{[^{}]+\}/g, ge = () => {
4
41
  var e, r;
5
42
  return typeof process == "object" && Number.parseInt((r = (e = process == null ? void 0 : process.versions) == null ? void 0 : e.node) == null ? void 0 : r.substring(0, 2)) >= 18 && process.versions.undici;
6
43
  };
7
- function ie() {
44
+ function we() {
8
45
  return Math.random().toString(36).slice(2, 11);
9
46
  }
10
- function oe(e) {
11
- let {
47
+ function Re(e) {
48
+ let j = y({}, e), {
12
49
  baseUrl: r = "",
13
50
  Request: t = globalThis.Request,
14
- fetch: s = globalThis.fetch,
15
- querySerializer: n,
16
- bodySerializer: o,
17
- headers: i,
18
- requestInitExt: u = void 0,
19
- ...d
20
- } = { ...e };
21
- u = se() ? u : void 0, r = W(r);
22
- const m = [];
23
- async function y(c, l) {
24
- const {
25
- baseUrl: p,
26
- fetch: E = s,
27
- Request: v = t,
28
- headers: C,
29
- params: w = {},
30
- parseAs: S = "json",
31
- querySerializer: A,
32
- bodySerializer: a = o ?? ce,
33
- body: g,
34
- ...$
35
- } = l || {};
36
- let z = r;
37
- p && (z = W(p) ?? r);
38
- let H = typeof n == "function" ? n : _(n);
39
- A && (H = typeof A == "function" ? A : _({
40
- ...typeof n == "object" ? n : {},
41
- ...A
42
- }));
43
- const k = g === void 0 ? void 0 : a(
44
- g,
45
- // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:
46
- // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,
47
- // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,
48
- // setting the content-type at the very beginning to be overwritten.
49
- // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.
50
- B(i, C, w.header)
51
- ), Z = B(
52
- // with no body, we should not to set Content-Type
53
- k === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
54
- k instanceof FormData ? {} : {
55
- "Content-Type": "application/json"
56
- },
57
- i,
58
- C,
59
- w.header
60
- ), ee = {
61
- redirect: "follow",
62
- ...d,
63
- ...$,
64
- body: k,
65
- headers: Z
66
- };
67
- let U, T, R = new t(
68
- le(c, { baseUrl: z, params: w, querySerializer: H }),
69
- ee
70
- ), f;
71
- for (const b in $)
72
- b in R || (R[b] = $[b]);
73
- if (m.length) {
74
- U = ie(), T = Object.freeze({
75
- baseUrl: z,
76
- fetch: E,
77
- parseAs: S,
78
- querySerializer: H,
79
- bodySerializer: a
51
+ fetch: n = globalThis.fetch,
52
+ querySerializer: i,
53
+ bodySerializer: s,
54
+ headers: o,
55
+ requestInitExt: u = void 0
56
+ } = j, c = W(j, [
57
+ "baseUrl",
58
+ "Request",
59
+ "fetch",
60
+ "querySerializer",
61
+ "bodySerializer",
62
+ "headers",
63
+ "requestInitExt"
64
+ ]);
65
+ u = ge() ? u : void 0, r = re(r);
66
+ const h = [];
67
+ function g(l, a) {
68
+ return S(this, null, function* () {
69
+ var K;
70
+ const G = a || {}, {
71
+ baseUrl: E,
72
+ fetch: C = n,
73
+ Request: $ = t,
74
+ headers: D,
75
+ params: A = {},
76
+ parseAs: q = "json",
77
+ querySerializer: U,
78
+ bodySerializer: f = s != null ? s : Ee,
79
+ body: d
80
+ } = G, v = W(G, [
81
+ "baseUrl",
82
+ "fetch",
83
+ "Request",
84
+ "headers",
85
+ "params",
86
+ "parseAs",
87
+ "querySerializer",
88
+ "bodySerializer",
89
+ "body"
90
+ ]);
91
+ let w = r;
92
+ E && (w = (K = re(E)) != null ? K : r);
93
+ let L = typeof i == "function" ? i : ee(i);
94
+ U && (L = typeof U == "function" ? U : ee(y(y({}, typeof i == "object" ? i : {}), U)));
95
+ const J = d === void 0 ? void 0 : f(
96
+ d,
97
+ // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:
98
+ // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,
99
+ // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,
100
+ // setting the content-type at the very beginning to be overwritten.
101
+ // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.
102
+ te(o, D, A.header)
103
+ ), ue = te(
104
+ // with no body, we should not to set Content-Type
105
+ J === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
106
+ J instanceof FormData ? {} : {
107
+ "Content-Type": "application/json"
108
+ },
109
+ o,
110
+ D,
111
+ A.header
112
+ ), fe = R(y(y({
113
+ redirect: "follow"
114
+ }, c), v), {
115
+ body: J,
116
+ headers: ue
80
117
  });
81
- for (const b of m)
82
- if (b && typeof b == "object" && typeof b.onRequest == "function") {
83
- const h = await b.onRequest({
84
- request: R,
85
- schemaPath: c,
86
- params: w,
87
- options: T,
88
- id: U
89
- });
90
- if (h)
91
- if (h instanceof t)
92
- R = h;
93
- else if (h instanceof Response) {
94
- f = h;
95
- break;
96
- } else
97
- throw new Error("onRequest: must return new Request() or Response() when modifying the request");
118
+ let O, z, I = new t(
119
+ Ce(l, { baseUrl: w, params: A, querySerializer: L }),
120
+ fe
121
+ ), m;
122
+ for (const p in v)
123
+ p in I || (I[p] = v[p]);
124
+ if (h.length) {
125
+ O = we(), z = Object.freeze({
126
+ baseUrl: w,
127
+ fetch: C,
128
+ parseAs: q,
129
+ querySerializer: L,
130
+ bodySerializer: f
131
+ });
132
+ for (const p of h)
133
+ if (p && typeof p == "object" && typeof p.onRequest == "function") {
134
+ const b = yield p.onRequest({
135
+ request: I,
136
+ schemaPath: l,
137
+ params: A,
138
+ options: z,
139
+ id: O
140
+ });
141
+ if (b)
142
+ if (b instanceof t)
143
+ I = b;
144
+ else if (b instanceof Response) {
145
+ m = b;
146
+ break;
147
+ } else
148
+ throw new Error("onRequest: must return new Request() or Response() when modifying the request");
149
+ }
150
+ }
151
+ if (!m) {
152
+ try {
153
+ m = yield C(I, u);
154
+ } catch (p) {
155
+ let b = p;
156
+ if (h.length)
157
+ for (let T = h.length - 1; T >= 0; T--) {
158
+ const P = h[T];
159
+ if (P && typeof P == "object" && typeof P.onError == "function") {
160
+ const H = yield P.onError({
161
+ request: I,
162
+ error: b,
163
+ schemaPath: l,
164
+ params: A,
165
+ options: z,
166
+ id: O
167
+ });
168
+ if (H) {
169
+ if (H instanceof Response) {
170
+ b = void 0, m = H;
171
+ break;
172
+ }
173
+ if (H instanceof Error) {
174
+ b = H;
175
+ continue;
176
+ }
177
+ throw new Error("onError: must return new Response() or instance of Error");
178
+ }
179
+ }
180
+ }
181
+ if (b)
182
+ throw b;
98
183
  }
99
- }
100
- if (!f) {
101
- try {
102
- f = await E(R, u);
103
- } catch (b) {
104
- let h = b;
105
- if (m.length)
106
- for (let j = m.length - 1; j >= 0; j--) {
107
- const x = m[j];
108
- if (x && typeof x == "object" && typeof x.onError == "function") {
109
- const D = await x.onError({
110
- request: R,
111
- error: h,
112
- schemaPath: c,
113
- params: w,
114
- options: T,
115
- id: U
184
+ if (h.length)
185
+ for (let p = h.length - 1; p >= 0; p--) {
186
+ const b = h[p];
187
+ if (b && typeof b == "object" && typeof b.onResponse == "function") {
188
+ const T = yield b.onResponse({
189
+ request: I,
190
+ response: m,
191
+ schemaPath: l,
192
+ params: A,
193
+ options: z,
194
+ id: O
116
195
  });
117
- if (D) {
118
- if (D instanceof Response) {
119
- h = void 0, f = D;
120
- break;
121
- }
122
- if (D instanceof Error) {
123
- h = D;
124
- continue;
125
- }
126
- throw new Error("onError: must return new Response() or instance of Error");
196
+ if (T) {
197
+ if (!(T instanceof Response))
198
+ throw new Error("onResponse: must return new Response() when modifying the response");
199
+ m = T;
127
200
  }
128
201
  }
129
202
  }
130
- if (h)
131
- throw h;
132
203
  }
133
- if (m.length)
134
- for (let b = m.length - 1; b >= 0; b--) {
135
- const h = m[b];
136
- if (h && typeof h == "object" && typeof h.onResponse == "function") {
137
- const j = await h.onResponse({
138
- request: R,
139
- response: f,
140
- schemaPath: c,
141
- params: w,
142
- options: T,
143
- id: U
144
- });
145
- if (j) {
146
- if (!(j instanceof Response))
147
- throw new Error("onResponse: must return new Response() when modifying the response");
148
- f = j;
149
- }
150
- }
151
- }
152
- }
153
- if (f.status === 204 || R.method === "HEAD" || f.headers.get("Content-Length") === "0")
154
- return f.ok ? { data: void 0, response: f } : { error: void 0, response: f };
155
- if (f.ok)
156
- return S === "stream" ? { data: f.body, response: f } : { data: await f[S](), response: f };
157
- let F = await f.text();
158
- try {
159
- F = JSON.parse(F);
160
- } catch {
161
- }
162
- return { error: F, response: f };
204
+ if (m.status === 204 || I.method === "HEAD" || m.headers.get("Content-Length") === "0")
205
+ return m.ok ? { data: void 0, response: m } : { error: void 0, response: m };
206
+ if (m.ok)
207
+ return q === "stream" ? { data: m.body, response: m } : { data: yield m[q](), response: m };
208
+ let _ = yield m.text();
209
+ try {
210
+ _ = JSON.parse(_);
211
+ } catch (p) {
212
+ }
213
+ return { error: _, response: m };
214
+ });
163
215
  }
164
216
  return {
165
- request(c, l, p) {
166
- return y(l, { ...p, method: c.toUpperCase() });
217
+ request(l, a, E) {
218
+ return g(a, R(y({}, E), { method: l.toUpperCase() }));
167
219
  },
168
220
  /** Call a GET endpoint */
169
- GET(c, l) {
170
- return y(c, { ...l, method: "GET" });
221
+ GET(l, a) {
222
+ return g(l, R(y({}, a), { method: "GET" }));
171
223
  },
172
224
  /** Call a PUT endpoint */
173
- PUT(c, l) {
174
- return y(c, { ...l, method: "PUT" });
225
+ PUT(l, a) {
226
+ return g(l, R(y({}, a), { method: "PUT" }));
175
227
  },
176
228
  /** Call a POST endpoint */
177
- POST(c, l) {
178
- return y(c, { ...l, method: "POST" });
229
+ POST(l, a) {
230
+ return g(l, R(y({}, a), { method: "POST" }));
179
231
  },
180
232
  /** Call a DELETE endpoint */
181
- DELETE(c, l) {
182
- return y(c, { ...l, method: "DELETE" });
233
+ DELETE(l, a) {
234
+ return g(l, R(y({}, a), { method: "DELETE" }));
183
235
  },
184
236
  /** Call a OPTIONS endpoint */
185
- OPTIONS(c, l) {
186
- return y(c, { ...l, method: "OPTIONS" });
237
+ OPTIONS(l, a) {
238
+ return g(l, R(y({}, a), { method: "OPTIONS" }));
187
239
  },
188
240
  /** Call a HEAD endpoint */
189
- HEAD(c, l) {
190
- return y(c, { ...l, method: "HEAD" });
241
+ HEAD(l, a) {
242
+ return g(l, R(y({}, a), { method: "HEAD" }));
191
243
  },
192
244
  /** Call a PATCH endpoint */
193
- PATCH(c, l) {
194
- return y(c, { ...l, method: "PATCH" });
245
+ PATCH(l, a) {
246
+ return g(l, R(y({}, a), { method: "PATCH" }));
195
247
  },
196
248
  /** Call a TRACE endpoint */
197
- TRACE(c, l) {
198
- return y(c, { ...l, method: "TRACE" });
249
+ TRACE(l, a) {
250
+ return g(l, R(y({}, a), { method: "TRACE" }));
199
251
  },
200
252
  /** Register middleware */
201
- use(...c) {
202
- for (const l of c)
203
- if (l) {
204
- if (typeof l != "object" || !("onRequest" in l || "onResponse" in l || "onError" in l))
253
+ use(...l) {
254
+ for (const a of l)
255
+ if (a) {
256
+ if (typeof a != "object" || !("onRequest" in a || "onResponse" in a || "onError" in a))
205
257
  throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
206
- m.push(l);
258
+ h.push(a);
207
259
  }
208
260
  },
209
261
  /** Unregister middleware */
210
- eject(...c) {
211
- for (const l of c) {
212
- const p = m.indexOf(l);
213
- p !== -1 && m.splice(p, 1);
262
+ eject(...l) {
263
+ for (const a of l) {
264
+ const E = h.indexOf(a);
265
+ E !== -1 && h.splice(E, 1);
214
266
  }
215
267
  }
216
268
  };
217
269
  }
218
- function O(e, r, t) {
270
+ function N(e, r, t) {
219
271
  if (r == null)
220
272
  return "";
221
273
  if (typeof r == "object")
@@ -224,149 +276,151 @@ function O(e, r, t) {
224
276
  );
225
277
  return `${e}=${(t == null ? void 0 : t.allowReserved) === !0 ? r : encodeURIComponent(r)}`;
226
278
  }
227
- function V(e, r, t) {
279
+ function ae(e, r, t) {
228
280
  if (!r || typeof r != "object")
229
281
  return "";
230
- const s = [], n = {
282
+ const n = [], i = {
231
283
  simple: ",",
232
284
  label: ".",
233
285
  matrix: ";"
234
286
  }[t.style] || "&";
235
287
  if (t.style !== "deepObject" && t.explode === !1) {
236
288
  for (const u in r)
237
- s.push(u, t.allowReserved === !0 ? r[u] : encodeURIComponent(r[u]));
238
- const i = s.join(",");
289
+ n.push(u, t.allowReserved === !0 ? r[u] : encodeURIComponent(r[u]));
290
+ const o = n.join(",");
239
291
  switch (t.style) {
240
292
  case "form":
241
- return `${e}=${i}`;
293
+ return `${e}=${o}`;
242
294
  case "label":
243
- return `.${i}`;
295
+ return `.${o}`;
244
296
  case "matrix":
245
- return `;${e}=${i}`;
297
+ return `;${e}=${o}`;
246
298
  default:
247
- return i;
299
+ return o;
248
300
  }
249
301
  }
250
- for (const i in r) {
251
- const u = t.style === "deepObject" ? `${e}[${i}]` : i;
252
- s.push(O(u, r[i], t));
302
+ for (const o in r) {
303
+ const u = t.style === "deepObject" ? `${e}[${o}]` : o;
304
+ n.push(N(u, r[o], t));
253
305
  }
254
- const o = s.join(n);
255
- return t.style === "label" || t.style === "matrix" ? `${n}${o}` : o;
306
+ const s = n.join(i);
307
+ return t.style === "label" || t.style === "matrix" ? `${i}${s}` : s;
256
308
  }
257
- function X(e, r, t) {
309
+ function ce(e, r, t) {
258
310
  if (!Array.isArray(r))
259
311
  return "";
260
312
  if (t.explode === !1) {
261
- const o = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[t.style] || ",", i = (t.allowReserved === !0 ? r : r.map((u) => encodeURIComponent(u))).join(o);
313
+ const s = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[t.style] || ",", o = (t.allowReserved === !0 ? r : r.map((u) => encodeURIComponent(u))).join(s);
262
314
  switch (t.style) {
263
315
  case "simple":
264
- return i;
316
+ return o;
265
317
  case "label":
266
- return `.${i}`;
318
+ return `.${o}`;
267
319
  case "matrix":
268
- return `;${e}=${i}`;
320
+ return `;${e}=${o}`;
269
321
  default:
270
- return `${e}=${i}`;
322
+ return `${e}=${o}`;
271
323
  }
272
324
  }
273
- const s = { simple: ",", label: ".", matrix: ";" }[t.style] || "&", n = [];
274
- for (const o of r)
275
- t.style === "simple" || t.style === "label" ? n.push(t.allowReserved === !0 ? o : encodeURIComponent(o)) : n.push(O(e, o, t));
276
- return t.style === "label" || t.style === "matrix" ? `${s}${n.join(s)}` : n.join(s);
325
+ const n = { simple: ",", label: ".", matrix: ";" }[t.style] || "&", i = [];
326
+ for (const s of r)
327
+ t.style === "simple" || t.style === "label" ? i.push(t.allowReserved === !0 ? s : encodeURIComponent(s)) : i.push(N(e, s, t));
328
+ return t.style === "label" || t.style === "matrix" ? `${n}${i.join(n)}` : i.join(n);
277
329
  }
278
- function _(e) {
330
+ function ee(e) {
279
331
  return function(t) {
280
- const s = [];
332
+ const n = [];
281
333
  if (t && typeof t == "object")
282
- for (const n in t) {
283
- const o = t[n];
284
- if (o != null) {
285
- if (Array.isArray(o)) {
286
- if (o.length === 0)
334
+ for (const i in t) {
335
+ const s = t[i];
336
+ if (s != null) {
337
+ if (Array.isArray(s)) {
338
+ if (s.length === 0)
287
339
  continue;
288
- s.push(
289
- X(n, o, {
340
+ n.push(
341
+ ce(i, s, R(y({
290
342
  style: "form",
291
- explode: !0,
292
- ...e == null ? void 0 : e.array,
343
+ explode: !0
344
+ }, e == null ? void 0 : e.array), {
293
345
  allowReserved: (e == null ? void 0 : e.allowReserved) || !1
294
- })
346
+ }))
295
347
  );
296
348
  continue;
297
349
  }
298
- if (typeof o == "object") {
299
- s.push(
300
- V(n, o, {
350
+ if (typeof s == "object") {
351
+ n.push(
352
+ ae(i, s, R(y({
301
353
  style: "deepObject",
302
- explode: !0,
303
- ...e == null ? void 0 : e.object,
354
+ explode: !0
355
+ }, e == null ? void 0 : e.object), {
304
356
  allowReserved: (e == null ? void 0 : e.allowReserved) || !1
305
- })
357
+ }))
306
358
  );
307
359
  continue;
308
360
  }
309
- s.push(O(n, o, e));
361
+ n.push(N(i, s, e));
310
362
  }
311
363
  }
312
- return s.join("&");
364
+ return n.join("&");
313
365
  };
314
366
  }
315
- function ae(e, r) {
367
+ function ve(e, r) {
368
+ var n;
316
369
  let t = e;
317
- for (const s of e.match(ne) ?? []) {
318
- let n = s.substring(1, s.length - 1), o = !1, i = "simple";
319
- if (n.endsWith("*") && (o = !0, n = n.substring(0, n.length - 1)), n.startsWith(".") ? (i = "label", n = n.substring(1)) : n.startsWith(";") && (i = "matrix", n = n.substring(1)), !r || r[n] === void 0 || r[n] === null)
370
+ for (const i of (n = e.match(pe)) != null ? n : []) {
371
+ let s = i.substring(1, i.length - 1), o = !1, u = "simple";
372
+ if (s.endsWith("*") && (o = !0, s = s.substring(0, s.length - 1)), s.startsWith(".") ? (u = "label", s = s.substring(1)) : s.startsWith(";") && (u = "matrix", s = s.substring(1)), !r || r[s] === void 0 || r[s] === null)
320
373
  continue;
321
- const u = r[n];
322
- if (Array.isArray(u)) {
323
- t = t.replace(s, X(n, u, { style: i, explode: o }));
374
+ const c = r[s];
375
+ if (Array.isArray(c)) {
376
+ t = t.replace(i, ce(s, c, { style: u, explode: o }));
324
377
  continue;
325
378
  }
326
- if (typeof u == "object") {
327
- t = t.replace(s, V(n, u, { style: i, explode: o }));
379
+ if (typeof c == "object") {
380
+ t = t.replace(i, ae(s, c, { style: u, explode: o }));
328
381
  continue;
329
382
  }
330
- if (i === "matrix") {
331
- t = t.replace(s, `;${O(n, u)}`);
383
+ if (u === "matrix") {
384
+ t = t.replace(i, `;${N(s, c)}`);
332
385
  continue;
333
386
  }
334
- t = t.replace(s, i === "label" ? `.${encodeURIComponent(u)}` : encodeURIComponent(u));
387
+ t = t.replace(i, u === "label" ? `.${encodeURIComponent(c)}` : encodeURIComponent(c));
335
388
  }
336
389
  return t;
337
390
  }
338
- function ce(e, r) {
339
- return e instanceof FormData ? e : r && (r.get instanceof Function ? r.get("Content-Type") ?? r.get("content-type") : r["Content-Type"] ?? r["content-type"]) === "application/x-www-form-urlencoded" ? new URLSearchParams(e).toString() : JSON.stringify(e);
391
+ function Ee(e, r) {
392
+ var t, n;
393
+ return e instanceof FormData ? e : r && (r.get instanceof Function ? (t = r.get("Content-Type")) != null ? t : r.get("content-type") : (n = r["Content-Type"]) != null ? n : r["content-type"]) === "application/x-www-form-urlencoded" ? new URLSearchParams(e).toString() : JSON.stringify(e);
340
394
  }
341
- function le(e, r) {
342
- var n;
395
+ function Ce(e, r) {
396
+ var i, s;
343
397
  let t = `${r.baseUrl}${e}`;
344
- (n = r.params) != null && n.path && (t = ae(t, r.params.path));
345
- let s = r.querySerializer(r.params.query ?? {});
346
- return s.startsWith("?") && (s = s.substring(1)), s && (t += `?${s}`), t;
398
+ (i = r.params) != null && i.path && (t = ve(t, r.params.path));
399
+ let n = r.querySerializer((s = r.params.query) != null ? s : {});
400
+ return n.startsWith("?") && (n = n.substring(1)), n && (t += `?${n}`), t;
347
401
  }
348
- function B(...e) {
402
+ function te(...e) {
349
403
  const r = new Headers();
350
404
  for (const t of e) {
351
405
  if (!t || typeof t != "object")
352
406
  continue;
353
- const s = t instanceof Headers ? t.entries() : Object.entries(t);
354
- for (const [n, o] of s)
355
- if (o === null)
356
- r.delete(n);
357
- else if (Array.isArray(o))
358
- for (const i of o)
359
- r.append(n, i);
360
- else o !== void 0 && r.set(n, o);
407
+ const n = t instanceof Headers ? t.entries() : Object.entries(t);
408
+ for (const [i, s] of n)
409
+ if (s === null)
410
+ r.delete(i);
411
+ else if (Array.isArray(s))
412
+ for (const o of s)
413
+ r.append(i, o);
414
+ else s !== void 0 && r.set(i, s);
361
415
  }
362
416
  return r;
363
417
  }
364
- function W(e) {
418
+ function re(e) {
365
419
  return e.endsWith("/") ? e.substring(0, e.length - 1) : e;
366
420
  }
367
- const ue = {
421
+ const Ae = {
368
422
  baseUrl: "http://localhost:3200"
369
- }, fe = {
423
+ }, je = {
370
424
  development: {
371
425
  baseUrl: "http://localhost:3200"
372
426
  },
@@ -378,152 +432,156 @@ const ue = {
378
432
  // baseUrl: import.meta.env.VITE_API_BASE_URL || "https://api.dismissible.io",
379
433
  baseUrl: "https://api.dismissible.io"
380
434
  }
381
- }, de = () => fe["production"] || ue, M = (e, r, t) => {
435
+ }, Ie = () => je["production"] || Ae, ne = (e, r, t) => {
382
436
  try {
383
- const s = `${r}_${e}`, n = localStorage.getItem(s);
384
- if (!n) return null;
385
- const { data: o, timestamp: i } = JSON.parse(n);
386
- return t && Date.now() - i > t ? (localStorage.removeItem(s), null) : o;
387
- } catch {
437
+ const n = `${r}_${e}`, i = localStorage.getItem(n);
438
+ if (!i) return null;
439
+ const { data: s, timestamp: o } = JSON.parse(i);
440
+ return t && Date.now() - o > t ? (localStorage.removeItem(n), null) : s;
441
+ } catch (n) {
388
442
  return null;
389
443
  }
390
- }, G = (e, r, t) => {
444
+ }, se = (e, r, t) => {
391
445
  try {
392
- const s = `${t}_${e}`, n = {
446
+ const n = `${t}_${e}`, i = {
393
447
  data: r,
394
448
  timestamp: Date.now()
395
449
  };
396
- localStorage.setItem(s, JSON.stringify(n));
397
- } catch (s) {
398
- console.warn("Failed to cache dismissible item:", s);
450
+ localStorage.setItem(n, JSON.stringify(i));
451
+ } catch (n) {
452
+ console.warn("Failed to cache dismissible item:", n);
399
453
  }
400
- }, K = (e, r) => {
454
+ }, ie = (e, r) => {
401
455
  try {
402
456
  const t = `${r}_${e}`;
403
457
  localStorage.removeItem(t);
404
458
  } catch (t) {
405
459
  console.warn("Failed to remove cached dismissible item:", t);
406
460
  }
407
- }, Y = te(
461
+ }, le = ye(
408
462
  null
409
- ), me = () => re(Y), he = "dismissible", ye = (e, r = {}) => {
463
+ ), Se = () => be(le), $e = "dismissible", De = (e, r = {}) => {
464
+ var U;
410
465
  const {
411
466
  initialData: t,
412
- enableCache: s = !0,
413
- cachePrefix: n = he,
414
- cacheExpiration: o
415
- } = r, i = me(), u = N(() => {
416
- const a = de(), g = (i == null ? void 0 : i.baseUrl) || a.baseUrl, $ = (i == null ? void 0 : i.getAuthHeaders()) || {};
417
- return oe({
418
- baseUrl: g,
419
- headers: {
420
- ...$
421
- }
467
+ enableCache: n = !0,
468
+ cachePrefix: i = $e,
469
+ cacheExpiration: s
470
+ } = r, o = Se(), u = B(() => {
471
+ const f = Ie(), d = (o == null ? void 0 : o.baseUrl) || f.baseUrl;
472
+ return Re({
473
+ baseUrl: d,
474
+ headers: {}
422
475
  });
423
- }, [i]), d = N(() => !!(i != null && i.jwt) ? `${e}-auth` : e, [e, i == null ? void 0 : i.jwt]), m = P({
424
- enableCache: s,
425
- cachePrefix: n,
426
- cacheExpiration: o
427
- }), y = P(e), c = P(d), [l, p] = q(!1), [E, v] = q(null), [C, w] = q(() => {
476
+ }, [o]), c = B(() => !!(o != null && o.jwt) ? `${e}-auth` : e, [e, o == null ? void 0 : o.jwt]), h = M({
477
+ enableCache: n,
478
+ cachePrefix: i,
479
+ cacheExpiration: s
480
+ }), g = M(e), j = M(c), [l, a] = F(!1), [E, C] = F(null), [$, D] = F(() => {
428
481
  if (t) return t;
429
- if (s) {
430
- const a = M(
431
- d,
432
- n,
433
- o
482
+ if (n) {
483
+ const f = ne(
484
+ c,
485
+ i,
486
+ s
434
487
  );
435
- if (a) return a;
488
+ if (f) return f;
436
489
  }
437
- }), S = L(async () => {
438
- if (s) {
439
- const a = M(
440
- d,
441
- n,
442
- o
490
+ }), A = Y(() => S(void 0, null, function* () {
491
+ var f;
492
+ if (n) {
493
+ const d = ne(
494
+ c,
495
+ i,
496
+ s
443
497
  );
444
- if (a != null && a.dismissedAt) {
445
- w(a), p(!1);
498
+ if (d != null && d.dismissedAt) {
499
+ D(d), a(!1);
446
500
  return;
447
501
  }
448
502
  }
449
- p(!0), v(null);
503
+ a(!0), C(null);
450
504
  try {
451
- const { data: a, error: g } = await u.GET(
505
+ const d = o != null && o.getAuthHeaders ? yield o.getAuthHeaders() : {}, { data: v, error: w } = yield u.GET(
452
506
  "/v1/dismissible/{itemId}",
453
507
  {
454
508
  params: {
455
509
  path: {
456
510
  itemId: e
457
511
  }
458
- }
512
+ },
513
+ headers: d
459
514
  }
460
515
  );
461
- if (g)
516
+ if (w)
462
517
  throw new Error(
463
- g.error.message || "Failed to fetch dismissible item"
518
+ ((f = w == null ? void 0 : w.error) == null ? void 0 : f.message) || "Failed to fetch dismissible item"
464
519
  );
465
- w(a.data), s && a.data && G(d, a.data, n);
466
- } catch (a) {
467
- v(
468
- a instanceof Error ? a : new Error("Unknown error occurred")
520
+ D(v.data), n && v.data && se(c, v.data, i);
521
+ } catch (d) {
522
+ C(
523
+ d instanceof Error ? d : new Error("Unknown error occurred")
469
524
  );
470
525
  } finally {
471
- p(!1);
526
+ a(!1);
472
527
  }
473
- }, [
528
+ }), [
474
529
  e,
475
- d,
476
- s,
530
+ c,
477
531
  n,
478
- o,
479
- u
532
+ i,
533
+ s,
534
+ u,
535
+ o
480
536
  ]);
481
- J(() => {
482
- const a = y.current !== e, g = c.current !== d;
483
- a || g ? (y.current = e, c.current = d, S()) : t || S();
484
- }, [e, d, t]), J(() => {
485
- const a = m.current;
486
- (a.enableCache !== s || a.cachePrefix !== n || a.cacheExpiration !== o) && (a.cachePrefix !== n && K(d, a.cachePrefix), !s && a.enableCache && K(d, n), m.current = {
487
- enableCache: s,
488
- cachePrefix: n,
489
- cacheExpiration: o
490
- }, S());
491
- }, [s, n, o, d]);
492
- const A = L(async () => {
493
- v(null);
537
+ Z(() => {
538
+ const f = g.current !== e, d = j.current !== c;
539
+ f || d ? (g.current = e, j.current = c, A()) : t || A();
540
+ }, [e, c, t]), Z(() => {
541
+ const f = h.current;
542
+ (f.enableCache !== n || f.cachePrefix !== i || f.cacheExpiration !== s) && (f.cachePrefix !== i && ie(c, f.cachePrefix), !n && f.enableCache && ie(c, i), h.current = {
543
+ enableCache: n,
544
+ cachePrefix: i,
545
+ cacheExpiration: s
546
+ }, A());
547
+ }, [n, i, s, c]);
548
+ const q = Y(() => S(void 0, null, function* () {
549
+ var f;
550
+ C(null);
494
551
  try {
495
- const { data: a, error: g } = await u.DELETE(
552
+ const d = o != null && o.getAuthHeaders ? yield o.getAuthHeaders() : {}, { data: v, error: w } = yield u.DELETE(
496
553
  "/v1/dismissible/{itemId}",
497
554
  {
498
555
  params: {
499
556
  path: {
500
557
  itemId: e
501
558
  }
502
- }
559
+ },
560
+ headers: d
503
561
  }
504
562
  );
505
- if (g)
506
- throw new Error(g.error.message || "Failed to dismiss item");
507
- w(a.data), s && a.data && G(d, a.data, n);
508
- } catch (a) {
509
- throw v(
510
- a instanceof Error ? a : new Error("Failed to dismiss item")
511
- ), a;
563
+ if (w)
564
+ throw new Error(((f = w == null ? void 0 : w.error) == null ? void 0 : f.message) || "Failed to dismiss item");
565
+ D(v.data), n && v.data && se(c, v.data, i);
566
+ } catch (d) {
567
+ throw C(
568
+ d instanceof Error ? d : new Error("Failed to dismiss item")
569
+ ), d;
512
570
  }
513
- }, [d, s, n, u]);
571
+ }), [c, n, i, u, o]);
514
572
  return {
515
- dismissedOn: (C == null ? void 0 : C.dismissedAt) ?? null,
516
- dismiss: A,
573
+ dismissedOn: (U = $ == null ? void 0 : $.dismissedAt) != null ? U : null,
574
+ dismiss: q,
517
575
  isLoading: l,
518
576
  error: E,
519
- item: C
577
+ item: $
520
578
  };
521
- }, be = () => /* @__PURE__ */ I("div", { className: "dismissible-loading", "aria-live": "polite", children: "Loading..." }), pe = ({
579
+ }, Ue = () => /* @__PURE__ */ x("div", { className: "dismissible-loading", "aria-live": "polite", children: "Loading..." }), Te = ({
522
580
  error: e
523
- }) => /* @__PURE__ */ Q("div", { className: "dismissible-error", role: "alert", children: [
581
+ }) => /* @__PURE__ */ oe("div", { className: "dismissible-error", role: "alert", children: [
524
582
  "Error loading dismissible item: ",
525
583
  e.message
526
- ] }), ge = ({ id: e, onDismiss: r, ariaLabel: t }) => /* @__PURE__ */ I(
584
+ ] }), xe = ({ id: e, onDismiss: r, ariaLabel: t }) => /* @__PURE__ */ x(
527
585
  "button",
528
586
  {
529
587
  id: e,
@@ -533,78 +591,82 @@ const ue = {
533
591
  type: "button",
534
592
  children: "×"
535
593
  }
536
- ), Ce = ({
594
+ ), ke = ({
537
595
  id: e,
538
596
  children: r,
539
597
  onDismiss: t,
540
- LoadingComponent: s = be,
541
- ErrorComponent: n = pe,
542
- DismissButtonComponent: o = ge,
543
- enableCache: i,
598
+ LoadingComponent: n = Ue,
599
+ ErrorComponent: i = Te,
600
+ DismissButtonComponent: s = xe,
601
+ enableCache: o,
544
602
  cachePrefix: u,
545
- cacheExpiration: d
603
+ cacheExpiration: c,
604
+ ignoreErrors: h = !1
546
605
  }) => {
547
- const { dismissedOn: m, isLoading: y, error: c, dismiss: l } = ye(e, {
548
- enableCache: i,
606
+ const { dismissedOn: g, isLoading: j, error: l, dismiss: a } = De(e, {
607
+ enableCache: o,
549
608
  cachePrefix: u,
550
- cacheExpiration: d
551
- }), [p, E] = q(!1), v = async () => {
552
- E(!0);
609
+ cacheExpiration: c
610
+ }), [E, C] = F(!1), $ = () => S(void 0, null, function* () {
611
+ C(!0);
553
612
  try {
554
- await l(), t == null || t();
555
- } catch {
556
- E(!1);
613
+ yield a(), t == null || t();
614
+ } catch (D) {
615
+ C(!1);
557
616
  }
558
- };
559
- return y && s ? /* @__PURE__ */ I(s, { id: e }) : y && !s ? null : c && n ? /* @__PURE__ */ I(n, { id: e, error: c }) : m || p ? null : /* @__PURE__ */ Q("div", { className: "dismissible-container", children: [
560
- /* @__PURE__ */ I("div", { className: "dismissible-content", children: r }),
561
- o ? /* @__PURE__ */ I(
562
- o,
617
+ });
618
+ return j && n ? /* @__PURE__ */ x(n, { id: e }) : j && !n ? null : l && i && !h ? /* @__PURE__ */ x(i, { id: e, error: l }) : g || E ? null : /* @__PURE__ */ oe("div", { className: "dismissible-container", children: [
619
+ /* @__PURE__ */ x("div", { className: "dismissible-content", children: r }),
620
+ s ? /* @__PURE__ */ x(
621
+ s,
563
622
  {
564
623
  id: e,
565
- onDismiss: v,
624
+ onDismiss: $,
566
625
  ariaLabel: `Dismiss ${e}`
567
626
  }
568
627
  ) : null
569
628
  ] });
570
- }, we = (e) => {
629
+ }, qe = (e) => S(void 0, null, function* () {
571
630
  if (typeof e == "function")
572
631
  try {
573
- return e();
632
+ const r = e();
633
+ return yield Promise.resolve(r);
574
634
  } catch (r) {
575
635
  console.warn("Failed to resolve JWT from function:", r);
576
636
  return;
577
637
  }
578
638
  return e;
579
- }, Re = (e) => {
580
- const r = we(e);
639
+ }), He = (e) => S(void 0, null, function* () {
640
+ const r = yield qe(e);
581
641
  return r ? { Authorization: `Bearer ${r}` } : {};
582
- }, Se = (e) => {
642
+ }), Fe = (e) => {
583
643
  const r = e.split(".");
584
644
  return r.length === 3 && r.every((t) => t.length > 0);
585
- }, je = ({
645
+ }, Ne = ({
586
646
  jwt: e,
587
647
  baseUrl: r,
588
648
  children: t
589
649
  }) => {
590
- const s = N(
650
+ const n = B(
591
651
  () => ({
592
652
  jwt: e,
593
653
  baseUrl: r,
594
- getAuthHeaders: () => Re(e)
654
+ getAuthHeaders: () => S(void 0, null, function* () {
655
+ return yield He(e);
656
+ })
595
657
  }),
596
658
  [e, r]
597
659
  );
598
- return /* @__PURE__ */ I(Y.Provider, { value: s, children: t });
599
- }, Ie = "0.1.0";
660
+ return /* @__PURE__ */ x(le.Provider, { value: n, children: t });
661
+ }, Le = "0.3.0";
600
662
  export {
601
- Ce as Dismissible,
602
- Y as DismissibleContext,
603
- je as DismissibleProvider,
604
- Ie as VERSION,
605
- Re as getAuthHeaders,
606
- Se as isValidJwtFormat,
607
- we as resolveJwt,
608
- me as useDismissibleContext,
609
- ye as useDismissibleItem
663
+ ke as Dismissible,
664
+ le as DismissibleContext,
665
+ Ne as DismissibleProvider,
666
+ Le as VERSION,
667
+ He as getAuthHeaders,
668
+ Fe as isValidJwtFormat,
669
+ qe as resolveJwt,
670
+ Se as useDismissibleContext,
671
+ De as useDismissibleItem
610
672
  };
@@ -1 +1 @@
1
- (function(m,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],w):(m=typeof globalThis<"u"?globalThis:m||self,w(m.DismissibleClient={},m.React.jsxRuntime,m.React))})(this,function(m,w,h){"use strict";const Z=/\{[^{}]+\}/g,ee=()=>{var e,r;return typeof process=="object"&&Number.parseInt((r=(e=process==null?void 0:process.versions)==null?void 0:e.node)==null?void 0:r.substring(0,2))>=18&&process.versions.undici};function te(){return Math.random().toString(36).slice(2,11)}function re(e){let{baseUrl:r="",Request:t=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:s,bodySerializer:o,headers:i,requestInitExt:u=void 0,...d}={...e};u=ee()?u:void 0,r=B(r);const b=[];async function p(l,c){const{baseUrl:v,fetch:S=n,Request:j=t,headers:I,params:C={},parseAs:D="json",querySerializer:$,bodySerializer:a=o??ne,body:E,...T}=c||{};let P=r;v&&(P=B(v)??r);let k=typeof s=="function"?s:M(s);$&&(k=typeof $=="function"?$:M({...typeof s=="object"?s:{},...$}));const F=E===void 0?void 0:a(E,_(i,I,C.header)),pe=_(F===void 0||F instanceof FormData?{}:{"Content-Type":"application/json"},i,I,C.header),ge={redirect:"follow",...d,...T,body:F,headers:pe};let O,x,R=new t(ie(l,{baseUrl:P,params:C,querySerializer:k}),ge),f;for(const g in T)g in R||(R[g]=T[g]);if(b.length){O=te(),x=Object.freeze({baseUrl:P,fetch:S,parseAs:D,querySerializer:k,bodySerializer:a});for(const g of b)if(g&&typeof g=="object"&&typeof g.onRequest=="function"){const y=await g.onRequest({request:R,schemaPath:l,params:C,options:x,id:O});if(y)if(y instanceof t)R=y;else if(y instanceof Response){f=y;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!f){try{f=await S(R,u)}catch(g){let y=g;if(b.length)for(let A=b.length-1;A>=0;A--){const z=b[A];if(z&&typeof z=="object"&&typeof z.onError=="function"){const U=await z.onError({request:R,error:y,schemaPath:l,params:C,options:x,id:O});if(U){if(U instanceof Response){y=void 0,f=U;break}if(U instanceof Error){y=U;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(y)throw y}if(b.length)for(let g=b.length-1;g>=0;g--){const y=b[g];if(y&&typeof y=="object"&&typeof y.onResponse=="function"){const A=await y.onResponse({request:R,response:f,schemaPath:l,params:C,options:x,id:O});if(A){if(!(A instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");f=A}}}}if(f.status===204||R.method==="HEAD"||f.headers.get("Content-Length")==="0")return f.ok?{data:void 0,response:f}:{error:void 0,response:f};if(f.ok)return D==="stream"?{data:f.body,response:f}:{data:await f[D](),response:f};let N=await f.text();try{N=JSON.parse(N)}catch{}return{error:N,response:f}}return{request(l,c,v){return p(c,{...v,method:l.toUpperCase()})},GET(l,c){return p(l,{...c,method:"GET"})},PUT(l,c){return p(l,{...c,method:"PUT"})},POST(l,c){return p(l,{...c,method:"POST"})},DELETE(l,c){return p(l,{...c,method:"DELETE"})},OPTIONS(l,c){return p(l,{...c,method:"OPTIONS"})},HEAD(l,c){return p(l,{...c,method:"HEAD"})},PATCH(l,c){return p(l,{...c,method:"PATCH"})},TRACE(l,c){return p(l,{...c,method:"TRACE"})},use(...l){for(const c of l)if(c){if(typeof c!="object"||!("onRequest"in c||"onResponse"in c||"onError"in c))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");b.push(c)}},eject(...l){for(const c of l){const v=b.indexOf(c);v!==-1&&b.splice(v,1)}}}}function q(e,r,t){if(r==null)return"";if(typeof r=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${(t==null?void 0:t.allowReserved)===!0?r:encodeURIComponent(r)}`}function L(e,r,t){if(!r||typeof r!="object")return"";const n=[],s={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const u in r)n.push(u,t.allowReserved===!0?r[u]:encodeURIComponent(r[u]));const i=n.join(",");switch(t.style){case"form":return`${e}=${i}`;case"label":return`.${i}`;case"matrix":return`;${e}=${i}`;default:return i}}for(const i in r){const u=t.style==="deepObject"?`${e}[${i}]`:i;n.push(q(u,r[i],t))}const o=n.join(s);return t.style==="label"||t.style==="matrix"?`${s}${o}`:o}function J(e,r,t){if(!Array.isArray(r))return"";if(t.explode===!1){const o={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",i=(t.allowReserved===!0?r:r.map(u=>encodeURIComponent(u))).join(o);switch(t.style){case"simple":return i;case"label":return`.${i}`;case"matrix":return`;${e}=${i}`;default:return`${e}=${i}`}}const n={simple:",",label:".",matrix:";"}[t.style]||"&",s=[];for(const o of r)t.style==="simple"||t.style==="label"?s.push(t.allowReserved===!0?o:encodeURIComponent(o)):s.push(q(e,o,t));return t.style==="label"||t.style==="matrix"?`${n}${s.join(n)}`:s.join(n)}function M(e){return function(t){const n=[];if(t&&typeof t=="object")for(const s in t){const o=t[s];if(o!=null){if(Array.isArray(o)){if(o.length===0)continue;n.push(J(s,o,{style:"form",explode:!0,...e==null?void 0:e.array,allowReserved:(e==null?void 0:e.allowReserved)||!1}));continue}if(typeof o=="object"){n.push(L(s,o,{style:"deepObject",explode:!0,...e==null?void 0:e.object,allowReserved:(e==null?void 0:e.allowReserved)||!1}));continue}n.push(q(s,o,e))}}return n.join("&")}}function se(e,r){let t=e;for(const n of e.match(Z)??[]){let s=n.substring(1,n.length-1),o=!1,i="simple";if(s.endsWith("*")&&(o=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(i="label",s=s.substring(1)):s.startsWith(";")&&(i="matrix",s=s.substring(1)),!r||r[s]===void 0||r[s]===null)continue;const u=r[s];if(Array.isArray(u)){t=t.replace(n,J(s,u,{style:i,explode:o}));continue}if(typeof u=="object"){t=t.replace(n,L(s,u,{style:i,explode:o}));continue}if(i==="matrix"){t=t.replace(n,`;${q(s,u)}`);continue}t=t.replace(n,i==="label"?`.${encodeURIComponent(u)}`:encodeURIComponent(u))}return t}function ne(e,r){return e instanceof FormData?e:r&&(r.get instanceof Function?r.get("Content-Type")??r.get("content-type"):r["Content-Type"]??r["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(e).toString():JSON.stringify(e)}function ie(e,r){var s;let t=`${r.baseUrl}${e}`;(s=r.params)!=null&&s.path&&(t=se(t,r.params.path));let n=r.querySerializer(r.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(t+=`?${n}`),t}function _(...e){const r=new Headers;for(const t of e){if(!t||typeof t!="object")continue;const n=t instanceof Headers?t.entries():Object.entries(t);for(const[s,o]of n)if(o===null)r.delete(s);else if(Array.isArray(o))for(const i of o)r.append(s,i);else o!==void 0&&r.set(s,o)}return r}function B(e){return e.endsWith("/")?e.substring(0,e.length-1):e}const oe={baseUrl:"http://localhost:3200"},ae={development:{baseUrl:"http://localhost:3200"},staging:{baseUrl:"https://api.staging.dismissible.io"},production:{baseUrl:"https://api.dismissible.io"}},le=()=>ae["production"]||oe,W=(e,r,t)=>{try{const n=`${r}_${e}`,s=localStorage.getItem(n);if(!s)return null;const{data:o,timestamp:i}=JSON.parse(s);return t&&Date.now()-i>t?(localStorage.removeItem(n),null):o}catch{return null}},V=(e,r,t)=>{try{const n=`${t}_${e}`,s={data:r,timestamp:Date.now()};localStorage.setItem(n,JSON.stringify(s))}catch(n){console.warn("Failed to cache dismissible item:",n)}},G=(e,r)=>{try{const t=`${r}_${e}`;localStorage.removeItem(t)}catch(t){console.warn("Failed to remove cached dismissible item:",t)}},H=h.createContext(null),K=()=>h.useContext(H),ce="dismissible",Q=(e,r={})=>{const{initialData:t,enableCache:n=!0,cachePrefix:s=ce,cacheExpiration:o}=r,i=K(),u=h.useMemo(()=>{const a=le(),E=(i==null?void 0:i.baseUrl)||a.baseUrl,T=(i==null?void 0:i.getAuthHeaders())||{};return re({baseUrl:E,headers:{...T}})},[i]),d=h.useMemo(()=>!!(i!=null&&i.jwt)?`${e}-auth`:e,[e,i==null?void 0:i.jwt]),b=h.useRef({enableCache:n,cachePrefix:s,cacheExpiration:o}),p=h.useRef(e),l=h.useRef(d),[c,v]=h.useState(!1),[S,j]=h.useState(null),[I,C]=h.useState(()=>{if(t)return t;if(n){const a=W(d,s,o);if(a)return a}}),D=h.useCallback(async()=>{if(n){const a=W(d,s,o);if(a!=null&&a.dismissedAt){C(a),v(!1);return}}v(!0),j(null);try{const{data:a,error:E}=await u.GET("/v1/dismissible/{itemId}",{params:{path:{itemId:e}}});if(E)throw new Error(E.error.message||"Failed to fetch dismissible item");C(a.data),n&&a.data&&V(d,a.data,s)}catch(a){j(a instanceof Error?a:new Error("Unknown error occurred"))}finally{v(!1)}},[e,d,n,s,o,u]);h.useEffect(()=>{const a=p.current!==e,E=l.current!==d;a||E?(p.current=e,l.current=d,D()):t||D()},[e,d,t]),h.useEffect(()=>{const a=b.current;(a.enableCache!==n||a.cachePrefix!==s||a.cacheExpiration!==o)&&(a.cachePrefix!==s&&G(d,a.cachePrefix),!n&&a.enableCache&&G(d,s),b.current={enableCache:n,cachePrefix:s,cacheExpiration:o},D())},[n,s,o,d]);const $=h.useCallback(async()=>{j(null);try{const{data:a,error:E}=await u.DELETE("/v1/dismissible/{itemId}",{params:{path:{itemId:e}}});if(E)throw new Error(E.error.message||"Failed to dismiss item");C(a.data),n&&a.data&&V(d,a.data,s)}catch(a){throw j(a instanceof Error?a:new Error("Failed to dismiss item")),a}},[d,n,s,u]);return{dismissedOn:(I==null?void 0:I.dismissedAt)??null,dismiss:$,isLoading:c,error:S,item:I}},ue=()=>w.jsx("div",{className:"dismissible-loading","aria-live":"polite",children:"Loading..."}),fe=({error:e})=>w.jsxs("div",{className:"dismissible-error",role:"alert",children:["Error loading dismissible item: ",e.message]}),de=({id:e,onDismiss:r,ariaLabel:t})=>w.jsx("button",{id:e,className:"dismissible-button",onClick:r,"aria-label":t,type:"button",children:"×"}),me=({id:e,children:r,onDismiss:t,LoadingComponent:n=ue,ErrorComponent:s=fe,DismissButtonComponent:o=de,enableCache:i,cachePrefix:u,cacheExpiration:d})=>{const{dismissedOn:b,isLoading:p,error:l,dismiss:c}=Q(e,{enableCache:i,cachePrefix:u,cacheExpiration:d}),[v,S]=h.useState(!1),j=async()=>{S(!0);try{await c(),t==null||t()}catch{S(!1)}};return p&&n?w.jsx(n,{id:e}):p&&!n?null:l&&s?w.jsx(s,{id:e,error:l}):b||v?null:w.jsxs("div",{className:"dismissible-container",children:[w.jsx("div",{className:"dismissible-content",children:r}),o?w.jsx(o,{id:e,onDismiss:j,ariaLabel:`Dismiss ${e}`}):null]})},X=e=>{if(typeof e=="function")try{return e()}catch(r){console.warn("Failed to resolve JWT from function:",r);return}return e},Y=e=>{const r=X(e);return r?{Authorization:`Bearer ${r}`}:{}},he=e=>{const r=e.split(".");return r.length===3&&r.every(t=>t.length>0)},be=({jwt:e,baseUrl:r,children:t})=>{const n=h.useMemo(()=>({jwt:e,baseUrl:r,getAuthHeaders:()=>Y(e)}),[e,r]);return w.jsx(H.Provider,{value:n,children:t})},ye="0.1.0";m.Dismissible=me,m.DismissibleContext=H,m.DismissibleProvider=be,m.VERSION=ye,m.getAuthHeaders=Y,m.isValidJwtFormat=he,m.resolveJwt=X,m.useDismissibleContext=K,m.useDismissibleItem=Q,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
1
+ (function(a,u){typeof exports=="object"&&typeof module!="undefined"?u(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],u):(a=typeof globalThis!="undefined"?globalThis:a||self,u(a.DismissibleClient={},a.React.jsxRuntime,a.React))})(this,function(a,u,l){"use strict";var Te=Object.defineProperty,Ue=Object.defineProperties;var qe=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var de=Object.prototype.hasOwnProperty,he=Object.prototype.propertyIsEnumerable;var fe=(a,u,l)=>u in a?Te(a,u,{enumerable:!0,configurable:!0,writable:!0,value:l}):a[u]=l,p=(a,u)=>{for(var l in u||(u={}))de.call(u,l)&&fe(a,l,u[l]);if(W)for(var l of W(u))he.call(u,l)&&fe(a,l,u[l]);return a},S=(a,u)=>Ue(a,qe(u));var Y=(a,u)=>{var l={};for(var C in a)de.call(a,C)&&u.indexOf(C)<0&&(l[C]=a[C]);if(a!=null&&W)for(var C of W(a))u.indexOf(C)<0&&he.call(a,C)&&(l[C]=a[C]);return l};var O=(a,u,l)=>new Promise((C,L)=>{var V=I=>{try{T(l.next(I))}catch(k){L(k)}},B=I=>{try{T(l.throw(I))}catch(k){L(k)}},T=I=>I.done?C(I.value):Promise.resolve(I.value).then(V,B);T((l=l.apply(a,u)).next())});const C=/\{[^{}]+\}/g,L=()=>{var e,r;return typeof process=="object"&&Number.parseInt((r=(e=process==null?void 0:process.versions)==null?void 0:e.node)==null?void 0:r.substring(0,2))>=18&&process.versions.undici};function V(){return Math.random().toString(36).slice(2,11)}function B(e){let U=p({},e),{baseUrl:r="",Request:t=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:s,headers:o,requestInitExt:d=void 0}=U,h=Y(U,["baseUrl","Request","fetch","querySerializer","bodySerializer","headers","requestInitExt"]);d=L()?d:void 0,r=te(r);const g=[];function E(f,c){return O(this,null,function*(){var ue;const ce=c||{},{baseUrl:A,fetch:D=n,Request:H=t,headers:x,params:$={},parseAs:F="json",querySerializer:z,bodySerializer:m=s!=null?s:ye,body:y}=ce,j=Y(ce,["baseUrl","fetch","Request","headers","params","parseAs","querySerializer","bodySerializer","body"]);let R=r;A&&(R=(ue=te(A))!=null?ue:r);let K=typeof i=="function"?i:Z(i);z&&(K=typeof z=="function"?z:Z(p(p({},typeof i=="object"?i:{}),z)));const Q=y===void 0?void 0:m(y,ee(o,x,$.header)),De=ee(Q===void 0||Q instanceof FormData?{}:{"Content-Type":"application/json"},o,x,$.header),$e=S(p(p({redirect:"follow"},h),j),{body:Q,headers:De});let J,M,q=new t(be(f,{baseUrl:R,params:$,querySerializer:K}),$e),b;for(const v in j)v in q||(q[v]=j[v]);if(g.length){J=V(),M=Object.freeze({baseUrl:R,fetch:D,parseAs:F,querySerializer:K,bodySerializer:m});for(const v of g)if(v&&typeof v=="object"&&typeof v.onRequest=="function"){const w=yield v.onRequest({request:q,schemaPath:f,params:$,options:M,id:J});if(w)if(w instanceof t)q=w;else if(w instanceof Response){b=w;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!b){try{b=yield D(q,d)}catch(v){let w=v;if(g.length)for(let P=g.length-1;P>=0;P--){const _=g[P];if(_&&typeof _=="object"&&typeof _.onError=="function"){const N=yield _.onError({request:q,error:w,schemaPath:f,params:$,options:M,id:J});if(N){if(N instanceof Response){w=void 0,b=N;break}if(N instanceof Error){w=N;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(w)throw w}if(g.length)for(let v=g.length-1;v>=0;v--){const w=g[v];if(w&&typeof w=="object"&&typeof w.onResponse=="function"){const P=yield w.onResponse({request:q,response:b,schemaPath:f,params:$,options:M,id:J});if(P){if(!(P instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");b=P}}}}if(b.status===204||q.method==="HEAD"||b.headers.get("Content-Length")==="0")return b.ok?{data:void 0,response:b}:{error:void 0,response:b};if(b.ok)return F==="stream"?{data:b.body,response:b}:{data:yield b[F](),response:b};let X=yield b.text();try{X=JSON.parse(X)}catch(v){}return{error:X,response:b}})}return{request(f,c,A){return E(c,S(p({},A),{method:f.toUpperCase()}))},GET(f,c){return E(f,S(p({},c),{method:"GET"}))},PUT(f,c){return E(f,S(p({},c),{method:"PUT"}))},POST(f,c){return E(f,S(p({},c),{method:"POST"}))},DELETE(f,c){return E(f,S(p({},c),{method:"DELETE"}))},OPTIONS(f,c){return E(f,S(p({},c),{method:"OPTIONS"}))},HEAD(f,c){return E(f,S(p({},c),{method:"HEAD"}))},PATCH(f,c){return E(f,S(p({},c),{method:"PATCH"}))},TRACE(f,c){return E(f,S(p({},c),{method:"TRACE"}))},use(...f){for(const c of f)if(c){if(typeof c!="object"||!("onRequest"in c||"onResponse"in c||"onError"in c))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");g.push(c)}},eject(...f){for(const c of f){const A=g.indexOf(c);A!==-1&&g.splice(A,1)}}}}function T(e,r,t){if(r==null)return"";if(typeof r=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${(t==null?void 0:t.allowReserved)===!0?r:encodeURIComponent(r)}`}function I(e,r,t){if(!r||typeof r!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const d in r)n.push(d,t.allowReserved===!0?r[d]:encodeURIComponent(r[d]));const o=n.join(",");switch(t.style){case"form":return`${e}=${o}`;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return o}}for(const o in r){const d=t.style==="deepObject"?`${e}[${o}]`:o;n.push(T(d,r[o],t))}const s=n.join(i);return t.style==="label"||t.style==="matrix"?`${i}${s}`:s}function k(e,r,t){if(!Array.isArray(r))return"";if(t.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",o=(t.allowReserved===!0?r:r.map(d=>encodeURIComponent(d))).join(s);switch(t.style){case"simple":return o;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return`${e}=${o}`}}const n={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const s of r)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?s:encodeURIComponent(s)):i.push(T(e,s,t));return t.style==="label"||t.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Z(e){return function(t){const n=[];if(t&&typeof t=="object")for(const i in t){const s=t[i];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;n.push(k(i,s,S(p({style:"form",explode:!0},e==null?void 0:e.array),{allowReserved:(e==null?void 0:e.allowReserved)||!1})));continue}if(typeof s=="object"){n.push(I(i,s,S(p({style:"deepObject",explode:!0},e==null?void 0:e.object),{allowReserved:(e==null?void 0:e.allowReserved)||!1})));continue}n.push(T(i,s,e))}}return n.join("&")}}function me(e,r){var n;let t=e;for(const i of(n=e.match(C))!=null?n:[]){let s=i.substring(1,i.length-1),o=!1,d="simple";if(s.endsWith("*")&&(o=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(d="label",s=s.substring(1)):s.startsWith(";")&&(d="matrix",s=s.substring(1)),!r||r[s]===void 0||r[s]===null)continue;const h=r[s];if(Array.isArray(h)){t=t.replace(i,k(s,h,{style:d,explode:o}));continue}if(typeof h=="object"){t=t.replace(i,I(s,h,{style:d,explode:o}));continue}if(d==="matrix"){t=t.replace(i,`;${T(s,h)}`);continue}t=t.replace(i,d==="label"?`.${encodeURIComponent(h)}`:encodeURIComponent(h))}return t}function ye(e,r){var t,n;return e instanceof FormData?e:r&&(r.get instanceof Function?(t=r.get("Content-Type"))!=null?t:r.get("content-type"):(n=r["Content-Type"])!=null?n:r["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(e).toString():JSON.stringify(e)}function be(e,r){var i,s;let t=`${r.baseUrl}${e}`;(i=r.params)!=null&&i.path&&(t=me(t,r.params.path));let n=r.querySerializer((s=r.params.query)!=null?s:{});return n.startsWith("?")&&(n=n.substring(1)),n&&(t+=`?${n}`),t}function ee(...e){const r=new Headers;for(const t of e){if(!t||typeof t!="object")continue;const n=t instanceof Headers?t.entries():Object.entries(t);for(const[i,s]of n)if(s===null)r.delete(i);else if(Array.isArray(s))for(const o of s)r.append(i,o);else s!==void 0&&r.set(i,s)}return r}function te(e){return e.endsWith("/")?e.substring(0,e.length-1):e}const pe={baseUrl:"http://localhost:3200"},ge={development:{baseUrl:"http://localhost:3200"},staging:{baseUrl:"https://api.staging.dismissible.io"},production:{baseUrl:"https://api.dismissible.io"}},we=()=>ge["production"]||pe,re=(e,r,t)=>{try{const n=`${r}_${e}`,i=localStorage.getItem(n);if(!i)return null;const{data:s,timestamp:o}=JSON.parse(i);return t&&Date.now()-o>t?(localStorage.removeItem(n),null):s}catch(n){return null}},se=(e,r,t)=>{try{const n=`${t}_${e}`,i={data:r,timestamp:Date.now()};localStorage.setItem(n,JSON.stringify(i))}catch(n){console.warn("Failed to cache dismissible item:",n)}},ne=(e,r)=>{try{const t=`${r}_${e}`;localStorage.removeItem(t)}catch(t){console.warn("Failed to remove cached dismissible item:",t)}},G=l.createContext(null),ie=()=>l.useContext(G),ve="dismissible",oe=(e,r={})=>{var z;const{initialData:t,enableCache:n=!0,cachePrefix:i=ve,cacheExpiration:s}=r,o=ie(),d=l.useMemo(()=>{const m=we(),y=(o==null?void 0:o.baseUrl)||m.baseUrl;return B({baseUrl:y,headers:{}})},[o]),h=l.useMemo(()=>!!(o!=null&&o.jwt)?`${e}-auth`:e,[e,o==null?void 0:o.jwt]),g=l.useRef({enableCache:n,cachePrefix:i,cacheExpiration:s}),E=l.useRef(e),U=l.useRef(h),[f,c]=l.useState(!1),[A,D]=l.useState(null),[H,x]=l.useState(()=>{if(t)return t;if(n){const m=re(h,i,s);if(m)return m}}),$=l.useCallback(()=>O(this,null,function*(){var m;if(n){const y=re(h,i,s);if(y!=null&&y.dismissedAt){x(y),c(!1);return}}c(!0),D(null);try{const y=o!=null&&o.getAuthHeaders?yield o.getAuthHeaders():{},{data:j,error:R}=yield d.GET("/v1/dismissible/{itemId}",{params:{path:{itemId:e}},headers:y});if(R)throw new Error(((m=R==null?void 0:R.error)==null?void 0:m.message)||"Failed to fetch dismissible item");x(j.data),n&&j.data&&se(h,j.data,i)}catch(y){D(y instanceof Error?y:new Error("Unknown error occurred"))}finally{c(!1)}}),[e,h,n,i,s,d,o]);l.useEffect(()=>{const m=E.current!==e,y=U.current!==h;m||y?(E.current=e,U.current=h,$()):t||$()},[e,h,t]),l.useEffect(()=>{const m=g.current;(m.enableCache!==n||m.cachePrefix!==i||m.cacheExpiration!==s)&&(m.cachePrefix!==i&&ne(h,m.cachePrefix),!n&&m.enableCache&&ne(h,i),g.current={enableCache:n,cachePrefix:i,cacheExpiration:s},$())},[n,i,s,h]);const F=l.useCallback(()=>O(this,null,function*(){var m;D(null);try{const y=o!=null&&o.getAuthHeaders?yield o.getAuthHeaders():{},{data:j,error:R}=yield d.DELETE("/v1/dismissible/{itemId}",{params:{path:{itemId:e}},headers:y});if(R)throw new Error(((m=R==null?void 0:R.error)==null?void 0:m.message)||"Failed to dismiss item");x(j.data),n&&j.data&&se(h,j.data,i)}catch(y){throw D(y instanceof Error?y:new Error("Failed to dismiss item")),y}}),[h,n,i,d,o]);return{dismissedOn:(z=H==null?void 0:H.dismissedAt)!=null?z:null,dismiss:F,isLoading:f,error:A,item:H}},Ee=()=>u.jsx("div",{className:"dismissible-loading","aria-live":"polite",children:"Loading..."}),Ce=({error:e})=>u.jsxs("div",{className:"dismissible-error",role:"alert",children:["Error loading dismissible item: ",e.message]}),Re=({id:e,onDismiss:r,ariaLabel:t})=>u.jsx("button",{id:e,className:"dismissible-button",onClick:r,"aria-label":t,type:"button",children:"×"}),Se=({id:e,children:r,onDismiss:t,LoadingComponent:n=Ee,ErrorComponent:i=Ce,DismissButtonComponent:s=Re,enableCache:o,cachePrefix:d,cacheExpiration:h,ignoreErrors:g=!1})=>{const{dismissedOn:E,isLoading:U,error:f,dismiss:c}=oe(e,{enableCache:o,cachePrefix:d,cacheExpiration:h}),[A,D]=l.useState(!1),H=()=>O(this,null,function*(){D(!0);try{yield c(),t==null||t()}catch(x){D(!1)}});return U&&n?u.jsx(n,{id:e}):U&&!n?null:f&&i&&!g?u.jsx(i,{id:e,error:f}):E||A?null:u.jsxs("div",{className:"dismissible-container",children:[u.jsx("div",{className:"dismissible-content",children:r}),s?u.jsx(s,{id:e,onDismiss:H,ariaLabel:`Dismiss ${e}`}):null]})},ae=e=>O(this,null,function*(){if(typeof e=="function")try{const r=e();return yield Promise.resolve(r)}catch(r){console.warn("Failed to resolve JWT from function:",r);return}return e}),le=e=>O(this,null,function*(){const r=yield ae(e);return r?{Authorization:`Bearer ${r}`}:{}}),je=e=>{const r=e.split(".");return r.length===3&&r.every(t=>t.length>0)},Ae=({jwt:e,baseUrl:r,children:t})=>{const n=l.useMemo(()=>({jwt:e,baseUrl:r,getAuthHeaders:()=>O(this,null,function*(){return yield le(e)})}),[e,r]);return u.jsx(G.Provider,{value:n,children:t})},Ie="0.3.0";a.Dismissible=Se,a.DismissibleContext=G,a.DismissibleProvider=Ae,a.VERSION=Ie,a.getAuthHeaders=le,a.isValidJwtFormat=je,a.resolveJwt=ae,a.useDismissibleContext=ie,a.useDismissibleItem=oe,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
package/dist/root.d.ts CHANGED
@@ -9,4 +9,4 @@ export * from './contexts/DismissibleContext';
9
9
  export * from './contexts/DismissibleProvider';
10
10
  export * from './types/dismissible.types';
11
11
  export * from './utils/auth.utils';
12
- export declare const VERSION = "0.1.0";
12
+ export declare const VERSION = "0.3.0";
@@ -2,9 +2,9 @@
2
2
  * TypeScript types for the Dismissible Provider system
3
3
  */
4
4
  /**
5
- * JWT token can be either a static string or a function that returns a string
5
+ * JWT token can be either a static string, a function that returns a string, or an async function that returns a string
6
6
  */
7
- export type JwtToken = string | (() => string);
7
+ export type JwtToken = string | (() => string) | (() => Promise<string>);
8
8
  /**
9
9
  * Configuration options for the DismissibleProvider
10
10
  */
@@ -25,7 +25,7 @@ export interface DismissibleContextValue {
25
25
  /** Base URL for API requests */
26
26
  baseUrl?: string;
27
27
  /** Helper function to get authentication headers */
28
- getAuthHeaders: () => AuthHeaders;
28
+ getAuthHeaders: () => Promise<AuthHeaders>;
29
29
  }
30
30
  /**
31
31
  * Authentication headers type
@@ -1,16 +1,16 @@
1
1
  import { JwtToken, AuthHeaders } from '../types/dismissible.types';
2
2
  /**
3
- * Resolves a JWT token from either a static string or a function
4
- * @param jwt - The JWT token (string or function)
5
- * @returns The resolved JWT token or undefined
3
+ * Resolves a JWT token from either a static string, sync function, or async function
4
+ * @param jwt - The JWT token (string, sync function, or async function)
5
+ * @returns Promise that resolves to the JWT token or undefined
6
6
  */
7
- export declare const resolveJwt: (jwt: JwtToken | undefined) => string | undefined;
7
+ export declare const resolveJwt: (jwt: JwtToken | undefined) => Promise<string | undefined>;
8
8
  /**
9
9
  * Creates authentication headers from a JWT token
10
- * @param jwt - The JWT token (string or function)
11
- * @returns Headers object with Authorization header if JWT is available
10
+ * @param jwt - The JWT token (string, sync function, or async function)
11
+ * @returns Promise that resolves to headers object with Authorization header if JWT is available
12
12
  */
13
- export declare const getAuthHeaders: (jwt?: JwtToken) => AuthHeaders;
13
+ export declare const getAuthHeaders: (jwt?: JwtToken) => Promise<AuthHeaders>;
14
14
  /**
15
15
  * Validates that a JWT token is properly formatted
16
16
  * @param token - The JWT token to validate
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dismissible/react-client",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -39,17 +39,21 @@
39
39
  "react-dom": ">=18.0.0"
40
40
  },
41
41
  "devDependencies": {
42
+ "@babel/core": "^7.28.0",
43
+ "@babel/preset-env": "^7.28.0",
44
+ "@babel/preset-typescript": "^7.27.1",
42
45
  "@storybook/addon-a11y": "^9.0.15",
43
46
  "@storybook/addon-docs": "^9.0.15",
44
47
  "@storybook/react-vite": "^9.0.15",
45
48
  "@testing-library/jest-dom": "^6.6.3",
46
49
  "@testing-library/react": "^16.3.0",
47
50
  "@types/node": "^24.0.10",
48
- "@types/react": "^19.1.8",
49
- "@types/react-dom": "^19.1.6",
51
+ "@types/react": "^18.3.23",
52
+ "@types/react-dom": "^18.3.7",
50
53
  "@typescript-eslint/eslint-plugin": "^8.36.0",
51
54
  "@typescript-eslint/parser": "^8.36.0",
52
55
  "@vitejs/plugin-react": "^4.0.3",
56
+ "core-js": "^3.44.0",
53
57
  "eslint": "^8.45.0",
54
58
  "eslint-plugin-react": "^7.37.5",
55
59
  "eslint-plugin-react-hooks": "^5.2.0",
@@ -59,8 +63,8 @@
59
63
  "msw-storybook-addon": "^2.0.5",
60
64
  "openapi-typescript": "^7.8.0",
61
65
  "prettier": "^3.0.0",
62
- "react": "^19.1.0",
63
- "react-dom": "^19.1.0",
66
+ "react": "^18.3.1",
67
+ "react-dom": "^18.3.1",
64
68
  "storybook": "^9.0.15",
65
69
  "ts-node": "^10.9.2",
66
70
  "typescript": "^5.8.3",