@dismissible/react-client 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # @dismissible/react-client
2
2
 
3
- A React component library for creating dismissible UI elements with persistent state management.
3
+ A React component library for creating dismissible UI elements with persistent state management.
4
+
5
+ Use this in combination with [dismissible.io](https://dismissible.io). Get your free account now!
4
6
 
5
7
  🌐 **[dismissible.io](https://dismissible.io)** | 💰 **[View Pricing](https://dismissible.io/pricing)** | 📖 **[Documentation](https://docs.dismissible.io)**
6
8
 
@@ -369,32 +371,6 @@ function Dashboard() {
369
371
  }
370
372
  ```
371
373
 
372
- ### Conditional Dismissible Content
373
-
374
- ```tsx
375
- import { Dismissible } from '@dismissible/react-client';
376
-
377
- function ConditionalBanner({ user }) {
378
- // Only show to new users
379
- if (user.isReturning) {
380
- return null;
381
- }
382
-
383
- return (
384
- <Dismissible id={`onboarding-${user.id}`}>
385
- <div className="onboarding-tips">
386
- <h3>Getting Started</h3>
387
- <ul>
388
- <li>Complete your profile</li>
389
- <li>Connect with friends</li>
390
- <li>Explore our features</li>
391
- </ul>
392
- </div>
393
- </Dismissible>
394
- );
395
- }
396
- ```
397
-
398
374
  ### User-Specific vs Anonymous Dismissible Items
399
375
 
400
376
  The behavior changes based on whether JWT authentication is configured:
@@ -422,18 +398,6 @@ function AuthenticatedApp() {
422
398
  </DismissibleProvider>
423
399
  );
424
400
  }
425
-
426
- // Without JWT - dismissible state is account-level (anonymous)
427
- function AnonymousApp() {
428
- return (
429
- <div>
430
- {/* These will be dismissed for all users of this account */}
431
- <Dismissible id="general-announcement">
432
- <div>Site maintenance scheduled</div>
433
- </Dismissible>
434
- </div>
435
- );
436
- }
437
401
  ```
438
402
 
439
403
  ### Error Handling with ignoreErrors
@@ -455,18 +419,6 @@ function RobustBanner() {
455
419
  </Dismissible>
456
420
  );
457
421
  }
458
-
459
- // Default behavior - hide content on errors
460
- function StandardBanner() {
461
- return (
462
- <Dismissible id="promo-banner">
463
- <div className="promo">
464
- <h3>Special Offer!</h3>
465
- <p>Get 50% off your first order</p>
466
- </div>
467
- </Dismissible>
468
- );
469
- }
470
422
  ```
471
423
 
472
424
  ### Async JWT Authentication Examples
@@ -630,79 +582,6 @@ const AuthProvider: React.FC<DismissibleProviderProps> = ({ children, jwt }) =>
630
582
  };
631
583
  ```
632
584
 
633
- ## Development
634
-
635
- ### Prerequisites
636
-
637
- - Node.js 18+
638
- - npm or yarn
639
-
640
- ### Setup
641
-
642
- ```bash
643
- # Clone the repository
644
- git clone https://github.com/your-org/dismissible.git
645
- cd dismissible/react-client
646
-
647
- # Install dependencies
648
- npm install
649
-
650
- # Start development server
651
- npm run dev
652
- ```
653
-
654
- ### Available Scripts
655
-
656
- - `npm run dev` - Start development server with Vite
657
- - `npm run build` - Build the library for production
658
- - `npm run test` - Run tests with Vitest
659
- - `npm run test:watch` - Run tests in watch mode
660
- - `npm run lint` - Run ESLint
661
- - `npm run format` - Format code with Prettier
662
- - `npm run storybook` - Start Storybook development server
663
- - `npm run build-storybook` - Build Storybook for production
664
-
665
- ### Testing
666
-
667
- ```bash
668
- # Run all tests
669
- npm run test
670
-
671
- # Run tests in watch mode
672
- npm run test:watch
673
-
674
- # Run tests with coverage
675
- npm run test -- --coverage
676
- ```
677
-
678
- ### Storybook
679
-
680
- The library includes Storybook for component development and documentation:
681
-
682
- ```bash
683
- npm run storybook
684
- ```
685
-
686
- ## Contributing
687
-
688
- We welcome contributions! Please see our [Contributing Guide](../CONTRIBUTING.md) for details.
689
-
690
- ### Development Workflow
691
-
692
- 1. Fork the repository
693
- 2. Create a feature branch: `git checkout -b feature/my-new-feature`
694
- 3. Make your changes
695
- 4. Add tests for new functionality
696
- 5. Run tests: `npm run test`
697
- 6. Run linting: `npm run lint`
698
- 7. Commit your changes: `git commit -am 'Add new feature'`
699
- 8. Push to the branch: `git push origin feature/my-new-feature`
700
- 9. Submit a pull request
701
-
702
- ## License
703
-
704
- MIT © [Dismissible](https://github.com/joshystuart)
705
-
706
585
  ## Support
707
586
 
708
587
  - 📖 [Documentation](https://docs.dismissible.io)
@@ -1,22 +1,22 @@
1
1
  var de = Object.defineProperty, he = Object.defineProperties;
2
2
  var me = Object.getOwnPropertyDescriptors;
3
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) => {
4
+ var X = Object.prototype.hasOwnProperty, Y = Object.prototype.propertyIsEnumerable;
5
+ var V = (e, r, t) => r in e ? de(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t, y = (e, r) => {
6
6
  for (var t in r || (r = {}))
7
- V.call(r, t) && Q(e, t, r[t]);
7
+ X.call(r, t) && V(e, t, r[t]);
8
8
  if (k)
9
9
  for (var t of k(r))
10
- X.call(r, t) && Q(e, t, r[t]);
10
+ Y.call(r, t) && V(e, t, r[t]);
11
11
  return e;
12
12
  }, R = (e, r) => he(e, me(r));
13
13
  var W = (e, r) => {
14
14
  var t = {};
15
15
  for (var n in e)
16
- V.call(e, n) && r.indexOf(n) < 0 && (t[n] = e[n]);
16
+ X.call(e, n) && r.indexOf(n) < 0 && (t[n] = e[n]);
17
17
  if (e != null && k)
18
18
  for (var n of k(e))
19
- r.indexOf(n) < 0 && X.call(e, n) && (t[n] = e[n]);
19
+ r.indexOf(n) < 0 && Y.call(e, n) && (t[n] = e[n]);
20
20
  return t;
21
21
  };
22
22
  var S = (e, r, t) => new Promise((n, i) => {
@@ -36,7 +36,7 @@ var S = (e, r, t) => new Promise((n, i) => {
36
36
  u((t = t.apply(e, r)).next());
37
37
  });
38
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";
39
+ import { createContext as ye, useContext as be, useMemo as B, useRef as M, useState as F, useCallback as Z, useEffect as G } from "react";
40
40
  const pe = /\{[^{}]+\}/g, ge = () => {
41
41
  var e, r;
42
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;
@@ -66,8 +66,8 @@ function Re(e) {
66
66
  const h = [];
67
67
  function g(l, a) {
68
68
  return S(this, null, function* () {
69
- var K;
70
- const G = a || {}, {
69
+ var Q;
70
+ const K = a || {}, {
71
71
  baseUrl: E,
72
72
  fetch: C = n,
73
73
  Request: $ = t,
@@ -77,7 +77,7 @@ function Re(e) {
77
77
  querySerializer: U,
78
78
  bodySerializer: f = s != null ? s : Ee,
79
79
  body: d
80
- } = G, v = W(G, [
80
+ } = K, v = W(K, [
81
81
  "baseUrl",
82
82
  "fetch",
83
83
  "Request",
@@ -89,7 +89,7 @@ function Re(e) {
89
89
  "body"
90
90
  ]);
91
91
  let w = r;
92
- E && (w = (K = re(E)) != null ? K : r);
92
+ E && (w = (Q = re(E)) != null ? Q : r);
93
93
  let L = typeof i == "function" ? i : ee(i);
94
94
  U && (L = typeof U == "function" ? U : ee(y(y({}, typeof i == "object" ? i : {}), U)));
95
95
  const J = d === void 0 ? void 0 : f(
@@ -487,7 +487,7 @@ const Ae = {
487
487
  );
488
488
  if (f) return f;
489
489
  }
490
- }), A = Y(() => S(void 0, null, function* () {
490
+ }), A = Z(() => S(void 0, null, function* () {
491
491
  var f;
492
492
  if (n) {
493
493
  const d = ne(
@@ -534,10 +534,10 @@ const Ae = {
534
534
  u,
535
535
  o
536
536
  ]);
537
- Z(() => {
537
+ G(() => {
538
538
  const f = g.current !== e, d = j.current !== c;
539
539
  f || d ? (g.current = e, j.current = c, A()) : t || A();
540
- }, [e, c, t]), Z(() => {
540
+ }, [e, c, t]), G(() => {
541
541
  const f = h.current;
542
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
543
  enableCache: n,
@@ -545,7 +545,7 @@ const Ae = {
545
545
  cacheExpiration: s
546
546
  }, A());
547
547
  }, [n, i, s, c]);
548
- const q = Y(() => S(void 0, null, function* () {
548
+ const q = Z(() => S(void 0, null, function* () {
549
549
  var f;
550
550
  C(null);
551
551
  try {
@@ -607,7 +607,11 @@ const Ae = {
607
607
  enableCache: o,
608
608
  cachePrefix: u,
609
609
  cacheExpiration: c
610
- }), [E, C] = F(!1), $ = () => S(void 0, null, function* () {
610
+ }), [E, C] = F(!1);
611
+ G(() => {
612
+ C(!1);
613
+ }, [e]);
614
+ const $ = () => S(void 0, null, function* () {
611
615
  C(!0);
612
616
  try {
613
617
  yield a(), t == null || t();
@@ -1 +1 @@
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.1";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"})});
1
+ (function(l,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):(l=typeof globalThis!="undefined"?globalThis:l||self,u(l.DismissibleClient={},l.React.jsxRuntime,l.React))})(this,function(l,u,a){"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=(l,u,a)=>u in l?Te(l,u,{enumerable:!0,configurable:!0,writable:!0,value:a}):l[u]=a,p=(l,u)=>{for(var a in u||(u={}))de.call(u,a)&&fe(l,a,u[a]);if(W)for(var a of W(u))he.call(u,a)&&fe(l,a,u[a]);return l},S=(l,u)=>Ue(l,qe(u));var Y=(l,u)=>{var a={};for(var C in l)de.call(l,C)&&u.indexOf(C)<0&&(a[C]=l[C]);if(l!=null&&W)for(var C of W(l))u.indexOf(C)<0&&he.call(l,C)&&(a[C]=l[C]);return a};var O=(l,u,a)=>new Promise((C,L)=>{var V=D=>{try{T(a.next(D))}catch(k){L(k)}},B=D=>{try{T(a.throw(D))}catch(k){L(k)}},T=D=>D.done?C(D.value):Promise.resolve(D.value).then(V,B);T((a=a.apply(l,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:I=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:I,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 I(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 D(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(D(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,D(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=a.createContext(null),ie=()=>a.useContext(G),ve="dismissible",oe=(e,r={})=>{var z;const{initialData:t,enableCache:n=!0,cachePrefix:i=ve,cacheExpiration:s}=r,o=ie(),d=a.useMemo(()=>{const m=we(),y=(o==null?void 0:o.baseUrl)||m.baseUrl;return B({baseUrl:y,headers:{}})},[o]),h=a.useMemo(()=>!!(o!=null&&o.jwt)?`${e}-auth`:e,[e,o==null?void 0:o.jwt]),g=a.useRef({enableCache:n,cachePrefix:i,cacheExpiration:s}),E=a.useRef(e),U=a.useRef(h),[f,c]=a.useState(!1),[A,I]=a.useState(null),[H,x]=a.useState(()=>{if(t)return t;if(n){const m=re(h,i,s);if(m)return m}}),$=a.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),I(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){I(y instanceof Error?y:new Error("Unknown error occurred"))}finally{c(!1)}}),[e,h,n,i,s,d,o]);a.useEffect(()=>{const m=E.current!==e,y=U.current!==h;m||y?(E.current=e,U.current=h,$()):t||$()},[e,h,t]),a.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=a.useCallback(()=>O(this,null,function*(){var m;I(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 I(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,I]=a.useState(!1);a.useEffect(()=>{I(!1)},[e]);const H=()=>O(this,null,function*(){I(!0);try{yield c(),t==null||t()}catch(x){I(!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=a.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.1";l.Dismissible=Se,l.DismissibleContext=G,l.DismissibleProvider=Ae,l.VERSION=Ie,l.getAuthHeaders=le,l.isValidJwtFormat=je,l.resolveJwt=ae,l.useDismissibleContext=ie,l.useDismissibleItem=oe,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dismissible/react-client",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",