@magicbell/react-headless
Advanced tools
Comparing version 4.4.5 to 4.4.6
/** | ||
* @license @magicbell/react-headless v4.4.5 | ||
* @license @magicbell/react-headless v4.4.6 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) MagicBell Inc. and its affiliates. |
/** | ||
* @license @magicbell/react-headless v4.4.5 | ||
* @license @magicbell/react-headless v4.4.6 | ||
* | ||
@@ -96,3 +96,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
name: "@magicbell/react-headless", | ||
version: "4.4.5" | ||
version: "4.4.6" | ||
} | ||
@@ -99,0 +99,0 @@ }); |
/** | ||
* @license @magicbell/react-headless v4.4.5 | ||
* @license @magicbell/react-headless v4.4.6 | ||
* | ||
@@ -10,3 +10,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
"use strict";var oe=Object.defineProperty,re=Object.defineProperties;var ie=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable;var T=(e,n,t)=>n in e?oe(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,p=(e,n)=>{for(var t in n||(n={}))B.call(n,t)&&T(e,t,n[t]);if(M)for(var t of M(n))J.call(n,t)&&T(e,t,n[t]);return e},A=(e,n)=>re(e,ie(n));var j=(e,n)=>{var t={};for(var s in e)B.call(e,s)&&n.indexOf(s)<0&&(t[s]=e[s]);if(e!=null&&M)for(var s of M(e))n.indexOf(s)<0&&J.call(e,s)&&(t[s]=e[s]);return t};var q=(e,n,t)=>(T(e,typeof n!="symbol"?n+"":n,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("tiny-warning");const $=require("react/jsx-runtime"),g=require("react"),ae=require("magicbell/user-client"),ce=require("zustand/vanilla"),ue=require("zustand"),le=require("humps"),fe=require("immer"),m=require("ramda"),de=require("mitt"),me=require("dayjs"),he=require("dayjs/plugin/localizedFormat"),pe=require("dayjs/plugin/relativeTime"),Ae=require("dayjs/plugin/updateLocale"),w=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},ge=w(ce),z=w(ue),N=w(le),S=w(fe),Q=w(de),C=w(me),ye=w(he),Pe=w(pe),we=w(Ae),I=ge.default((e,n)=>{let t=null,s="";return{apiKey:"",userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com",appInfo:void 0,getClient(){const o=n(),i=JSON.stringify([o.apiKey,o.userEmail,o.userExternalId,o.userKey]);return i!==s&&(s=i,t=new ae.UserClient({userExternalId:o.userExternalId,userEmail:o.userEmail,userHmac:o.userKey,apiKey:o.apiKey,host:o.serverURL,appInfo:o.appInfo||{name:"@magicbell/react-headless",version:"4.4.5"}})),t}}});function F(e,n,t,s){const o=I.getState().getClient(),i=s?Object.fromEntries(Object.entries(s).map(([a,r])=>[a,String(r)])):void 0;return o.request({method:e,path:n,data:t,params:i})}function E(e,n){return F("GET",e,void 0,n)}function x(e,n,t){return F("POST",e,n,t)}function W(e,n){return F("DELETE",e,void 0,n)}function G(e,n){return F("PUT",e,n)}class Se{constructor(n="/config"){q(this,"remotePathOrUrl");this.remotePathOrUrl=n}async get(){const n=await E(this.remotePathOrUrl);return N.default.camelizeKeys(n)}}const K=z.default((e,n)=>({channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new Se,fetch:async()=>{const{_repository:t}=n(),s=await t.get();e(A(p({},s),{lastFetchedAt:Date.now()}))}}));class be{constructor(n){q(this,"remotePathOrUrl");this.remotePathOrUrl=n}async get(n){const t=`${this.remotePathOrUrl}/${n}`,s=await E(t);return N.default.camelizeKeys(s)}async findBy(n){try{const t=await E(this.remotePathOrUrl,n);return N.default.camelizeKeys(t)}catch(t){if(/Network Error/.test(t.message))return;throw t}}delete(n){const t=`${this.remotePathOrUrl}/${n}`;return W(t).then(()=>!0).catch(()=>!1)}}class V extends be{constructor(n="/notifications"){super(n)}markAsRead(n){const t=`${this.remotePathOrUrl}/${n}/read`;return x(t).then(()=>!0).catch(()=>!1)}markAsUnread(n){const t=`${this.remotePathOrUrl}/${n}/unread`;return x(t).then(()=>!0).catch(()=>!1)}markAllAsSeen(n){const t=`${this.remotePathOrUrl}/seen`;return x(t,void 0,n).then(()=>!0).catch(()=>!1)}markAllAsRead(n){const t=`${this.remotePathOrUrl}/read`;return x(t,void 0,n).then(()=>!0).catch(()=>!1)}}const X=Q.default(),D=Q.default();function P(e,n,t){t==="remote"&&X.emit(e,n),D.emit(e,{data:n,source:t})}function ve(e){const{clientId:n}=I.getState(),t=e.name.replace(/\//gi,"."),s=e.data;return s.client_id&&s.client_id===n?Promise.resolve(!1):typeof s.id=="string"?t==="notifications.delete"?(P(t,s,"remote"),Promise.resolve(!0)):new V().get(s.id).then(a=>(P(t,a.notification,"remote"),!0)):(P(t,s,"remote"),Promise.resolve(!0))}function L(e){const n={context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]};return m.mergeRight(n,e)}function xe(e,n,t={reset:!1}){const a=n,{notifications:s=[]}=a,o=j(a,["notifications"]),i=t.reset?s:m.uniqBy(r=>r.id,t.prepend?[...s,...e.notifications]:[...e.notifications,...s]);return p({context:e.context,notifications:i},o)}function Ne(e,n){return e===n||e!==e&&n!==n}function H(e){return Array.isArray(e)?e:String(e).split(",")}function v(e,n,t=Ne){const s=[];return Object.keys(n).forEach(o=>{const i=n[o];(o==="read"&&!t(!m.isNil(e.readAt),i)||o==="seen"&&!t(!m.isNil(e.seenAt),i)||o==="categories"&&H(i).every(a=>!t(e.category,a))||o==="topics"&&H(i).every(a=>!t(e.topic,a))||Object.hasOwnProperty.call(e,o)&&!t(e[o],i))&&s.push(o)}),{result:s.length===0,delta:s}}const U=z.default((e,n)=>({stores:{},_repository:new V,setStore:(t,s={},o={})=>{e(S.default(i=>{i.stores[t]=L(A(p({},o),{context:s}))}))},fetchStore:async(t,s={},o={})=>{const{stores:i,_repository:a}=n(),r=i[t];if(r){const l=await a.findBy(p(p({},r.context),s));if(!l)return;e(S.default(u=>{u.stores[t]=xe(r,A(p({},l),{lastFetchedAt:new Date}),o)}))}else console.error(`Store not found. Define a store with the ${t} ID`)},fetchAllStores:async(t={},s={})=>{const{stores:o,fetchStore:i}=n(),r=Object.keys(o).map(l=>i(l,t,s));await Promise.all(r)},markNotificationAsSeen:t=>{const{stores:s}=n(),o=t.id;P("notifications.seen",t,"local"),e(S.default(i=>{for(const a in s){const{notifications:r,unseenCount:l}=s[a],u=m.findIndex(m.propEq("id",o),r);u>-1&&(r[u].seenAt||(i.stores[a].unseenCount=Math.max(0,l-1),i.stores[a].notifications[u]=m.mergeRight(r[u],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:t=>{const{stores:s,_repository:o}=n(),{id:i}=t,a=o.markAsRead(i);return P("notifications.read",t,"local"),e(S.default(r=>{const l=Date.now()/1e3,u={readAt:l,seenAt:l};for(const c in s){const{total:d,notifications:f,context:h,unreadCount:y,unseenCount:R}=s[c],O=m.findIndex(m.propEq("id",i),f);if(O>-1){t.readAt||(r.stores[c].unreadCount=Math.max(0,y-1)),t.seenAt||(r.stores[c].unseenCount=Math.max(0,R-1));const k=m.mergeRight(f[O],u);v(k,h).result?r.stores[c].notifications[O]=k:(r.stores[c].total=Math.max(0,d-1),r.stores[c].notifications.splice(O,1))}else{const k=m.mergeRight(t,u);v(k,h).result&&(r.stores[c].total+=1,r.stores[c].notifications.push(k))}}})),a},markNotificationAsUnread:t=>{const{stores:s,_repository:o}=n(),{id:i}=t,a=o.markAsUnread(i);return P("notifications.unread",t,"local"),e(S.default(r=>{const l={readAt:null};for(const u in s){const{notifications:c,context:d}=s[u],f=m.findIndex(m.propEq("id",i),c);if(f>-1){const h=m.mergeRight(c[f],l);v(h,d).result?(t.readAt&&(r.stores[u].unreadCount+=1),r.stores[u].notifications[f]=h):(r.stores[u].total=Math.max(0,r.stores[u].total-1),r.stores[u].notifications.splice(f,1))}else{const h=m.mergeRight(t,l);v(h,d).result&&(r.stores[u].total+=1,t.readAt&&(r.stores[u].unreadCount+=1),r.stores[u].notifications.push(h))}}})),a},deleteNotification:(t,s={})=>{const{stores:o,_repository:i}=n(),a=t.id;let r=Promise.resolve(!0);return s.persist!==!1&&(r=i.delete(a),P("notifications.delete",t,"local")),e(S.default(l=>{for(const u in o){const{notifications:c,total:d,unseenCount:f,unreadCount:h}=o[u],y=m.findIndex(m.propEq("id",a),c);if(y>-1){const R=c[y];R.seenAt||(l.stores[u].unseenCount=Math.max(0,f-1)),R.readAt||(l.stores[u].unreadCount=Math.max(0,h-1)),l.stores[u].total=Math.max(0,d-1),l.stores[u].notifications.splice(y,1)}}})),r},markAllAsSeen:(t={persist:!0,updateModels:!0})=>{var a;const{stores:s,_repository:o}=n();let i=Promise.resolve(!0);if(t.persist!==!1){const r=t.storeId?(a=s[t.storeId])==null?void 0:a.context:{};i=o.markAllAsSeen(r),P("notifications.seen.all",null,"local")}return e(S.default(r=>{const l=new Map,u=Date.now()/1e3;for(const c in s){const{context:d}=s[c];if(r.stores[c].unseenCount=0,t.updateModels!==!1){if(d.seen!==!0)for(const f of r.stores[c].notifications)f.seenAt||(f.seenAt=u,l.set(f.id,f));d.seen===!1&&(r.stores[c].notifications=[],r.stores[c].total=0)}}for(const c in s){const{context:d}=s[c];if(d.seen!==!0)continue;const f=r.stores[c].notifications;for(const h of l.values())v(h,d).result&&!f.find(y=>y.id===h.id)&&(f.push(h),r.stores[c].total+=1)}})),i},markAllAsRead:(t={persist:!0,updateModels:!0})=>{var a;const{stores:s,_repository:o}=n();let i=Promise.resolve(!0);if(t.persist!==!1){const r=t.storeId?(a=s[t.storeId])==null?void 0:a.context:{};i=o.markAllAsRead(r),P("notifications.read.all",null,"local")}return e(S.default(r=>{const l=new Map,u=Date.now()/1e3;for(const c in s){const{context:d}=s[c];if(r.stores[c].unreadCount=0,r.stores[c].unseenCount=0,t.updateModels!==!1){if(d.read!==!0)for(const f of r.stores[c].notifications)f.readAt||(f.readAt=u,f.seenAt=u,l.set(f.id,f));d.read===!1&&(r.stores[c].notifications=[],r.stores[c].total=0)}}for(const c in s){const{context:d}=s[c];if(d.read!==!0)continue;const f=r.stores[c].notifications;for(const h of l.values())v(h,d).result&&!f.find(y=>y.id===h.id)&&(f.push(h),r.stores[c].total+=1)}})),i}}));function b(e,n,t={source:"any"}){g.useEffect(()=>{const s=(o={})=>{t.source==="remote"&&o.source!=="remote"||t.source==="local"&&o.source!=="local"||n(o.data,o.source)};return D.on(e,s),()=>{D.off(e,s)}},[])}function Y(){const e=U(),n=I.getState(),t=n.getClient(),s=n.apiKey,o=n.userExternalId||n.userEmail,i=()=>e.fetchAllStores({page:1},{reset:!0}),a=()=>e.fetchAllStores({page:1},{prepend:!0}),r=()=>e.markAllAsSeen({persist:!1}),l=()=>e.markAllAsRead({persist:!1}),u=c=>e.deleteNotification(c,{persist:!1});return g.useEffect(()=>{if(!s||!o)return;const c=t.listen();return c.forEach(d=>{!d||ve(d)}),()=>c.close()},[t,s,o]),b("reconnected",i),b("notifications.new",a,{source:"remote"}),b("notifications.seen.all",r,{source:"remote"}),b("notifications.read.all",l,{source:"remote"}),b("notifications.read",i,{source:"remote"}),b("notifications.unread",i,{source:"remote"}),b("notifications.delete",u,{source:"remote"}),null}function ke(t){var s=t,{serverURL:e}=s,n=j(s,["serverURL"]);const o=n;return e&&(o.serverURL=e),I.setState(o),o}function _e(e){const n={};return e.forEach(t=>{const{defaultQueryParams:s,defaults:o={}}=t;n[t.id]=L(p({context:s},o))}),U.setState({stores:n}),n}function Ee(o){var i=o,{children:e,stores:n=[{id:"default",defaultQueryParams:{}}],disableRealtime:t}=i,s=j(i,["children","stores","disableRealtime"]);g.useState(()=>ke(s)),g.useEffect(()=>{_e(n)},[]);const a=K();return g.useEffect(()=>{a.lastFetchedAt||a.fetch()},[a]),$.jsxs($.Fragment,{children:[t?null:$.jsx(Y,{}),e]})}function Ce(e){const n="=".repeat((4-e.length%4)%4),t=(e+n).replace(/-/g,"+").replace(/_/g,"/"),s=window.atob(t),o=new Uint8Array(s.length);for(let i=0;i<s.length;++i)o[i]=s.charCodeAt(i);return o}function Z(e){return x("/web_push_subscriptions",{web_push_subscription:{data:e}})}function Ie(e,n){const t=Ce(n);return e.subscribe({userVisibleOnly:!0,applicationServerKey:t})}async function Ue(e,n){const t=m.path(["webPush","config","vapidAuthentication","publicKey"],n.channels),s=await Ie(e,t);return Z(s.toJSON())}function Re(e,n,t="web.com.magicbell-notifications"){const s=window.safari.pushNotification.permission(t);return s.permission==="granted"?Promise.resolve(s):s.permission==="denied"?Promise.reject(!1):new Promise(function(o,i){window.safari.pushNotification.requestPermission(n,t,{authenticationToken:e},function(a){if(a.deviceToken){const r={endpoint:a.deviceToken,keys:{websitePushID:t},platform:"safari"};Z(r).then(l=>{o(l)}).catch(l=>{i(l)})}else{const r=new Error("Permission was denied");i(r)}})})}function Oe({children:e,serviceWorkerPath:n="/service-worker.js",skipServiceWorkerRegistration:t=!1}){const s=K(),o="safari"in window,i="PushManager"in window;return g.useEffect(()=>{t||navigator.serviceWorker.register(n)},[n,t]),e({createSubscription:async()=>{var r,l,u;if(!s)return Promise.reject(new Error("Context for MagicBell was not found"));if(o){const c=m.path(["safari","authenticationToken"],(r=s.channels)==null?void 0:r.webPush.config),d=m.path(["safari","websitePushId"],(l=s.channels)==null?void 0:l.webPush.config),f=m.path(["safari","webServiceUrl"],(u=s.channels)==null?void 0:u.webPush.config);return Re(c,f,d)}if(i)return navigator.serviceWorker.ready.then(async c=>{await Ue(c.pushManager,s)})},isPushAPISupported:i})}function ee(e="default"){const{stores:n,fetchStore:t,markAllAsSeen:s,markAllAsRead:o}=U(),i=K(),a=n[e],r=g.useCallback((d,f)=>t(e,d,f),[t,e]),l=g.useCallback((d={},f)=>{const h=a.currentPage+1;return t(e,A(p({},d),{page:h}),f)},[t,e,a==null?void 0:a.currentPage]);g.useEffect(()=>{!a||i.lastFetchedAt&&!a.lastFetchedAt&&r({page:1})},[i.lastFetchedAt,a,r]);const u=g.useCallback(d=>o(A(p({},d),{storeId:e})),[o,e]),c=g.useCallback(d=>s(A(p({},d),{storeId:e})),[s,e]);return a?A(p({},a),{isEmpty:a.notifications.length===0,hasNextPage:a.currentPage<a.totalPages,fetch:r,fetchNextPage:l,markAllAsSeen:c,markAllAsRead:u}):null}function Me({storeId:e}={}){const n=ee(e),t=()=>n&&n.unseenCount>0?n==null?void 0:n.markAllAsSeen({updateModels:!1}):Promise.resolve(!0);return n?A(p({},n),{markAllAsSeen:t}):null}C.default.extend(ye.default);C.default.extend(Pe.default);C.default.extend(we.default);function _(e){return e?te(e*1e3):null}function te(e){return C.default(e)}function je(e){return C.default(e).unix()}function qe(e){if(m.isNil(e))return null;if(typeof e=="string")try{return JSON.parse(e)}catch(n){}return e}function ne(e){const{markNotificationAsRead:n,markNotificationAsSeen:t,markNotificationAsUnread:s,deleteNotification:o}=U(),i=()=>t(e),a=()=>n(e),r=()=>s(e),l=()=>o(e);return A(p({},e),{customAttributes:qe(e.customAttributes),readAt:_(e.readAt),seenAt:_(e.seenAt),sentAt:_(e.sentAt),archivedAt:_(e.archivedAt),isSeen:!m.isNil(e.seenAt),isRead:!m.isNil(e.readAt),isArchived:!m.isNil(e.archivedAt),sanitizedContent:e.content,markAsSeen:i,markAsRead:a,markAsUnread:r,delete:l})}function se(e,n){g.useEffect(()=>()=>{n?n(e):e.markAsSeen()},[])}function De(e,n){const t=ne(e);return se(t,n),t}class Fe{constructor(n="/notification_preferences"){q(this,"remotePathOrUrl");this.remotePathOrUrl=n}async get(){const n=this.remotePathOrUrl,t=await E(n);return N.default.camelizeKeys(t)}async update(n){const t=this.remotePathOrUrl,s=N.default.decamelizeKeys({notificationPreferences:n}),o=await G(t,s);return N.default.camelizeKeys(o)}}const Ke=z.default((e,n)=>({categories:[],_repository:new Fe,fetch:async()=>{const{_repository:t}=n();try{const{notificationPreferences:s}=await t.get();e(A(p({},s),{lastFetchedAt:Date.now()}))}catch(s){e({categories:[],lastFetchedAt:Date.now()})}},save:async t=>{const{_repository:s}=n();try{const{notificationPreferences:o}=await s.update(t);e(A(p({},o),{lastFetchedAt:Date.now()}))}catch(o){e({categories:[],lastFetchedAt:Date.now()})}}}));exports.MagicBellProvider=Ee;exports.RealtimeListener=Y;exports.WebPushNotificationsSubscriber=Oe;exports.buildStore=L;exports.clientSettings=I;exports.deleteAPI=W;exports.eventAggregator=D;exports.fetchAPI=E;exports.postAPI=x;exports.pushEventAggregator=X;exports.putAPI=G;exports.secondsToDate=_;exports.toDate=te;exports.toUnix=je;exports.useBell=Me;exports.useConfig=K;exports.useMagicBellEvent=b;exports.useNotification=De;exports.useNotificationFactory=ne;exports.useNotificationPreferences=Ke;exports.useNotificationStoresCollection=U;exports.useNotificationUnmount=se;exports.useNotifications=ee; | ||
"use strict";var oe=Object.defineProperty,re=Object.defineProperties;var ie=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable;var T=(e,n,t)=>n in e?oe(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,p=(e,n)=>{for(var t in n||(n={}))B.call(n,t)&&T(e,t,n[t]);if(M)for(var t of M(n))J.call(n,t)&&T(e,t,n[t]);return e},A=(e,n)=>re(e,ie(n));var j=(e,n)=>{var t={};for(var s in e)B.call(e,s)&&n.indexOf(s)<0&&(t[s]=e[s]);if(e!=null&&M)for(var s of M(e))n.indexOf(s)<0&&J.call(e,s)&&(t[s]=e[s]);return t};var q=(e,n,t)=>(T(e,typeof n!="symbol"?n+"":n,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("tiny-warning");const $=require("react/jsx-runtime"),g=require("react"),ae=require("magicbell/user-client"),ce=require("zustand/vanilla"),ue=require("zustand"),le=require("humps"),fe=require("immer"),m=require("ramda"),de=require("mitt"),me=require("dayjs"),he=require("dayjs/plugin/localizedFormat"),pe=require("dayjs/plugin/relativeTime"),Ae=require("dayjs/plugin/updateLocale"),w=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},ge=w(ce),z=w(ue),N=w(le),S=w(fe),Q=w(de),C=w(me),ye=w(he),Pe=w(pe),we=w(Ae),I=ge.default((e,n)=>{let t=null,s="";return{apiKey:"",userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com",appInfo:void 0,getClient(){const o=n(),i=JSON.stringify([o.apiKey,o.userEmail,o.userExternalId,o.userKey]);return i!==s&&(s=i,t=new ae.UserClient({userExternalId:o.userExternalId,userEmail:o.userEmail,userHmac:o.userKey,apiKey:o.apiKey,host:o.serverURL,appInfo:o.appInfo||{name:"@magicbell/react-headless",version:"4.4.6"}})),t}}});function F(e,n,t,s){const o=I.getState().getClient(),i=s?Object.fromEntries(Object.entries(s).map(([a,r])=>[a,String(r)])):void 0;return o.request({method:e,path:n,data:t,params:i})}function E(e,n){return F("GET",e,void 0,n)}function x(e,n,t){return F("POST",e,n,t)}function W(e,n){return F("DELETE",e,void 0,n)}function G(e,n){return F("PUT",e,n)}class Se{constructor(n="/config"){q(this,"remotePathOrUrl");this.remotePathOrUrl=n}async get(){const n=await E(this.remotePathOrUrl);return N.default.camelizeKeys(n)}}const K=z.default((e,n)=>({channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new Se,fetch:async()=>{const{_repository:t}=n(),s=await t.get();e(A(p({},s),{lastFetchedAt:Date.now()}))}}));class be{constructor(n){q(this,"remotePathOrUrl");this.remotePathOrUrl=n}async get(n){const t=`${this.remotePathOrUrl}/${n}`,s=await E(t);return N.default.camelizeKeys(s)}async findBy(n){try{const t=await E(this.remotePathOrUrl,n);return N.default.camelizeKeys(t)}catch(t){if(/Network Error/.test(t.message))return;throw t}}delete(n){const t=`${this.remotePathOrUrl}/${n}`;return W(t).then(()=>!0).catch(()=>!1)}}class V extends be{constructor(n="/notifications"){super(n)}markAsRead(n){const t=`${this.remotePathOrUrl}/${n}/read`;return x(t).then(()=>!0).catch(()=>!1)}markAsUnread(n){const t=`${this.remotePathOrUrl}/${n}/unread`;return x(t).then(()=>!0).catch(()=>!1)}markAllAsSeen(n){const t=`${this.remotePathOrUrl}/seen`;return x(t,void 0,n).then(()=>!0).catch(()=>!1)}markAllAsRead(n){const t=`${this.remotePathOrUrl}/read`;return x(t,void 0,n).then(()=>!0).catch(()=>!1)}}const X=Q.default(),D=Q.default();function P(e,n,t){t==="remote"&&X.emit(e,n),D.emit(e,{data:n,source:t})}function ve(e){const{clientId:n}=I.getState(),t=e.name.replace(/\//gi,"."),s=e.data;return s.client_id&&s.client_id===n?Promise.resolve(!1):typeof s.id=="string"?t==="notifications.delete"?(P(t,s,"remote"),Promise.resolve(!0)):new V().get(s.id).then(a=>(P(t,a.notification,"remote"),!0)):(P(t,s,"remote"),Promise.resolve(!0))}function L(e){const n={context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]};return m.mergeRight(n,e)}function xe(e,n,t={reset:!1}){const a=n,{notifications:s=[]}=a,o=j(a,["notifications"]),i=t.reset?s:m.uniqBy(r=>r.id,t.prepend?[...s,...e.notifications]:[...e.notifications,...s]);return p({context:e.context,notifications:i},o)}function Ne(e,n){return e===n||e!==e&&n!==n}function H(e){return Array.isArray(e)?e:String(e).split(",")}function v(e,n,t=Ne){const s=[];return Object.keys(n).forEach(o=>{const i=n[o];(o==="read"&&!t(!m.isNil(e.readAt),i)||o==="seen"&&!t(!m.isNil(e.seenAt),i)||o==="categories"&&H(i).every(a=>!t(e.category,a))||o==="topics"&&H(i).every(a=>!t(e.topic,a))||Object.hasOwnProperty.call(e,o)&&!t(e[o],i))&&s.push(o)}),{result:s.length===0,delta:s}}const U=z.default((e,n)=>({stores:{},_repository:new V,setStore:(t,s={},o={})=>{e(S.default(i=>{i.stores[t]=L(A(p({},o),{context:s}))}))},fetchStore:async(t,s={},o={})=>{const{stores:i,_repository:a}=n(),r=i[t];if(r){const l=await a.findBy(p(p({},r.context),s));if(!l)return;e(S.default(u=>{u.stores[t]=xe(r,A(p({},l),{lastFetchedAt:new Date}),o)}))}else console.error(`Store not found. Define a store with the ${t} ID`)},fetchAllStores:async(t={},s={})=>{const{stores:o,fetchStore:i}=n(),r=Object.keys(o).map(l=>i(l,t,s));await Promise.all(r)},markNotificationAsSeen:t=>{const{stores:s}=n(),o=t.id;P("notifications.seen",t,"local"),e(S.default(i=>{for(const a in s){const{notifications:r,unseenCount:l}=s[a],u=m.findIndex(m.propEq("id",o),r);u>-1&&(r[u].seenAt||(i.stores[a].unseenCount=Math.max(0,l-1),i.stores[a].notifications[u]=m.mergeRight(r[u],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:t=>{const{stores:s,_repository:o}=n(),{id:i}=t,a=o.markAsRead(i);return P("notifications.read",t,"local"),e(S.default(r=>{const l=Date.now()/1e3,u={readAt:l,seenAt:l};for(const c in s){const{total:d,notifications:f,context:h,unreadCount:y,unseenCount:R}=s[c],O=m.findIndex(m.propEq("id",i),f);if(O>-1){t.readAt||(r.stores[c].unreadCount=Math.max(0,y-1)),t.seenAt||(r.stores[c].unseenCount=Math.max(0,R-1));const k=m.mergeRight(f[O],u);v(k,h).result?r.stores[c].notifications[O]=k:(r.stores[c].total=Math.max(0,d-1),r.stores[c].notifications.splice(O,1))}else{const k=m.mergeRight(t,u);v(k,h).result&&(r.stores[c].total+=1,r.stores[c].notifications.push(k))}}})),a},markNotificationAsUnread:t=>{const{stores:s,_repository:o}=n(),{id:i}=t,a=o.markAsUnread(i);return P("notifications.unread",t,"local"),e(S.default(r=>{const l={readAt:null};for(const u in s){const{notifications:c,context:d}=s[u],f=m.findIndex(m.propEq("id",i),c);if(f>-1){const h=m.mergeRight(c[f],l);v(h,d).result?(t.readAt&&(r.stores[u].unreadCount+=1),r.stores[u].notifications[f]=h):(r.stores[u].total=Math.max(0,r.stores[u].total-1),r.stores[u].notifications.splice(f,1))}else{const h=m.mergeRight(t,l);v(h,d).result&&(r.stores[u].total+=1,t.readAt&&(r.stores[u].unreadCount+=1),r.stores[u].notifications.push(h))}}})),a},deleteNotification:(t,s={})=>{const{stores:o,_repository:i}=n(),a=t.id;let r=Promise.resolve(!0);return s.persist!==!1&&(r=i.delete(a),P("notifications.delete",t,"local")),e(S.default(l=>{for(const u in o){const{notifications:c,total:d,unseenCount:f,unreadCount:h}=o[u],y=m.findIndex(m.propEq("id",a),c);if(y>-1){const R=c[y];R.seenAt||(l.stores[u].unseenCount=Math.max(0,f-1)),R.readAt||(l.stores[u].unreadCount=Math.max(0,h-1)),l.stores[u].total=Math.max(0,d-1),l.stores[u].notifications.splice(y,1)}}})),r},markAllAsSeen:(t={persist:!0,updateModels:!0})=>{var a;const{stores:s,_repository:o}=n();let i=Promise.resolve(!0);if(t.persist!==!1){const r=t.storeId?(a=s[t.storeId])==null?void 0:a.context:{};i=o.markAllAsSeen(r),P("notifications.seen.all",null,"local")}return e(S.default(r=>{const l=new Map,u=Date.now()/1e3;for(const c in s){const{context:d}=s[c];if(r.stores[c].unseenCount=0,t.updateModels!==!1){if(d.seen!==!0)for(const f of r.stores[c].notifications)f.seenAt||(f.seenAt=u,l.set(f.id,f));d.seen===!1&&(r.stores[c].notifications=[],r.stores[c].total=0)}}for(const c in s){const{context:d}=s[c];if(d.seen!==!0)continue;const f=r.stores[c].notifications;for(const h of l.values())v(h,d).result&&!f.find(y=>y.id===h.id)&&(f.push(h),r.stores[c].total+=1)}})),i},markAllAsRead:(t={persist:!0,updateModels:!0})=>{var a;const{stores:s,_repository:o}=n();let i=Promise.resolve(!0);if(t.persist!==!1){const r=t.storeId?(a=s[t.storeId])==null?void 0:a.context:{};i=o.markAllAsRead(r),P("notifications.read.all",null,"local")}return e(S.default(r=>{const l=new Map,u=Date.now()/1e3;for(const c in s){const{context:d}=s[c];if(r.stores[c].unreadCount=0,r.stores[c].unseenCount=0,t.updateModels!==!1){if(d.read!==!0)for(const f of r.stores[c].notifications)f.readAt||(f.readAt=u,f.seenAt=u,l.set(f.id,f));d.read===!1&&(r.stores[c].notifications=[],r.stores[c].total=0)}}for(const c in s){const{context:d}=s[c];if(d.read!==!0)continue;const f=r.stores[c].notifications;for(const h of l.values())v(h,d).result&&!f.find(y=>y.id===h.id)&&(f.push(h),r.stores[c].total+=1)}})),i}}));function b(e,n,t={source:"any"}){g.useEffect(()=>{const s=(o={})=>{t.source==="remote"&&o.source!=="remote"||t.source==="local"&&o.source!=="local"||n(o.data,o.source)};return D.on(e,s),()=>{D.off(e,s)}},[])}function Y(){const e=U(),n=I.getState(),t=n.getClient(),s=n.apiKey,o=n.userExternalId||n.userEmail,i=()=>e.fetchAllStores({page:1},{reset:!0}),a=()=>e.fetchAllStores({page:1},{prepend:!0}),r=()=>e.markAllAsSeen({persist:!1}),l=()=>e.markAllAsRead({persist:!1}),u=c=>e.deleteNotification(c,{persist:!1});return g.useEffect(()=>{if(!s||!o)return;const c=t.listen();return c.forEach(d=>{!d||ve(d)}),()=>c.close()},[t,s,o]),b("reconnected",i),b("notifications.new",a,{source:"remote"}),b("notifications.seen.all",r,{source:"remote"}),b("notifications.read.all",l,{source:"remote"}),b("notifications.read",i,{source:"remote"}),b("notifications.unread",i,{source:"remote"}),b("notifications.delete",u,{source:"remote"}),null}function ke(t){var s=t,{serverURL:e}=s,n=j(s,["serverURL"]);const o=n;return e&&(o.serverURL=e),I.setState(o),o}function _e(e){const n={};return e.forEach(t=>{const{defaultQueryParams:s,defaults:o={}}=t;n[t.id]=L(p({context:s},o))}),U.setState({stores:n}),n}function Ee(o){var i=o,{children:e,stores:n=[{id:"default",defaultQueryParams:{}}],disableRealtime:t}=i,s=j(i,["children","stores","disableRealtime"]);g.useState(()=>ke(s)),g.useEffect(()=>{_e(n)},[]);const a=K();return g.useEffect(()=>{a.lastFetchedAt||a.fetch()},[a]),$.jsxs($.Fragment,{children:[t?null:$.jsx(Y,{}),e]})}function Ce(e){const n="=".repeat((4-e.length%4)%4),t=(e+n).replace(/-/g,"+").replace(/_/g,"/"),s=window.atob(t),o=new Uint8Array(s.length);for(let i=0;i<s.length;++i)o[i]=s.charCodeAt(i);return o}function Z(e){return x("/web_push_subscriptions",{web_push_subscription:{data:e}})}function Ie(e,n){const t=Ce(n);return e.subscribe({userVisibleOnly:!0,applicationServerKey:t})}async function Ue(e,n){const t=m.path(["webPush","config","vapidAuthentication","publicKey"],n.channels),s=await Ie(e,t);return Z(s.toJSON())}function Re(e,n,t="web.com.magicbell-notifications"){const s=window.safari.pushNotification.permission(t);return s.permission==="granted"?Promise.resolve(s):s.permission==="denied"?Promise.reject(!1):new Promise(function(o,i){window.safari.pushNotification.requestPermission(n,t,{authenticationToken:e},function(a){if(a.deviceToken){const r={endpoint:a.deviceToken,keys:{websitePushID:t},platform:"safari"};Z(r).then(l=>{o(l)}).catch(l=>{i(l)})}else{const r=new Error("Permission was denied");i(r)}})})}function Oe({children:e,serviceWorkerPath:n="/service-worker.js",skipServiceWorkerRegistration:t=!1}){const s=K(),o="safari"in window,i="PushManager"in window;return g.useEffect(()=>{t||navigator.serviceWorker.register(n)},[n,t]),e({createSubscription:async()=>{var r,l,u;if(!s)return Promise.reject(new Error("Context for MagicBell was not found"));if(o){const c=m.path(["safari","authenticationToken"],(r=s.channels)==null?void 0:r.webPush.config),d=m.path(["safari","websitePushId"],(l=s.channels)==null?void 0:l.webPush.config),f=m.path(["safari","webServiceUrl"],(u=s.channels)==null?void 0:u.webPush.config);return Re(c,f,d)}if(i)return navigator.serviceWorker.ready.then(async c=>{await Ue(c.pushManager,s)})},isPushAPISupported:i})}function ee(e="default"){const{stores:n,fetchStore:t,markAllAsSeen:s,markAllAsRead:o}=U(),i=K(),a=n[e],r=g.useCallback((d,f)=>t(e,d,f),[t,e]),l=g.useCallback((d={},f)=>{const h=a.currentPage+1;return t(e,A(p({},d),{page:h}),f)},[t,e,a==null?void 0:a.currentPage]);g.useEffect(()=>{!a||i.lastFetchedAt&&!a.lastFetchedAt&&r({page:1})},[i.lastFetchedAt,a,r]);const u=g.useCallback(d=>o(A(p({},d),{storeId:e})),[o,e]),c=g.useCallback(d=>s(A(p({},d),{storeId:e})),[s,e]);return a?A(p({},a),{isEmpty:a.notifications.length===0,hasNextPage:a.currentPage<a.totalPages,fetch:r,fetchNextPage:l,markAllAsSeen:c,markAllAsRead:u}):null}function Me({storeId:e}={}){const n=ee(e),t=()=>n&&n.unseenCount>0?n==null?void 0:n.markAllAsSeen({updateModels:!1}):Promise.resolve(!0);return n?A(p({},n),{markAllAsSeen:t}):null}C.default.extend(ye.default);C.default.extend(Pe.default);C.default.extend(we.default);function _(e){return e?te(e*1e3):null}function te(e){return C.default(e)}function je(e){return C.default(e).unix()}function qe(e){if(m.isNil(e))return null;if(typeof e=="string")try{return JSON.parse(e)}catch(n){}return e}function ne(e){const{markNotificationAsRead:n,markNotificationAsSeen:t,markNotificationAsUnread:s,deleteNotification:o}=U(),i=()=>t(e),a=()=>n(e),r=()=>s(e),l=()=>o(e);return A(p({},e),{customAttributes:qe(e.customAttributes),readAt:_(e.readAt),seenAt:_(e.seenAt),sentAt:_(e.sentAt),archivedAt:_(e.archivedAt),isSeen:!m.isNil(e.seenAt),isRead:!m.isNil(e.readAt),isArchived:!m.isNil(e.archivedAt),sanitizedContent:e.content,markAsSeen:i,markAsRead:a,markAsUnread:r,delete:l})}function se(e,n){g.useEffect(()=>()=>{n?n(e):e.markAsSeen()},[])}function De(e,n){const t=ne(e);return se(t,n),t}class Fe{constructor(n="/notification_preferences"){q(this,"remotePathOrUrl");this.remotePathOrUrl=n}async get(){const n=this.remotePathOrUrl,t=await E(n);return N.default.camelizeKeys(t)}async update(n){const t=this.remotePathOrUrl,s=N.default.decamelizeKeys({notificationPreferences:n}),o=await G(t,s);return N.default.camelizeKeys(o)}}const Ke=z.default((e,n)=>({categories:[],_repository:new Fe,fetch:async()=>{const{_repository:t}=n();try{const{notificationPreferences:s}=await t.get();e(A(p({},s),{lastFetchedAt:Date.now()}))}catch(s){e({categories:[],lastFetchedAt:Date.now()})}},save:async t=>{const{_repository:s}=n();try{const{notificationPreferences:o}=await s.update(t);e(A(p({},o),{lastFetchedAt:Date.now()}))}catch(o){e({categories:[],lastFetchedAt:Date.now()})}}}));exports.MagicBellProvider=Ee;exports.RealtimeListener=Y;exports.WebPushNotificationsSubscriber=Oe;exports.buildStore=L;exports.clientSettings=I;exports.deleteAPI=W;exports.eventAggregator=D;exports.fetchAPI=E;exports.postAPI=x;exports.pushEventAggregator=X;exports.putAPI=G;exports.secondsToDate=_;exports.toDate=te;exports.toUnix=je;exports.useBell=Me;exports.useConfig=K;exports.useMagicBellEvent=b;exports.useNotification=De;exports.useNotificationFactory=ne;exports.useNotificationPreferences=Ke;exports.useNotificationStoresCollection=U;exports.useNotificationUnmount=se;exports.useNotifications=ee; | ||
//# sourceMappingURL=magicbell-react-headless.cjs.min.js.map |
/** | ||
* @license @magicbell/react-headless v4.4.5 | ||
* @license @magicbell/react-headless v4.4.6 | ||
* | ||
@@ -83,3 +83,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
name: "@magicbell/react-headless", | ||
version: "4.4.5" | ||
version: "4.4.6" | ||
} | ||
@@ -86,0 +86,0 @@ }); |
/** | ||
* @license @magicbell/react-headless v4.4.5 | ||
* @license @magicbell/react-headless v4.4.6 | ||
* | ||
@@ -66,3 +66,3 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
name: "@magicbell/react-headless", | ||
version: "4.4.5" | ||
version: "4.4.6" | ||
} | ||
@@ -69,0 +69,0 @@ })), t; |
{ | ||
"name": "@magicbell/react-headless", | ||
"version": "4.4.5", | ||
"version": "4.4.6", | ||
"description": "Hooks to build a notification inbox", | ||
@@ -64,5 +64,5 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com/)", | ||
"@types/humps": "^2.0.6", | ||
"@types/lodash": "^4.14.200", | ||
"@types/lodash": "^4.14.201", | ||
"@types/ramda": "^0.28.0", | ||
"@types/rosie": "^0.0.43", | ||
"@types/rosie": "^0.0.45", | ||
"babel-loader": "^8.2.2", | ||
@@ -69,0 +69,0 @@ "react": "^17.0.2", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package