Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@magicbell/react-headless

Package Overview
Dependencies
Maintainers
2
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@magicbell/react-headless - npm Package Compare versions

Comparing version 2.5.1 to 2.6.0

12

dist/hooks/useMagicBellEvent.d.ts

@@ -0,7 +1,13 @@

import { EventSource } from '../lib/realtime';
interface HookOptions {
source: EventSource | 'any';
}
/**
* React hook to listen to realtime events.
* React hook to listen to events.
*
* @param event Name of the event
* @param handler
* @param handler Callback function
* @param options
*/
export default function useMagicBellEvent(event: string, handler: (data?: any) => void): void;
export default function useMagicBellEvent(event: string, handler: (data?: unknown, source?: EventSource) => void, options?: HookOptions): void;
export {};

@@ -11,9 +11,9 @@ export { default as MagicBellProvider } from './components/MagicBellProvider';

export { secondsToDate, toDate, toUnix } from './lib/date';
export { pushEventAggregator } from './lib/realtime';
export { eventAggregator, pushEventAggregator } from './lib/realtime';
export { default as clientSettings } from './stores/clientSettings';
export { default as useConfig } from './stores/config';
export { default as useNotificationPreferences } from './stores/notification_preferences';
export { useNotificationStoresCollection } from './stores/notifications';
export { default as buildStore } from './stores/notifications/helpers/buildStore';
export { default as useNotificationPreferences } from './stores/notification_preferences';
export * from './types';
export { INotification as Notification } from './types';
import * as Ably from 'ably';
import { WebSocketConfig } from '../types/IRemoteConfig';
declare const pushEventAggregator: import("mitt").Emitter<Record<import("mitt").EventType, unknown>>;
export { pushEventAggregator };
/** @deprecated */
export declare const pushEventAggregator: import("mitt").Emitter<Record<import("mitt").EventType, unknown>>;
export declare const eventAggregator: import("mitt").Emitter<Record<import("mitt").EventType, unknown>>;
export declare type EventSource = 'local' | 'remote';
/**

@@ -12,2 +14,10 @@ * Open an authenticated connection to ably.

/**
* Publish events to the internal and public event emitter, based on the event source.
*
* @param event The name of the event.
* @param data The data object to pass along with the event.
* @param source The origin of the event, local for an action that's triggered by the user in the current tab, remote if it's an event from another instance that should be mirrored.
*/
export declare function emitEvent(event: string, data: unknown, source: EventSource): void;
/**
* Publish an ably event to the push event emitter. If the push event contains

@@ -18,2 +28,2 @@ * the ID of a notification, this is fetched before emitting the event.

*/
export declare function handleAblyEvent(event: Ably.Types.Message): Promise<void> | Promise<boolean>;
export declare function handleAblyEvent(event: Ably.Types.Message): Promise<boolean>;

@@ -1,2 +0,2 @@

import t,{useEffect as e,useState as r}from"react";import n from"zustand/vanilla";import o from"zustand";import i from"humps";import a from"axios";import s from"immer";import u from"ramda/src/findIndex";import c from"ramda/src/mergeRight";import f from"ramda/src/propEq";import l from"ramda/src/uniqBy";import d from"ramda/src/isNil";import*as m from"ably";import v from"mitt";import h from"dayjs";import p from"dayjs/plugin/localizedFormat";import A from"dayjs/plugin/relativeTime";import P from"dayjs/plugin/updateLocale";import y from"ramda/src/mergeDeepRight";function g(){return(g=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function k(t,e){if(null==t)return{};var r,n,o={},i=Object.keys(t);for(n=0;n<i.length;n++)e.indexOf(r=i[n])>=0||(o[r]=t[r]);return o}var U=n(function(){return{apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}});function O(){var t=U.getState(),e=t.apiSecret,r=t.userEmail,n=t.userExternalId,o=t.userKey,i={"X-MAGICBELL-CLIENT-ID":t.clientId,"X-MAGICBELL-API-KEY":t.apiKey};return e&&(i["X-MAGICBELL-API-SECRET"]=e),r&&(i["X-MAGICBELL-USER-EMAIL"]=r),o&&(i["X-MAGICBELL-USER-HMAC"]=o),n&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=n),i}function w(t,e,r,n){var o=U.getState().serverURL,i=O();return a({method:t,url:e,data:r,params:n,headers:i,baseURL:o}).then(function(t){return t.data},function(t){throw t})}function E(t,e){return void 0===e&&(e={}),w("get",t,void 0,e)}function R(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),w("post",t,e,r)}function x(t,e){return void 0===e&&(e={}),w("delete",t,void 0,e)}function C(t,e,r){return void 0===r&&(r={}),w("put",t,e,r)}var b=/*#__PURE__*/function(){function t(t){void 0===t&&(t="/config"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}return t.prototype.get=function(){try{return Promise.resolve(E(this.remotePathOrUrl)).then(function(t){return i.camelizeKeys(t)})}catch(t){return Promise.reject(t)}},t}(),L=o(function(t,e){return{channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new b,fetch:function(){try{var r=e();return Promise.resolve(r._repository.get()).then(function(e){t(g({},e,{lastFetchedAt:Date.now()}))})}catch(t){return Promise.reject(t)}}}});function M(t){return c({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},t)}var j=["notifications"];function I(t,e){return t===e||t!=t&&e!=e}function _(t,e,r){void 0===r&&(r=I);var n=[];return Object.keys(e).forEach(function(o){var i=e[o];("read"===o&&!r(!d(t.readAt),i)||"seen"===o&&!r(!d(t.seenAt),i)||Object.hasOwnProperty.call(t,o)&&!r(t[o],i))&&n.push(o)}),{result:0===n.length,delta:n}}var N=/*#__PURE__*/function(t){var e,r;function n(e){return void 0===e&&(e="/notifications"),t.call(this,e)||this}r=t,(e=n).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var o=n.prototype;return o.markAsRead=function(t){return R(this.remotePathOrUrl+"/"+t+"/read").then(function(){return!0}).catch(function(){return!1})},o.markAsUnread=function(t){return R(this.remotePathOrUrl+"/"+t+"/unread").then(function(){return!0}).catch(function(){return!1})},o.markAllAsSeen=function(){return R(this.remotePathOrUrl+"/seen").then(function(){return!0}).catch(function(){return!1})},o.markAllAsRead=function(){return R(this.remotePathOrUrl+"/read").then(function(){return!0}).catch(function(){return!1})},n}(/*#__PURE__*/function(){function t(t){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}var e=t.prototype;return e.get=function(t){try{return Promise.resolve(E(this.remotePathOrUrl+"/"+t)).then(function(t){return i.camelizeKeys(t)})}catch(t){return Promise.reject(t)}},e.findBy=function(t){try{var e=this;return Promise.resolve(function(r,n){try{var o=Promise.resolve(E(e.remotePathOrUrl,t)).then(function(t){return i.camelizeKeys(t)})}catch(t){return n(t)}return o&&o.then?o.then(void 0,n):o}(0,function(t){if(!/Network Error/.test(t.message))throw t}))}catch(t){return Promise.reject(t)}},e.delete=function(t){return x(this.remotePathOrUrl+"/"+t).then(function(){return!0}).catch(function(){return!1})},t}()),D=o(function(t,e){return{stores:{},_repository:new N,setStore:function(e,r,n){void 0===r&&(r={}),void 0===n&&(n={}),t(s(function(t){t.stores[e]=M(g({},n,{context:r}))}))},fetchStore:function(r,n,o){void 0===n&&(n={}),void 0===o&&(o={});try{var i=e(),a=i._repository,u=i.stores[r];return Promise.resolve(function(){if(u)return Promise.resolve(a.findBy(g({},u.context,n))).then(function(e){e&&t(s(function(t){t.stores[r]=function(t,e,r){void 0===r&&(r={reset:!1});var n=e.notifications,o=k(e,j),i=r.reset?n:l(function(t){return t.id},r.prepend?[].concat(n,t.notifications):[].concat(t.notifications,n));return g({context:t.context,notifications:i},o)}(u,g({},e,{lastFetchedAt:new Date}),o)}))});console.error("Store not found. Define a store with the "+r+" ID")}())}catch(t){return Promise.reject(t)}},fetchAllStores:function(t,r){void 0===t&&(t={}),void 0===r&&(r={});try{var n=e(),o=n.fetchStore,i=Object.keys(n.stores).map(function(e){return o(e,t,r)});return Promise.resolve(Promise.all(i)).then(function(){})}catch(t){return Promise.reject(t)}},markNotificationAsSeen:function(r){var n=e().stores,o=r.id;t(s(function(t){for(var e in n){var r=n[e],i=r.notifications,a=r.unseenCount,s=u(f("id",o),i);s>-1&&(i[s].seenAt||(t.stores[e].unseenCount=Math.max(0,a-1),t.stores[e].notifications[s]=c(i[s],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:function(r){var n=e(),o=n.stores,i=r.id,a=n._repository.markAsRead(i);return t(s(function(t){var e={readAt:Date.now()/1e3};for(var n in o){var a=o[n],s=a.total,l=a.notifications,d=a.unreadCount,m=a.context,v=u(f("id",i),l);if(v>-1){t.stores[n].unreadCount=Math.max(0,d-1);var h=c(l[v],e);_(h,m).result?t.stores[n].notifications[v]=h:(t.stores[n].total=Math.max(0,s-1),t.stores[n].notifications.splice(v,1))}else{var p=c(r,e);_(p,m).result&&(t.stores[n].total+=1,t.stores[n].notifications.push(p))}}})),a},markNotificationAsUnread:function(r){var n=e(),o=n.stores,i=r.id,a=n._repository.markAsUnread(i);return t(s(function(t){var e={readAt:null};for(var n in o){var a=o[n],s=a.total,l=a.notifications,d=a.context,m=u(f("id",i),l);if(m>-1){var v=c(l[m],e);_(v,d).result?(t.stores[n].unreadCount+=1,t.stores[n].notifications[m]=v):(t.stores[n].total-=Math.max(0,s-1),t.stores[n].notifications.splice(m,1))}else{var h=c(r,e);_(h,d).result&&(t.stores[n].total+=1,t.stores[n].unreadCount+=1,t.stores[n].notifications.push(h))}}})),a},deleteNotification:function(r,n){void 0===n&&(n={});var o=e(),i=o.stores,a=o._repository,c=r.id,l=!1===n.persist?Promise.resolve(!0):a.delete(c);return t(s(function(t){for(var e in i){var r=i[e],n=r.notifications,o=r.total,a=r.unseenCount,s=r.unreadCount,l=u(f("id",c),n);if(l>-1){var d=n[l];d.seenAt||(t.stores[e].unseenCount=Math.max(0,a-1)),d.readAt||(t.stores[e].unreadCount=Math.max(0,s-1)),t.stores[e].total=Math.max(0,o-1),t.stores[e].notifications.splice(l,1)}}})),l},markAllAsSeen:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=e(),o=n.stores,i=!1!==r.persist?n._repository.markAllAsSeen():Promise.resolve(!0);return t(s(function(t){var e=function(e){var n=o[e].notifications;t.stores[e].unseenCount=0,!1!==r.updateModels&&n.forEach(function(r,n){t.stores[e].notifications[n]=c(r,{seenAt:Date.now()/1e3})})};for(var n in o)e(n)})),i},markAllAsRead:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=e(),o=n.stores,i=!1!==r.persist?n._repository.markAllAsRead():Promise.resolve(!0);return t(s(function(t){var e=function(e){var n=o[e].notifications;t.stores[e].unreadCount=0,!1!==r.updateModels&&n.forEach(function(r,n){t.stores[e].notifications[n]=c(r,{readAt:Date.now()/1e3})})};for(var n in o)e(n)})),i}}}),F=v();function K(t){var e=U.getState().clientId,r=t.name.replace(/\//gi,"."),n=t.data;return n.client_id&&n.client_id===e?Promise.resolve():"string"==typeof n.id?"notifications.delete"===r?(F.emit(r,n),Promise.resolve(!0)):(new N).get(n.id).then(function(t){F.emit(r,t.notification)}):(F.emit(r,n),Promise.resolve())}function z(t,r){e(function(){return F.on(t,r),function(){F.off(t,r)}},[])}function B(){var t,r=D(),n=function(){return r.fetchAllStores({page:1},{reset:!0})};return t=L(),e(function(){return t.ws?function(t){var e=t.channel,r=function(t){var e=U.getState().serverURL+"/"+t.authUrl,r=O();return new m.Realtime({authUrl:e,authHeaders:r,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(t),n=function(){return F.emit("wakeup")};r.connection.on("disconnected",n),r.connection.on("suspended",n);var o=r.channels.get(e);return o.subscribe(K),function(){o.unsubscribe(K),o.detach(),r.connection.off("disconnected"),r.connection.off("suspended"),r.close()}}(t.ws):function(){}},[t.ws]),z("wakeup",n),z("notifications.new",function(){return r.fetchAllStores({page:1},{prepend:!0})}),z("notifications.seen.all",function(){return r.markAllAsSeen({persist:!1})}),z("notifications.read.all",function(){return r.markAllAsRead({persist:!1})}),z("notifications.read",n),z("notifications.unread",n),z("notifications.delete",function(t){return r.deleteNotification(t,{persist:!1})}),null}var X=["serverURL"],G=["children","stores","disableRealtime"];function T(t){var e=t.serverURL,r=k(t,X);return e&&(r.serverURL=e),U.setState(r),r}function q(n){var o=n.children,i=n.stores,a=void 0===i?[{id:"default",defaultQueryParams:{}}]:i,s=n.disableRealtime,u=k(n,G);r(function(){return T(u)}),r(function(){return function(t){var e={};return t.forEach(function(t){var r=t.defaults;e[t.id]=M(g({context:t.defaultQueryParams},void 0===r?{}:r))}),D.setState({stores:e}),e}(a)});var c=L();return e(function(){c.lastFetchedAt||c.fetch()},[c]),t.createElement(t.Fragment,null,s?null:t.createElement(B,null),o)}function H(t){void 0===t&&(t="default");var r=D(),n=r.stores,o=r.fetchStore,i=r.markAllAsSeen,a=r.markAllAsRead,s=L(),u=n[t],c=function(e,r){return o(t,e,r)};return e(function(){u&&s.lastFetchedAt&&!u.lastFetchedAt&&c({page:1})},[s.lastFetchedAt]),u?g({},u,{isEmpty:0===u.notifications.length,hasNextPage:u.currentPage<u.totalPages,fetch:c,fetchNextPage:function(e,r){return void 0===e&&(e={}),o(t,g({},e,{page:u.currentPage+1}),r)},markAllAsSeen:i,markAllAsRead:a}):null}function J(t){var e=H((void 0===t?{}:t).storeId);return e?g({},e,{markAllAsSeen:function(){return e&&e.unseenCount>0?null==e?void 0:e.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}}):null}function Q(t){return t?Y(1e3*t):null}function Y(t){return h(t)}function V(t){return h(t).unix()}function W(t){if(d(t))return null;if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.warn('"customAttributes" is not valid JSON')}return t}function Z(t){var e=D(),r=e.markNotificationAsRead,n=e.markNotificationAsSeen,o=e.markNotificationAsUnread,i=e.deleteNotification;return g({},t,{customAttributes:W(t.customAttributes),readAt:Q(t.readAt),seenAt:Q(t.seenAt),sentAt:Q(t.sentAt),archivedAt:Q(t.archivedAt),isSeen:!d(t.seenAt),isRead:!d(t.readAt),isArchived:!d(t.archivedAt),sanitizedContent:t.content,markAsSeen:function(){return n(t)},markAsRead:function(){return r(t)},markAsUnread:function(){return o(t)},delete:function(){return i(t)}})}function $(t,r){e(function(){return function(){r?r(t):t.markAsSeen()}},[])}function tt(t,e){var r=Z(t);return $(r,e),r}h.extend(p),h.extend(A),h.extend(P);var et=/*#__PURE__*/function(){function t(t){void 0===t&&(t="/notification_preferences"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}var e=t.prototype;return e.get=function(){try{return Promise.resolve(E(this.remotePathOrUrl)).then(function(t){return i.camelizeKeys(t)})}catch(t){return Promise.reject(t)}},e.update=function(t){return C(this.remotePathOrUrl,i.decamelizeKeys(t)).then(function(){return!0}).catch(function(){return!1})},t}(),rt=o(function(t,e){return{categories:{},_repository:new et,fetch:function(){try{var r=e();return Promise.resolve(r._repository.get()).then(function(e){t(g({},e.notificationPreferences,{lastFetchedAt:Date.now()}))})}catch(t){return Promise.reject(t)}},save:function(r){try{var n=e(),o=n.categories;return n._repository.update({notificationPreferences:r}),t({categories:y(o,r.categories),lastFetchedAt:Date.now()}),Promise.resolve()}catch(t){return Promise.reject(t)}}}});export{q as MagicBellProvider,B as RealtimeListener,M as buildStore,U as clientSettings,x as deleteAPI,E as fetchAPI,R as postAPI,F as pushEventAggregator,C as putAPI,Q as secondsToDate,Y as toDate,V as toUnix,J as useBell,L as useConfig,z as useMagicBellEvent,tt as useNotification,Z as useNotificationFactory,rt as useNotificationPreferences,D as useNotificationStoresCollection,$ as useNotificationUnmount,H as useNotifications};
import t,{useEffect as e,useState as r}from"react";import n from"zustand/vanilla";import o from"zustand";import i from"humps";import a from"axios";import s from"immer";import c from"ramda/src/findIndex";import u from"ramda/src/mergeRight";import f from"ramda/src/propEq";import*as l from"ably";import d from"mitt";import m from"ramda/src/uniqBy";import v from"ramda/src/isNil";import h from"dayjs";import p from"dayjs/plugin/localizedFormat";import A from"dayjs/plugin/relativeTime";import P from"dayjs/plugin/updateLocale";import y from"ramda/src/mergeDeepRight";function g(){return(g=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function k(t,e){if(null==t)return{};var r,n,o={},i=Object.keys(t);for(n=0;n<i.length;n++)e.indexOf(r=i[n])>=0||(o[r]=t[r]);return o}var U=n(function(){return{apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}});function O(){var t=U.getState(),e=t.apiSecret,r=t.userEmail,n=t.userExternalId,o=t.userKey,i={"X-MAGICBELL-CLIENT-ID":t.clientId,"X-MAGICBELL-API-KEY":t.apiKey};return e&&(i["X-MAGICBELL-API-SECRET"]=e),r&&(i["X-MAGICBELL-USER-EMAIL"]=r),o&&(i["X-MAGICBELL-USER-HMAC"]=o),n&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=n),i}function w(t,e,r,n){var o=U.getState().serverURL,i=O();return a({method:t,url:e,data:r,params:n,headers:i,baseURL:o}).then(function(t){return t.data},function(t){throw t})}function E(t,e){return void 0===e&&(e={}),w("get",t,void 0,e)}function R(t,e,r){return void 0===e&&(e={}),void 0===r&&(r={}),w("post",t,e,r)}function x(t,e){return void 0===e&&(e={}),w("delete",t,void 0,e)}function C(t,e,r){return void 0===r&&(r={}),w("put",t,e,r)}var b=/*#__PURE__*/function(){function t(t){void 0===t&&(t="/config"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}return t.prototype.get=function(){try{return Promise.resolve(E(this.remotePathOrUrl)).then(function(t){return i.camelizeKeys(t)})}catch(t){return Promise.reject(t)}},t}(),L=o(function(t,e){return{channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new b,fetch:function(){try{var r=e();return Promise.resolve(r._repository.get()).then(function(e){t(g({},e,{lastFetchedAt:Date.now()}))})}catch(t){return Promise.reject(t)}}}}),M=/*#__PURE__*/function(t){var e,r;function n(e){return void 0===e&&(e="/notifications"),t.call(this,e)||this}r=t,(e=n).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var o=n.prototype;return o.markAsRead=function(t){return R(this.remotePathOrUrl+"/"+t+"/read").then(function(){return!0}).catch(function(){return!1})},o.markAsUnread=function(t){return R(this.remotePathOrUrl+"/"+t+"/unread").then(function(){return!0}).catch(function(){return!1})},o.markAllAsSeen=function(){return R(this.remotePathOrUrl+"/seen").then(function(){return!0}).catch(function(){return!1})},o.markAllAsRead=function(){return R(this.remotePathOrUrl+"/read").then(function(){return!0}).catch(function(){return!1})},n}(/*#__PURE__*/function(){function t(t){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}var e=t.prototype;return e.get=function(t){try{return Promise.resolve(E(this.remotePathOrUrl+"/"+t)).then(function(t){return i.camelizeKeys(t)})}catch(t){return Promise.reject(t)}},e.findBy=function(t){try{var e=this;return Promise.resolve(function(r,n){try{var o=Promise.resolve(E(e.remotePathOrUrl,t)).then(function(t){return i.camelizeKeys(t)})}catch(t){return n(t)}return o&&o.then?o.then(void 0,n):o}(0,function(t){if(!/Network Error/.test(t.message))throw t}))}catch(t){return Promise.reject(t)}},e.delete=function(t){return x(this.remotePathOrUrl+"/"+t).then(function(){return!0}).catch(function(){return!1})},t}()),j=d(),I=d();function _(t,e,r){"remote"===r&&j.emit(t,e),I.emit(t,{data:e,source:r})}function N(t){var e=U.getState().clientId,r=t.name.replace(/\//gi,"."),n=t.data;return n.client_id&&n.client_id===e?Promise.resolve(!1):"string"==typeof n.id?"notifications.delete"===r?(_(r,n,"remote"),Promise.resolve(!0)):(new M).get(n.id).then(function(t){return _(r,t.notification,"remote"),!0}):(_(r,n,"remote"),Promise.resolve(!0))}function D(t){return u({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},t)}var F=["notifications"];function K(t,e){return t===e||t!=t&&e!=e}function z(t,e,r){void 0===r&&(r=K);var n=[];return Object.keys(e).forEach(function(o){var i=e[o];("read"===o&&!r(!v(t.readAt),i)||"seen"===o&&!r(!v(t.seenAt),i)||Object.hasOwnProperty.call(t,o)&&!r(t[o],i))&&n.push(o)}),{result:0===n.length,delta:n}}var B=o(function(t,e){return{stores:{},_repository:new M,setStore:function(e,r,n){void 0===r&&(r={}),void 0===n&&(n={}),t(s(function(t){t.stores[e]=D(g({},n,{context:r}))}))},fetchStore:function(r,n,o){void 0===n&&(n={}),void 0===o&&(o={});try{var i=e(),a=i._repository,c=i.stores[r];return Promise.resolve(function(){if(c)return Promise.resolve(a.findBy(g({},c.context,n))).then(function(e){e&&t(s(function(t){t.stores[r]=function(t,e,r){void 0===r&&(r={reset:!1});var n=e.notifications,o=k(e,F),i=r.reset?n:m(function(t){return t.id},r.prepend?[].concat(n,t.notifications):[].concat(t.notifications,n));return g({context:t.context,notifications:i},o)}(c,g({},e,{lastFetchedAt:new Date}),o)}))});console.error("Store not found. Define a store with the "+r+" ID")}())}catch(t){return Promise.reject(t)}},fetchAllStores:function(t,r){void 0===t&&(t={}),void 0===r&&(r={});try{var n=e(),o=n.fetchStore,i=Object.keys(n.stores).map(function(e){return o(e,t,r)});return Promise.resolve(Promise.all(i)).then(function(){})}catch(t){return Promise.reject(t)}},markNotificationAsSeen:function(r){var n=e().stores,o=r.id;_("notifications.seen",r,"local"),t(s(function(t){for(var e in n){var r=n[e],i=r.notifications,a=r.unseenCount,s=c(f("id",o),i);s>-1&&(i[s].seenAt||(t.stores[e].unseenCount=Math.max(0,a-1),t.stores[e].notifications[s]=u(i[s],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:function(r){var n=e(),o=n.stores,i=r.id,a=n._repository.markAsRead(i);return _("notifications.read",r,"local"),t(s(function(t){var e={readAt:Date.now()/1e3};for(var n in o){var a=o[n],s=a.total,l=a.notifications,d=a.unreadCount,m=a.context,v=c(f("id",i),l);if(v>-1){t.stores[n].unreadCount=Math.max(0,d-1);var h=u(l[v],e);z(h,m).result?t.stores[n].notifications[v]=h:(t.stores[n].total=Math.max(0,s-1),t.stores[n].notifications.splice(v,1))}else{var p=u(r,e);z(p,m).result&&(t.stores[n].total+=1,t.stores[n].notifications.push(p))}}})),a},markNotificationAsUnread:function(r){var n=e(),o=n.stores,i=r.id,a=n._repository.markAsUnread(i);return _("notifications.unread",r,"local"),t(s(function(t){var e={readAt:null};for(var n in o){var a=o[n],s=a.total,l=a.notifications,d=a.context,m=c(f("id",i),l);if(m>-1){var v=u(l[m],e);z(v,d).result?(t.stores[n].unreadCount+=1,t.stores[n].notifications[m]=v):(t.stores[n].total-=Math.max(0,s-1),t.stores[n].notifications.splice(m,1))}else{var h=u(r,e);z(h,d).result&&(t.stores[n].total+=1,t.stores[n].unreadCount+=1,t.stores[n].notifications.push(h))}}})),a},deleteNotification:function(r,n){void 0===n&&(n={});var o=e(),i=o.stores,a=o._repository,u=r.id,l=Promise.resolve(!0);return!1!==n.persist&&(l=a.delete(u),_("notifications.delete",r,"local")),t(s(function(t){for(var e in i){var r=i[e],n=r.notifications,o=r.total,a=r.unseenCount,s=r.unreadCount,l=c(f("id",u),n);if(l>-1){var d=n[l];d.seenAt||(t.stores[e].unseenCount=Math.max(0,a-1)),d.readAt||(t.stores[e].unreadCount=Math.max(0,s-1)),t.stores[e].total=Math.max(0,o-1),t.stores[e].notifications.splice(l,1)}}})),l},markAllAsSeen:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=e(),o=n.stores,i=n._repository,a=Promise.resolve(!0);return!1!==r.persist&&(a=i.markAllAsSeen(),_("notifications.seen.all",null,"local")),t(s(function(t){var e=function(e){var n=o[e].notifications;t.stores[e].unseenCount=0,!1!==r.updateModels&&n.forEach(function(r,n){t.stores[e].notifications[n]=u(r,{seenAt:Date.now()/1e3})})};for(var n in o)e(n)})),a},markAllAsRead:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=e(),o=n.stores,i=n._repository,a=Promise.resolve(!0);return!1!==r.persist&&(a=i.markAllAsRead(),_("notifications.read.all",null,"local")),t(s(function(t){var e=function(e){var n=o[e].notifications;t.stores[e].unreadCount=0,!1!==r.updateModels&&n.forEach(function(r,n){t.stores[e].notifications[n]=u(r,{readAt:Date.now()/1e3})})};for(var n in o)e(n)})),a}}});function X(t,r,n){void 0===n&&(n={source:"any"}),e(function(){var e=function(t){void 0===t&&(t={}),"remote"===n.source&&"remote"!==t.source||"local"===n.source&&"local"!==t.source||r(t.data,t.source)};return I.on(t,e),function(){I.off(t,e)}},[])}function G(){var t,r=B(),n=function(){return r.fetchAllStores({page:1},{reset:!0})};return t=L(),e(function(){return t.ws?function(t){var e=t.channel,r=function(t){var e=U.getState().serverURL+"/"+t.authUrl,r=O();return new l.Realtime({authUrl:e,authHeaders:r,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(t),n=function(){return _("wakeup",null,"local")};r.connection.on("disconnected",n),r.connection.on("suspended",n);var o=r.channels.get(e);return o.subscribe(N),function(){o.unsubscribe(N),o.detach(),r.connection.off("disconnected"),r.connection.off("suspended"),r.close()}}(t.ws):function(){}},[t.ws]),X("wakeup",n),X("notifications.new",function(){return r.fetchAllStores({page:1},{prepend:!0})},{source:"remote"}),X("notifications.seen.all",function(){return r.markAllAsSeen({persist:!1})},{source:"remote"}),X("notifications.read.all",function(){return r.markAllAsRead({persist:!1})},{source:"remote"}),X("notifications.read",n,{source:"remote"}),X("notifications.unread",n,{source:"remote"}),X("notifications.delete",function(t){return r.deleteNotification(t,{persist:!1})},{source:"remote"}),null}var T=["serverURL"],q=["children","stores","disableRealtime"];function H(t){var e=t.serverURL,r=k(t,T);return e&&(r.serverURL=e),U.setState(r),r}function J(n){var o=n.children,i=n.stores,a=void 0===i?[{id:"default",defaultQueryParams:{}}]:i,s=n.disableRealtime,c=k(n,q);r(function(){return H(c)}),r(function(){return function(t){var e={};return t.forEach(function(t){var r=t.defaults;e[t.id]=D(g({context:t.defaultQueryParams},void 0===r?{}:r))}),B.setState({stores:e}),e}(a)});var u=L();return e(function(){u.lastFetchedAt||u.fetch()},[u]),t.createElement(t.Fragment,null,s?null:t.createElement(G,null),o)}function Q(t){void 0===t&&(t="default");var r=B(),n=r.stores,o=r.fetchStore,i=r.markAllAsSeen,a=r.markAllAsRead,s=L(),c=n[t],u=function(e,r){return o(t,e,r)};return e(function(){c&&s.lastFetchedAt&&!c.lastFetchedAt&&u({page:1})},[s.lastFetchedAt]),c?g({},c,{isEmpty:0===c.notifications.length,hasNextPage:c.currentPage<c.totalPages,fetch:u,fetchNextPage:function(e,r){return void 0===e&&(e={}),o(t,g({},e,{page:c.currentPage+1}),r)},markAllAsSeen:i,markAllAsRead:a}):null}function Y(t){var e=Q((void 0===t?{}:t).storeId);return e?g({},e,{markAllAsSeen:function(){return e&&e.unseenCount>0?null==e?void 0:e.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}}):null}function V(t){return t?W(1e3*t):null}function W(t){return h(t)}function Z(t){return h(t).unix()}function $(t){if(v(t))return null;if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.warn('"customAttributes" is not valid JSON')}return t}function tt(t){var e=B(),r=e.markNotificationAsRead,n=e.markNotificationAsSeen,o=e.markNotificationAsUnread,i=e.deleteNotification;return g({},t,{customAttributes:$(t.customAttributes),readAt:V(t.readAt),seenAt:V(t.seenAt),sentAt:V(t.sentAt),archivedAt:V(t.archivedAt),isSeen:!v(t.seenAt),isRead:!v(t.readAt),isArchived:!v(t.archivedAt),sanitizedContent:t.content,markAsSeen:function(){return n(t)},markAsRead:function(){return r(t)},markAsUnread:function(){return o(t)},delete:function(){return i(t)}})}function et(t,r){e(function(){return function(){r?r(t):t.markAsSeen()}},[])}function rt(t,e){var r=tt(t);return et(r,e),r}h.extend(p),h.extend(A),h.extend(P);var nt=/*#__PURE__*/function(){function t(t){void 0===t&&(t="/notification_preferences"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}var e=t.prototype;return e.get=function(){try{return Promise.resolve(E(this.remotePathOrUrl)).then(function(t){return i.camelizeKeys(t)})}catch(t){return Promise.reject(t)}},e.update=function(t){return C(this.remotePathOrUrl,i.decamelizeKeys(t)).then(function(){return!0}).catch(function(){return!1})},t}(),ot=o(function(t,e){return{categories:{},_repository:new nt,fetch:function(){try{var r=e();return Promise.resolve(r._repository.get()).then(function(e){t(g({},e.notificationPreferences,{lastFetchedAt:Date.now()}))})}catch(t){return Promise.reject(t)}},save:function(r){try{var n=e(),o=n.categories;return n._repository.update({notificationPreferences:r}),t({categories:y(o,r.categories),lastFetchedAt:Date.now()}),Promise.resolve()}catch(t){return Promise.reject(t)}}}});export{J as MagicBellProvider,G as RealtimeListener,D as buildStore,U as clientSettings,x as deleteAPI,I as eventAggregator,E as fetchAPI,R as postAPI,j as pushEventAggregator,C as putAPI,V as secondsToDate,W as toDate,Z as toUnix,Y as useBell,L as useConfig,X as useMagicBellEvent,rt as useNotification,tt as useNotificationFactory,ot as useNotificationPreferences,B as useNotificationStoresCollection,et as useNotificationUnmount,Q as useNotifications};
//# sourceMappingURL=magicbell-react-headless.esm.js.map

@@ -1,2 +0,2 @@

var e=require("react"),t=require("zustand/vanilla"),r=require("zustand"),n=require("humps"),o=require("axios"),i=require("immer"),a=require("ramda/src/findIndex"),u=require("ramda/src/mergeRight"),s=require("ramda/src/propEq"),c=require("ramda/src/uniqBy"),f=require("ramda/src/isNil"),l=require("ably"),d=require("mitt"),v=require("dayjs"),h=require("dayjs/plugin/localizedFormat"),m=require("dayjs/plugin/relativeTime"),p=require("dayjs/plugin/updateLocale"),A=require("ramda/src/mergeDeepRight");function P(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function y(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}var g=/*#__PURE__*/P(e),x=/*#__PURE__*/P(t),S=/*#__PURE__*/P(r),E=/*#__PURE__*/P(n),k=/*#__PURE__*/P(o),O=/*#__PURE__*/P(i),U=/*#__PURE__*/P(a),b=/*#__PURE__*/P(u),w=/*#__PURE__*/P(s),R=/*#__PURE__*/P(c),C=/*#__PURE__*/P(f),j=/*#__PURE__*/y(l),M=/*#__PURE__*/P(d),I=/*#__PURE__*/P(v),L=/*#__PURE__*/P(h),N=/*#__PURE__*/P(m),_=/*#__PURE__*/P(p),q=/*#__PURE__*/P(A);function D(){return(D=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function B(e,t){return(B=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function F(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)t.indexOf(r=i[n])>=0||(o[r]=e[r]);return o}var K=x.default(function(){return{apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}});function z(){var e=K.getState(),t=e.apiSecret,r=e.userEmail,n=e.userExternalId,o=e.userKey,i={"X-MAGICBELL-CLIENT-ID":e.clientId,"X-MAGICBELL-API-KEY":e.apiKey};return t&&(i["X-MAGICBELL-API-SECRET"]=t),r&&(i["X-MAGICBELL-USER-EMAIL"]=r),o&&(i["X-MAGICBELL-USER-HMAC"]=o),n&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=n),i}function X(e,t,r,n){var o=K.getState().serverURL,i=z();return k.default({method:e,url:t,data:r,params:n,headers:i,baseURL:o}).then(function(e){return e.data},function(e){throw e})}function G(e,t){return void 0===t&&(t={}),X("get",e,void 0,t)}function T(e,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),X("post",e,t,r)}function H(e,t){return void 0===t&&(t={}),X("delete",e,void 0,t)}function J(e,t,r){return void 0===r&&(r={}),X("put",e,t,r)}var Q=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/config"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}return e.prototype.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},e}(),Y=S.default(function(e,t){return{channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new Q,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(D({},t,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}}}});function V(e){return b.default({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},e)}var W=["notifications"];function Z(e,t){return e===t||e!=e&&t!=t}function $(e,t,r){void 0===r&&(r=Z);var n=[];return Object.keys(t).forEach(function(o){var i=t[o];("read"===o&&!r(!C.default(e.readAt),i)||"seen"===o&&!r(!C.default(e.seenAt),i)||Object.hasOwnProperty.call(e,o)&&!r(e[o],i))&&n.push(o)}),{result:0===n.length,delta:n}}var ee=/*#__PURE__*/function(e){var t,r;function n(t){return void 0===t&&(t="/notifications"),e.call(this,t)||this}r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,B(t,r);var o=n.prototype;return o.markAsRead=function(e){return T(this.remotePathOrUrl+"/"+e+"/read").then(function(){return!0}).catch(function(){return!1})},o.markAsUnread=function(e){return T(this.remotePathOrUrl+"/"+e+"/unread").then(function(){return!0}).catch(function(){return!1})},o.markAllAsSeen=function(){return T(this.remotePathOrUrl+"/seen").then(function(){return!0}).catch(function(){return!1})},o.markAllAsRead=function(){return T(this.remotePathOrUrl+"/read").then(function(){return!0}).catch(function(){return!1})},n}(/*#__PURE__*/function(){function e(e){this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(e){try{return Promise.resolve(G(this.remotePathOrUrl+"/"+e)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.findBy=function(e){try{var t=this;return Promise.resolve(function(r,n){try{var o=Promise.resolve(G(t.remotePathOrUrl,e)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){if(!/Network Error/.test(e.message))throw e}))}catch(e){return Promise.reject(e)}},t.delete=function(e){return H(this.remotePathOrUrl+"/"+e).then(function(){return!0}).catch(function(){return!1})},e}()),te=S.default(function(e,t){return{stores:{},_repository:new ee,setStore:function(t,r,n){void 0===r&&(r={}),void 0===n&&(n={}),e(O.default(function(e){e.stores[t]=V(D({},n,{context:r}))}))},fetchStore:function(r,n,o){void 0===n&&(n={}),void 0===o&&(o={});try{var i=t(),a=i._repository,u=i.stores[r];return Promise.resolve(function(){if(u)return Promise.resolve(a.findBy(D({},u.context,n))).then(function(t){t&&e(O.default(function(e){e.stores[r]=function(e,t,r){void 0===r&&(r={reset:!1});var n=t.notifications,o=F(t,W),i=r.reset?n:R.default(function(e){return e.id},r.prepend?[].concat(n,e.notifications):[].concat(e.notifications,n));return D({context:e.context,notifications:i},o)}(u,D({},t,{lastFetchedAt:new Date}),o)}))});console.error("Store not found. Define a store with the "+r+" ID")}())}catch(e){return Promise.reject(e)}},fetchAllStores:function(e,r){void 0===e&&(e={}),void 0===r&&(r={});try{var n=t(),o=n.fetchStore,i=Object.keys(n.stores).map(function(t){return o(t,e,r)});return Promise.resolve(Promise.all(i)).then(function(){})}catch(e){return Promise.reject(e)}},markNotificationAsSeen:function(r){var n=t().stores,o=r.id;e(O.default(function(e){for(var t in n){var r=n[t],i=r.notifications,a=r.unseenCount,u=U.default(w.default("id",o),i);u>-1&&(i[u].seenAt||(e.stores[t].unseenCount=Math.max(0,a-1),e.stores[t].notifications[u]=b.default(i[u],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsRead(i);return e(O.default(function(e){var t={readAt:Date.now()/1e3};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.unreadCount,f=a.context,l=U.default(w.default("id",i),s);if(l>-1){e.stores[n].unreadCount=Math.max(0,c-1);var d=b.default(s[l],t);$(d,f).result?e.stores[n].notifications[l]=d:(e.stores[n].total=Math.max(0,u-1),e.stores[n].notifications.splice(l,1))}else{var v=b.default(r,t);$(v,f).result&&(e.stores[n].total+=1,e.stores[n].notifications.push(v))}}})),a},markNotificationAsUnread:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsUnread(i);return e(O.default(function(e){var t={readAt:null};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.context,f=U.default(w.default("id",i),s);if(f>-1){var l=b.default(s[f],t);$(l,c).result?(e.stores[n].unreadCount+=1,e.stores[n].notifications[f]=l):(e.stores[n].total-=Math.max(0,u-1),e.stores[n].notifications.splice(f,1))}else{var d=b.default(r,t);$(d,c).result&&(e.stores[n].total+=1,e.stores[n].unreadCount+=1,e.stores[n].notifications.push(d))}}})),a},deleteNotification:function(r,n){void 0===n&&(n={});var o=t(),i=o.stores,a=o._repository,u=r.id,s=!1===n.persist?Promise.resolve(!0):a.delete(u);return e(O.default(function(e){for(var t in i){var r=i[t],n=r.notifications,o=r.total,a=r.unseenCount,s=r.unreadCount,c=U.default(w.default("id",u),n);if(c>-1){var f=n[c];f.seenAt||(e.stores[t].unseenCount=Math.max(0,a-1)),f.readAt||(e.stores[t].unreadCount=Math.max(0,s-1)),e.stores[t].total=Math.max(0,o-1),e.stores[t].notifications.splice(c,1)}}})),s},markAllAsSeen:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=!1!==r.persist?n._repository.markAllAsSeen():Promise.resolve(!0);return e(O.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unseenCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=b.default(r,{seenAt:Date.now()/1e3})})};for(var n in o)t(n)})),i},markAllAsRead:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=!1!==r.persist?n._repository.markAllAsRead():Promise.resolve(!0);return e(O.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unreadCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=b.default(r,{readAt:Date.now()/1e3})})};for(var n in o)t(n)})),i}}}),re=M.default();function ne(e){var t=K.getState().clientId,r=e.name.replace(/\//gi,"."),n=e.data;return n.client_id&&n.client_id===t?Promise.resolve():"string"==typeof n.id?"notifications.delete"===r?(re.emit(r,n),Promise.resolve(!0)):(new ee).get(n.id).then(function(e){re.emit(r,e.notification)}):(re.emit(r,n),Promise.resolve())}function oe(t,r){e.useEffect(function(){return re.on(t,r),function(){re.off(t,r)}},[])}function ie(){var t,r=te(),n=function(){return r.fetchAllStores({page:1},{reset:!0})};return t=Y(),e.useEffect(function(){return t.ws?function(e){var t=e.channel,r=function(e){var t=K.getState().serverURL+"/"+e.authUrl,r=z();return new j.Realtime({authUrl:t,authHeaders:r,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(e),n=function(){return re.emit("wakeup")};r.connection.on("disconnected",n),r.connection.on("suspended",n);var o=r.channels.get(t);return o.subscribe(ne),function(){o.unsubscribe(ne),o.detach(),r.connection.off("disconnected"),r.connection.off("suspended"),r.close()}}(t.ws):function(){}},[t.ws]),oe("wakeup",n),oe("notifications.new",function(){return r.fetchAllStores({page:1},{prepend:!0})}),oe("notifications.seen.all",function(){return r.markAllAsSeen({persist:!1})}),oe("notifications.read.all",function(){return r.markAllAsRead({persist:!1})}),oe("notifications.read",n),oe("notifications.unread",n),oe("notifications.delete",function(e){return r.deleteNotification(e,{persist:!1})}),null}var ae=["serverURL"],ue=["children","stores","disableRealtime"];function se(e){var t=e.serverURL,r=F(e,ae);return t&&(r.serverURL=t),K.setState(r),r}function ce(t){void 0===t&&(t="default");var r=te(),n=r.stores,o=r.fetchStore,i=r.markAllAsSeen,a=r.markAllAsRead,u=Y(),s=n[t],c=function(e,r){return o(t,e,r)};return e.useEffect(function(){s&&u.lastFetchedAt&&!s.lastFetchedAt&&c({page:1})},[u.lastFetchedAt]),s?D({},s,{isEmpty:0===s.notifications.length,hasNextPage:s.currentPage<s.totalPages,fetch:c,fetchNextPage:function(e,r){return void 0===e&&(e={}),o(t,D({},e,{page:s.currentPage+1}),r)},markAllAsSeen:i,markAllAsRead:a}):null}function fe(e){return e?le(1e3*e):null}function le(e){return I.default(e)}function de(e){if(C.default(e))return null;if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.warn('"customAttributes" is not valid JSON')}return e}function ve(e){var t=te(),r=t.markNotificationAsRead,n=t.markNotificationAsSeen,o=t.markNotificationAsUnread,i=t.deleteNotification;return D({},e,{customAttributes:de(e.customAttributes),readAt:fe(e.readAt),seenAt:fe(e.seenAt),sentAt:fe(e.sentAt),archivedAt:fe(e.archivedAt),isSeen:!C.default(e.seenAt),isRead:!C.default(e.readAt),isArchived:!C.default(e.archivedAt),sanitizedContent:e.content,markAsSeen:function(){return n(e)},markAsRead:function(){return r(e)},markAsUnread:function(){return o(e)},delete:function(){return i(e)}})}function he(t,r){e.useEffect(function(){return function(){r?r(t):t.markAsSeen()}},[])}I.default.extend(L.default),I.default.extend(N.default),I.default.extend(_.default);var me=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/notification_preferences"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.update=function(e){return J(this.remotePathOrUrl,E.default.decamelizeKeys(e)).then(function(){return!0}).catch(function(){return!1})},e}(),pe=S.default(function(e,t){return{categories:{},_repository:new me,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(D({},t.notificationPreferences,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}},save:function(r){try{var n=t(),o=n.categories;return n._repository.update({notificationPreferences:r}),e({categories:q.default(o,r.categories),lastFetchedAt:Date.now()}),Promise.resolve()}catch(e){return Promise.reject(e)}}}});exports.MagicBellProvider=function(t){var r=t.children,n=t.stores,o=void 0===n?[{id:"default",defaultQueryParams:{}}]:n,i=t.disableRealtime,a=F(t,ue);e.useState(function(){return se(a)}),e.useState(function(){return function(e){var t={};return e.forEach(function(e){var r=e.defaults;t[e.id]=V(D({context:e.defaultQueryParams},void 0===r?{}:r))}),te.setState({stores:t}),t}(o)});var u=Y();return e.useEffect(function(){u.lastFetchedAt||u.fetch()},[u]),g.default.createElement(g.default.Fragment,null,i?null:g.default.createElement(ie,null),r)},exports.RealtimeListener=ie,exports.buildStore=V,exports.clientSettings=K,exports.deleteAPI=H,exports.fetchAPI=G,exports.postAPI=T,exports.pushEventAggregator=re,exports.putAPI=J,exports.secondsToDate=fe,exports.toDate=le,exports.toUnix=function(e){return I.default(e).unix()},exports.useBell=function(e){var t=ce((void 0===e?{}:e).storeId);return t?D({},t,{markAllAsSeen:function(){return t&&t.unseenCount>0?null==t?void 0:t.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}}):null},exports.useConfig=Y,exports.useMagicBellEvent=oe,exports.useNotification=function(e,t){var r=ve(e);return he(r,t),r},exports.useNotificationFactory=ve,exports.useNotificationPreferences=pe,exports.useNotificationStoresCollection=te,exports.useNotificationUnmount=he,exports.useNotifications=ce;
var e=require("react"),t=require("zustand/vanilla"),r=require("zustand"),n=require("humps"),o=require("axios"),i=require("immer"),a=require("ramda/src/findIndex"),u=require("ramda/src/mergeRight"),s=require("ramda/src/propEq"),c=require("ably"),f=require("mitt"),l=require("ramda/src/uniqBy"),d=require("ramda/src/isNil"),v=require("dayjs"),h=require("dayjs/plugin/localizedFormat"),m=require("dayjs/plugin/relativeTime"),p=require("dayjs/plugin/updateLocale"),A=require("ramda/src/mergeDeepRight");function P(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function y(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}var g=/*#__PURE__*/P(e),x=/*#__PURE__*/P(t),S=/*#__PURE__*/P(r),E=/*#__PURE__*/P(n),k=/*#__PURE__*/P(o),O=/*#__PURE__*/P(i),U=/*#__PURE__*/P(a),b=/*#__PURE__*/P(u),w=/*#__PURE__*/P(s),R=/*#__PURE__*/y(c),C=/*#__PURE__*/P(f),j=/*#__PURE__*/P(l),M=/*#__PURE__*/P(d),I=/*#__PURE__*/P(v),L=/*#__PURE__*/P(h),N=/*#__PURE__*/P(m),_=/*#__PURE__*/P(p),q=/*#__PURE__*/P(A);function D(){return(D=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function B(e,t){return(B=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function F(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)t.indexOf(r=i[n])>=0||(o[r]=e[r]);return o}var K=x.default(function(){return{apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}});function z(){var e=K.getState(),t=e.apiSecret,r=e.userEmail,n=e.userExternalId,o=e.userKey,i={"X-MAGICBELL-CLIENT-ID":e.clientId,"X-MAGICBELL-API-KEY":e.apiKey};return t&&(i["X-MAGICBELL-API-SECRET"]=t),r&&(i["X-MAGICBELL-USER-EMAIL"]=r),o&&(i["X-MAGICBELL-USER-HMAC"]=o),n&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=n),i}function X(e,t,r,n){var o=K.getState().serverURL,i=z();return k.default({method:e,url:t,data:r,params:n,headers:i,baseURL:o}).then(function(e){return e.data},function(e){throw e})}function G(e,t){return void 0===t&&(t={}),X("get",e,void 0,t)}function T(e,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),X("post",e,t,r)}function H(e,t){return void 0===t&&(t={}),X("delete",e,void 0,t)}function J(e,t,r){return void 0===r&&(r={}),X("put",e,t,r)}var Q=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/config"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}return e.prototype.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},e}(),Y=S.default(function(e,t){return{channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new Q,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(D({},t,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}}}}),V=/*#__PURE__*/function(e){var t,r;function n(t){return void 0===t&&(t="/notifications"),e.call(this,t)||this}r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,B(t,r);var o=n.prototype;return o.markAsRead=function(e){return T(this.remotePathOrUrl+"/"+e+"/read").then(function(){return!0}).catch(function(){return!1})},o.markAsUnread=function(e){return T(this.remotePathOrUrl+"/"+e+"/unread").then(function(){return!0}).catch(function(){return!1})},o.markAllAsSeen=function(){return T(this.remotePathOrUrl+"/seen").then(function(){return!0}).catch(function(){return!1})},o.markAllAsRead=function(){return T(this.remotePathOrUrl+"/read").then(function(){return!0}).catch(function(){return!1})},n}(/*#__PURE__*/function(){function e(e){this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(e){try{return Promise.resolve(G(this.remotePathOrUrl+"/"+e)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.findBy=function(e){try{var t=this;return Promise.resolve(function(r,n){try{var o=Promise.resolve(G(t.remotePathOrUrl,e)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){if(!/Network Error/.test(e.message))throw e}))}catch(e){return Promise.reject(e)}},t.delete=function(e){return H(this.remotePathOrUrl+"/"+e).then(function(){return!0}).catch(function(){return!1})},e}()),W=C.default(),Z=C.default();function $(e,t,r){"remote"===r&&W.emit(e,t),Z.emit(e,{data:t,source:r})}function ee(e){var t=K.getState().clientId,r=e.name.replace(/\//gi,"."),n=e.data;return n.client_id&&n.client_id===t?Promise.resolve(!1):"string"==typeof n.id?"notifications.delete"===r?($(r,n,"remote"),Promise.resolve(!0)):(new V).get(n.id).then(function(e){return $(r,e.notification,"remote"),!0}):($(r,n,"remote"),Promise.resolve(!0))}function te(e){return b.default({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},e)}var re=["notifications"];function ne(e,t){return e===t||e!=e&&t!=t}function oe(e,t,r){void 0===r&&(r=ne);var n=[];return Object.keys(t).forEach(function(o){var i=t[o];("read"===o&&!r(!M.default(e.readAt),i)||"seen"===o&&!r(!M.default(e.seenAt),i)||Object.hasOwnProperty.call(e,o)&&!r(e[o],i))&&n.push(o)}),{result:0===n.length,delta:n}}var ie=S.default(function(e,t){return{stores:{},_repository:new V,setStore:function(t,r,n){void 0===r&&(r={}),void 0===n&&(n={}),e(O.default(function(e){e.stores[t]=te(D({},n,{context:r}))}))},fetchStore:function(r,n,o){void 0===n&&(n={}),void 0===o&&(o={});try{var i=t(),a=i._repository,u=i.stores[r];return Promise.resolve(function(){if(u)return Promise.resolve(a.findBy(D({},u.context,n))).then(function(t){t&&e(O.default(function(e){e.stores[r]=function(e,t,r){void 0===r&&(r={reset:!1});var n=t.notifications,o=F(t,re),i=r.reset?n:j.default(function(e){return e.id},r.prepend?[].concat(n,e.notifications):[].concat(e.notifications,n));return D({context:e.context,notifications:i},o)}(u,D({},t,{lastFetchedAt:new Date}),o)}))});console.error("Store not found. Define a store with the "+r+" ID")}())}catch(e){return Promise.reject(e)}},fetchAllStores:function(e,r){void 0===e&&(e={}),void 0===r&&(r={});try{var n=t(),o=n.fetchStore,i=Object.keys(n.stores).map(function(t){return o(t,e,r)});return Promise.resolve(Promise.all(i)).then(function(){})}catch(e){return Promise.reject(e)}},markNotificationAsSeen:function(r){var n=t().stores,o=r.id;$("notifications.seen",r,"local"),e(O.default(function(e){for(var t in n){var r=n[t],i=r.notifications,a=r.unseenCount,u=U.default(w.default("id",o),i);u>-1&&(i[u].seenAt||(e.stores[t].unseenCount=Math.max(0,a-1),e.stores[t].notifications[u]=b.default(i[u],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsRead(i);return $("notifications.read",r,"local"),e(O.default(function(e){var t={readAt:Date.now()/1e3};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.unreadCount,f=a.context,l=U.default(w.default("id",i),s);if(l>-1){e.stores[n].unreadCount=Math.max(0,c-1);var d=b.default(s[l],t);oe(d,f).result?e.stores[n].notifications[l]=d:(e.stores[n].total=Math.max(0,u-1),e.stores[n].notifications.splice(l,1))}else{var v=b.default(r,t);oe(v,f).result&&(e.stores[n].total+=1,e.stores[n].notifications.push(v))}}})),a},markNotificationAsUnread:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsUnread(i);return $("notifications.unread",r,"local"),e(O.default(function(e){var t={readAt:null};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.context,f=U.default(w.default("id",i),s);if(f>-1){var l=b.default(s[f],t);oe(l,c).result?(e.stores[n].unreadCount+=1,e.stores[n].notifications[f]=l):(e.stores[n].total-=Math.max(0,u-1),e.stores[n].notifications.splice(f,1))}else{var d=b.default(r,t);oe(d,c).result&&(e.stores[n].total+=1,e.stores[n].unreadCount+=1,e.stores[n].notifications.push(d))}}})),a},deleteNotification:function(r,n){void 0===n&&(n={});var o=t(),i=o.stores,a=o._repository,u=r.id,s=Promise.resolve(!0);return!1!==n.persist&&(s=a.delete(u),$("notifications.delete",r,"local")),e(O.default(function(e){for(var t in i){var r=i[t],n=r.notifications,o=r.total,a=r.unseenCount,s=r.unreadCount,c=U.default(w.default("id",u),n);if(c>-1){var f=n[c];f.seenAt||(e.stores[t].unseenCount=Math.max(0,a-1)),f.readAt||(e.stores[t].unreadCount=Math.max(0,s-1)),e.stores[t].total=Math.max(0,o-1),e.stores[t].notifications.splice(c,1)}}})),s},markAllAsSeen:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=n._repository,a=Promise.resolve(!0);return!1!==r.persist&&(a=i.markAllAsSeen(),$("notifications.seen.all",null,"local")),e(O.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unseenCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=b.default(r,{seenAt:Date.now()/1e3})})};for(var n in o)t(n)})),a},markAllAsRead:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=n._repository,a=Promise.resolve(!0);return!1!==r.persist&&(a=i.markAllAsRead(),$("notifications.read.all",null,"local")),e(O.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unreadCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=b.default(r,{readAt:Date.now()/1e3})})};for(var n in o)t(n)})),a}}});function ae(t,r,n){void 0===n&&(n={source:"any"}),e.useEffect(function(){var e=function(e){void 0===e&&(e={}),"remote"===n.source&&"remote"!==e.source||"local"===n.source&&"local"!==e.source||r(e.data,e.source)};return Z.on(t,e),function(){Z.off(t,e)}},[])}function ue(){var t,r=ie(),n=function(){return r.fetchAllStores({page:1},{reset:!0})};return t=Y(),e.useEffect(function(){return t.ws?function(e){var t=e.channel,r=function(e){var t=K.getState().serverURL+"/"+e.authUrl,r=z();return new R.Realtime({authUrl:t,authHeaders:r,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(e),n=function(){return $("wakeup",null,"local")};r.connection.on("disconnected",n),r.connection.on("suspended",n);var o=r.channels.get(t);return o.subscribe(ee),function(){o.unsubscribe(ee),o.detach(),r.connection.off("disconnected"),r.connection.off("suspended"),r.close()}}(t.ws):function(){}},[t.ws]),ae("wakeup",n),ae("notifications.new",function(){return r.fetchAllStores({page:1},{prepend:!0})},{source:"remote"}),ae("notifications.seen.all",function(){return r.markAllAsSeen({persist:!1})},{source:"remote"}),ae("notifications.read.all",function(){return r.markAllAsRead({persist:!1})},{source:"remote"}),ae("notifications.read",n,{source:"remote"}),ae("notifications.unread",n,{source:"remote"}),ae("notifications.delete",function(e){return r.deleteNotification(e,{persist:!1})},{source:"remote"}),null}var se=["serverURL"],ce=["children","stores","disableRealtime"];function fe(e){var t=e.serverURL,r=F(e,se);return t&&(r.serverURL=t),K.setState(r),r}function le(t){void 0===t&&(t="default");var r=ie(),n=r.stores,o=r.fetchStore,i=r.markAllAsSeen,a=r.markAllAsRead,u=Y(),s=n[t],c=function(e,r){return o(t,e,r)};return e.useEffect(function(){s&&u.lastFetchedAt&&!s.lastFetchedAt&&c({page:1})},[u.lastFetchedAt]),s?D({},s,{isEmpty:0===s.notifications.length,hasNextPage:s.currentPage<s.totalPages,fetch:c,fetchNextPage:function(e,r){return void 0===e&&(e={}),o(t,D({},e,{page:s.currentPage+1}),r)},markAllAsSeen:i,markAllAsRead:a}):null}function de(e){return e?ve(1e3*e):null}function ve(e){return I.default(e)}function he(e){if(M.default(e))return null;if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.warn('"customAttributes" is not valid JSON')}return e}function me(e){var t=ie(),r=t.markNotificationAsRead,n=t.markNotificationAsSeen,o=t.markNotificationAsUnread,i=t.deleteNotification;return D({},e,{customAttributes:he(e.customAttributes),readAt:de(e.readAt),seenAt:de(e.seenAt),sentAt:de(e.sentAt),archivedAt:de(e.archivedAt),isSeen:!M.default(e.seenAt),isRead:!M.default(e.readAt),isArchived:!M.default(e.archivedAt),sanitizedContent:e.content,markAsSeen:function(){return n(e)},markAsRead:function(){return r(e)},markAsUnread:function(){return o(e)},delete:function(){return i(e)}})}function pe(t,r){e.useEffect(function(){return function(){r?r(t):t.markAsSeen()}},[])}I.default.extend(L.default),I.default.extend(N.default),I.default.extend(_.default);var Ae=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/notification_preferences"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return E.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.update=function(e){return J(this.remotePathOrUrl,E.default.decamelizeKeys(e)).then(function(){return!0}).catch(function(){return!1})},e}(),Pe=S.default(function(e,t){return{categories:{},_repository:new Ae,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(D({},t.notificationPreferences,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}},save:function(r){try{var n=t(),o=n.categories;return n._repository.update({notificationPreferences:r}),e({categories:q.default(o,r.categories),lastFetchedAt:Date.now()}),Promise.resolve()}catch(e){return Promise.reject(e)}}}});exports.MagicBellProvider=function(t){var r=t.children,n=t.stores,o=void 0===n?[{id:"default",defaultQueryParams:{}}]:n,i=t.disableRealtime,a=F(t,ce);e.useState(function(){return fe(a)}),e.useState(function(){return function(e){var t={};return e.forEach(function(e){var r=e.defaults;t[e.id]=te(D({context:e.defaultQueryParams},void 0===r?{}:r))}),ie.setState({stores:t}),t}(o)});var u=Y();return e.useEffect(function(){u.lastFetchedAt||u.fetch()},[u]),g.default.createElement(g.default.Fragment,null,i?null:g.default.createElement(ue,null),r)},exports.RealtimeListener=ue,exports.buildStore=te,exports.clientSettings=K,exports.deleteAPI=H,exports.eventAggregator=Z,exports.fetchAPI=G,exports.postAPI=T,exports.pushEventAggregator=W,exports.putAPI=J,exports.secondsToDate=de,exports.toDate=ve,exports.toUnix=function(e){return I.default(e).unix()},exports.useBell=function(e){var t=le((void 0===e?{}:e).storeId);return t?D({},t,{markAllAsSeen:function(){return t&&t.unseenCount>0?null==t?void 0:t.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}}):null},exports.useConfig=Y,exports.useMagicBellEvent=ae,exports.useNotification=function(e,t){var r=me(e);return pe(r,t),r},exports.useNotificationFactory=me,exports.useNotificationPreferences=Pe,exports.useNotificationStoresCollection=ie,exports.useNotificationUnmount=pe,exports.useNotifications=le;
//# sourceMappingURL=magicbell-react-headless.js.map

@@ -1,2 +0,2 @@

import t,{useEffect as e,useState as r}from"react";import n from"zustand/vanilla";import o from"zustand";import s from"humps";import i from"axios";import a from"immer";import c from"ramda/src/findIndex";import l from"ramda/src/mergeRight";import u from"ramda/src/propEq";import d from"ramda/src/uniqBy";import f from"ramda/src/isNil";import*as m from"ably";import h from"mitt";import p from"dayjs";import A from"dayjs/plugin/localizedFormat";import y from"dayjs/plugin/relativeTime";import g from"dayjs/plugin/updateLocale";import P from"ramda/src/mergeDeepRight";function v(){return(v=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function w(t,e){if(null==t)return{};var r,n,o={},s=Object.keys(t);for(n=0;n<s.length;n++)e.indexOf(r=s[n])>=0||(o[r]=t[r]);return o}const S=n(()=>({apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}));function k(){const{apiKey:t,apiSecret:e,clientId:r,userEmail:n,userExternalId:o,userKey:s}=S.getState(),i={"X-MAGICBELL-CLIENT-ID":r,"X-MAGICBELL-API-KEY":t};return e&&(i["X-MAGICBELL-API-SECRET"]=e),n&&(i["X-MAGICBELL-USER-EMAIL"]=n),s&&(i["X-MAGICBELL-USER-HMAC"]=s),o&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=o),i}function U(t,e,r,n){const{serverURL:o}=S.getState(),s=k();return i({method:t,url:e,data:r,params:n,headers:s,baseURL:o}).then(t=>t.data,t=>{throw t})}function x(t,e={}){return U("get",t,void 0,e)}function E(t,e={},r={}){return U("post",t,e,r)}function R(t,e={}){return U("delete",t,void 0,e)}function O(t,e,r={}){return U("put",t,e,r)}class C{constructor(t="/config"){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}async get(){const t=await x(this.remotePathOrUrl);return s.camelizeKeys(t)}}const L=o((t,e)=>({channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new C,fetch:async()=>{const{_repository:r}=e(),n=await r.get();t(v({},n,{lastFetchedAt:Date.now()}))}}));function M(t){return l({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},t)}const b=["notifications"];function I(t,e){return t===e||t!=t&&e!=e}function N(t,e,r=I){const n=[];return Object.keys(e).forEach(o=>{const s=e[o];("read"===o&&!r(!f(t.readAt),s)||"seen"===o&&!r(!f(t.seenAt),s)||Object.hasOwnProperty.call(t,o)&&!r(t[o],s))&&n.push(o)}),{result:0===n.length,delta:n}}class _ extends class{constructor(t){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}async get(t){const e=`${this.remotePathOrUrl}/${t}`,r=await x(e);return s.camelizeKeys(r)}async findBy(t){try{const e=await x(this.remotePathOrUrl,t);return s.camelizeKeys(e)}catch(t){if(/Network Error/.test(t.message))return;throw t}}delete(t){return R(`${this.remotePathOrUrl}/${t}`).then(()=>!0).catch(()=>!1)}}{constructor(t="/notifications"){super(t)}markAsRead(t){return E(`${this.remotePathOrUrl}/${t}/read`).then(()=>!0).catch(()=>!1)}markAsUnread(t){return E(`${this.remotePathOrUrl}/${t}/unread`).then(()=>!0).catch(()=>!1)}markAllAsSeen(){return E(`${this.remotePathOrUrl}/seen`).then(()=>!0).catch(()=>!1)}markAllAsRead(){return E(`${this.remotePathOrUrl}/read`).then(()=>!0).catch(()=>!1)}}const D=o((t,e)=>({stores:{},_repository:new _,setStore:(e,r={},n={})=>{t(a(t=>{t.stores[e]=M(v({},n,{context:r}))}))},fetchStore:async(r,n={},o={})=>{const{stores:s,_repository:i}=e(),c=s[r];if(c){const e=await i.findBy(v({},c.context,n));if(!e)return;t(a(t=>{t.stores[r]=function(t,e,r={reset:!1}){const{notifications:n}=e,o=w(e,b),s=r.reset?n:d(t=>t.id,r.prepend?[...n,...t.notifications]:[...t.notifications,...n]);return v({context:t.context,notifications:s},o)}(c,v({},e,{lastFetchedAt:new Date}),o)}))}else console.error(`Store not found. Define a store with the ${r} ID`)},fetchAllStores:async(t={},r={})=>{const{stores:n,fetchStore:o}=e(),s=Object.keys(n).map(e=>o(e,t,r));await Promise.all(s)},markNotificationAsSeen:r=>{const{stores:n}=e(),o=r.id;t(a(t=>{for(const e in n){const{notifications:r,unseenCount:s}=n[e],i=c(u("id",o),r);i>-1&&(r[i].seenAt||(t.stores[e].unseenCount=Math.max(0,s-1),t.stores[e].notifications[i]=l(r[i],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:r=>{const{stores:n,_repository:o}=e(),{id:s}=r,i=o.markAsRead(s);return t(a(t=>{const e={readAt:Date.now()/1e3};for(const o in n){const{total:i,notifications:a,unreadCount:d,context:f}=n[o],m=c(u("id",s),a);if(m>-1){t.stores[o].unreadCount=Math.max(0,d-1);const r=l(a[m],e);N(r,f).result?t.stores[o].notifications[m]=r:(t.stores[o].total=Math.max(0,i-1),t.stores[o].notifications.splice(m,1))}else{const n=l(r,e);N(n,f).result&&(t.stores[o].total+=1,t.stores[o].notifications.push(n))}}})),i},markNotificationAsUnread:r=>{const{stores:n,_repository:o}=e(),{id:s}=r,i=o.markAsUnread(s);return t(a(t=>{const e={readAt:null};for(const o in n){const{total:i,notifications:a,context:d}=n[o],f=c(u("id",s),a);if(f>-1){const r=l(a[f],e);N(r,d).result?(t.stores[o].unreadCount+=1,t.stores[o].notifications[f]=r):(t.stores[o].total-=Math.max(0,i-1),t.stores[o].notifications.splice(f,1))}else{const n=l(r,e);N(n,d).result&&(t.stores[o].total+=1,t.stores[o].unreadCount+=1,t.stores[o].notifications.push(n))}}})),i},deleteNotification:(r,n={})=>{const{stores:o,_repository:s}=e(),i=r.id,l=!1===n.persist?Promise.resolve(!0):s.delete(i);return t(a(t=>{for(const e in o){const{notifications:r,total:n,unseenCount:s,unreadCount:a}=o[e],l=c(u("id",i),r);if(l>-1){const o=r[l];o.seenAt||(t.stores[e].unseenCount=Math.max(0,s-1)),o.readAt||(t.stores[e].unreadCount=Math.max(0,a-1)),t.stores[e].total=Math.max(0,n-1),t.stores[e].notifications.splice(l,1)}}})),l},markAllAsSeen:(r={persist:!0,updateModels:!0})=>{const{stores:n,_repository:o}=e(),s=!1!==r.persist?o.markAllAsSeen():Promise.resolve(!0);return t(a(t=>{for(const e in n){const{notifications:o}=n[e];t.stores[e].unseenCount=0,!1!==r.updateModels&&o.forEach((r,n)=>{t.stores[e].notifications[n]=l(r,{seenAt:Date.now()/1e3})})}})),s},markAllAsRead:(r={persist:!0,updateModels:!0})=>{const{stores:n,_repository:o}=e(),s=!1!==r.persist?o.markAllAsRead():Promise.resolve(!0);return t(a(t=>{for(const e in n){const{notifications:o}=n[e];t.stores[e].unreadCount=0,!1!==r.updateModels&&o.forEach((r,n)=>{t.stores[e].notifications[n]=l(r,{readAt:Date.now()/1e3})})}})),s}})),$=h();function F(t){const{clientId:e}=S.getState(),r=t.name.replace(/\//gi,"."),n=t.data;return n.client_id&&n.client_id===e?Promise.resolve():"string"==typeof n.id?"notifications.delete"===r?($.emit(r,n),Promise.resolve(!0)):(new _).get(n.id).then(t=>{$.emit(r,t.notification)}):($.emit(r,n),Promise.resolve())}function j(t,r){e(()=>($.on(t,r),()=>{$.off(t,r)}),[])}function K(){const t=D(),r=()=>t.fetchAllStores({page:1},{reset:!0});return function(){const t=L();e(()=>t.ws?function(t){const{channel:e}=t,r=function(t){const{serverURL:e}=S.getState(),r=`${e}/${t.authUrl}`,n=k();return new m.Realtime({authUrl:r,authHeaders:n,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(t),n=()=>$.emit("wakeup");r.connection.on("disconnected",n),r.connection.on("suspended",n);const o=r.channels.get(e);return o.subscribe(F),()=>{o.unsubscribe(F),o.detach(),r.connection.off("disconnected"),r.connection.off("suspended"),r.close()}}(t.ws):()=>{},[t.ws])}(),j("wakeup",r),j("notifications.new",()=>t.fetchAllStores({page:1},{prepend:!0})),j("notifications.seen.all",()=>t.markAllAsSeen({persist:!1})),j("notifications.read.all",()=>t.markAllAsRead({persist:!1})),j("notifications.read",r),j("notifications.unread",r),j("notifications.delete",e=>t.deleteNotification(e,{persist:!1})),null}const z=["serverURL"],B=["children","stores","disableRealtime"];function X(t){let{serverURL:e}=t;const r=w(t,z);return e&&(r.serverURL=e),S.setState(r),r}function G(n){let{children:o,stores:s=[{id:"default",defaultQueryParams:{}}],disableRealtime:i}=n,a=w(n,B);r(()=>X(a)),r(()=>function(t){const e={};return t.forEach(t=>{const{defaultQueryParams:r,defaults:n={}}=t;e[t.id]=M(v({context:r},n))}),D.setState({stores:e}),e}(s));const c=L();return e(()=>{c.lastFetchedAt||c.fetch()},[c]),t.createElement(t.Fragment,null,i?null:t.createElement(K,null),o)}function T(t="default"){const{stores:r,fetchStore:n,markAllAsSeen:o,markAllAsRead:s}=D(),i=L(),a=r[t],c=(e,r)=>n(t,e,r);return e(()=>{a&&i.lastFetchedAt&&!a.lastFetchedAt&&c({page:1})},[i.lastFetchedAt]),a?v({},a,{isEmpty:0===a.notifications.length,hasNextPage:a.currentPage<a.totalPages,fetch:c,fetchNextPage:(e={},r)=>n(t,v({},e,{page:a.currentPage+1}),r),markAllAsSeen:o,markAllAsRead:s}):null}function q({storeId:t}={}){const e=T(t);return e?v({},e,{markAllAsSeen:()=>e&&e.unseenCount>0?null==e?void 0:e.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}):null}function H(t){return t?J(1e3*t):null}function J(t){return p(t)}function Q(t){return p(t).unix()}function Y(t){if(f(t))return null;if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.warn('"customAttributes" is not valid JSON')}return t}function V(t){const{markNotificationAsRead:e,markNotificationAsSeen:r,markNotificationAsUnread:n,deleteNotification:o}=D();return v({},t,{customAttributes:Y(t.customAttributes),readAt:H(t.readAt),seenAt:H(t.seenAt),sentAt:H(t.sentAt),archivedAt:H(t.archivedAt),isSeen:!f(t.seenAt),isRead:!f(t.readAt),isArchived:!f(t.archivedAt),sanitizedContent:t.content,markAsSeen:()=>r(t),markAsRead:()=>e(t),markAsUnread:()=>n(t),delete:()=>o(t)})}function W(t,r){e(()=>()=>{r?r(t):t.markAsSeen()},[])}function Z(t,e){const r=V(t);return W(r,e),r}p.extend(A),p.extend(y),p.extend(g);class tt{constructor(t="/notification_preferences"){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}async get(){const t=await x(this.remotePathOrUrl);return s.camelizeKeys(t)}update(t){return O(this.remotePathOrUrl,s.decamelizeKeys(t)).then(()=>!0).catch(()=>!1)}}const et=o((t,e)=>({categories:{},_repository:new tt,fetch:async()=>{const{_repository:r}=e(),{notificationPreferences:n}=await r.get();t(v({},n,{lastFetchedAt:Date.now()}))},save:async r=>{const{_repository:n,categories:o}=e();n.update({notificationPreferences:r}),t({categories:P(o,r.categories),lastFetchedAt:Date.now()})}}));export{G as MagicBellProvider,K as RealtimeListener,M as buildStore,S as clientSettings,R as deleteAPI,x as fetchAPI,E as postAPI,$ as pushEventAggregator,O as putAPI,H as secondsToDate,J as toDate,Q as toUnix,q as useBell,L as useConfig,j as useMagicBellEvent,Z as useNotification,V as useNotificationFactory,et as useNotificationPreferences,D as useNotificationStoresCollection,W as useNotificationUnmount,T as useNotifications};
import t,{useEffect as e,useState as o}from"react";import r from"zustand/vanilla";import n from"zustand";import s from"humps";import i from"axios";import a from"immer";import c from"ramda/src/findIndex";import l from"ramda/src/mergeRight";import u from"ramda/src/propEq";import*as d from"ably";import f from"mitt";import m from"ramda/src/uniqBy";import h from"ramda/src/isNil";import p from"dayjs";import A from"dayjs/plugin/localizedFormat";import y from"dayjs/plugin/relativeTime";import g from"dayjs/plugin/updateLocale";import P from"ramda/src/mergeDeepRight";function v(){return(v=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var o=arguments[e];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(t[r]=o[r])}return t}).apply(this,arguments)}function w(t,e){if(null==t)return{};var o,r,n={},s=Object.keys(t);for(r=0;r<s.length;r++)e.indexOf(o=s[r])>=0||(n[o]=t[o]);return n}const S=r(()=>({apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}));function k(){const{apiKey:t,apiSecret:e,clientId:o,userEmail:r,userExternalId:n,userKey:s}=S.getState(),i={"X-MAGICBELL-CLIENT-ID":o,"X-MAGICBELL-API-KEY":t};return e&&(i["X-MAGICBELL-API-SECRET"]=e),r&&(i["X-MAGICBELL-USER-EMAIL"]=r),s&&(i["X-MAGICBELL-USER-HMAC"]=s),n&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=n),i}function U(t,e,o,r){const{serverURL:n}=S.getState(),s=k();return i({method:t,url:e,data:o,params:r,headers:s,baseURL:n}).then(t=>t.data,t=>{throw t})}function x(t,e={}){return U("get",t,void 0,e)}function E(t,e={},o={}){return U("post",t,e,o)}function R(t,e={}){return U("delete",t,void 0,e)}function O(t,e,o={}){return U("put",t,e,o)}class C{constructor(t="/config"){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}async get(){const t=await x(this.remotePathOrUrl);return s.camelizeKeys(t)}}const L=n((t,e)=>({channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new C,fetch:async()=>{const{_repository:o}=e(),r=await o.get();t(v({},r,{lastFetchedAt:Date.now()}))}}));class M extends class{constructor(t){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}async get(t){const e=`${this.remotePathOrUrl}/${t}`,o=await x(e);return s.camelizeKeys(o)}async findBy(t){try{const e=await x(this.remotePathOrUrl,t);return s.camelizeKeys(e)}catch(t){if(/Network Error/.test(t.message))return;throw t}}delete(t){return R(`${this.remotePathOrUrl}/${t}`).then(()=>!0).catch(()=>!1)}}{constructor(t="/notifications"){super(t)}markAsRead(t){return E(`${this.remotePathOrUrl}/${t}/read`).then(()=>!0).catch(()=>!1)}markAsUnread(t){return E(`${this.remotePathOrUrl}/${t}/unread`).then(()=>!0).catch(()=>!1)}markAllAsSeen(){return E(`${this.remotePathOrUrl}/seen`).then(()=>!0).catch(()=>!1)}markAllAsRead(){return E(`${this.remotePathOrUrl}/read`).then(()=>!0).catch(()=>!1)}}const b=f(),I=f();function N(t,e,o){"remote"===o&&b.emit(t,e),I.emit(t,{data:e,source:o})}function _(t){const{clientId:e}=S.getState(),o=t.name.replace(/\//gi,"."),r=t.data;return r.client_id&&r.client_id===e?Promise.resolve(!1):"string"==typeof r.id?"notifications.delete"===o?(N(o,r,"remote"),Promise.resolve(!0)):(new M).get(r.id).then(t=>(N(o,t.notification,"remote"),!0)):(N(o,r,"remote"),Promise.resolve(!0))}function D(t){return l({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},t)}const $=["notifications"];function F(t,e){return t===e||t!=t&&e!=e}function j(t,e,o=F){const r=[];return Object.keys(e).forEach(n=>{const s=e[n];("read"===n&&!o(!h(t.readAt),s)||"seen"===n&&!o(!h(t.seenAt),s)||Object.hasOwnProperty.call(t,n)&&!o(t[n],s))&&r.push(n)}),{result:0===r.length,delta:r}}const K=n((t,e)=>({stores:{},_repository:new M,setStore:(e,o={},r={})=>{t(a(t=>{t.stores[e]=D(v({},r,{context:o}))}))},fetchStore:async(o,r={},n={})=>{const{stores:s,_repository:i}=e(),c=s[o];if(c){const e=await i.findBy(v({},c.context,r));if(!e)return;t(a(t=>{t.stores[o]=function(t,e,o={reset:!1}){const{notifications:r}=e,n=w(e,$),s=o.reset?r:m(t=>t.id,o.prepend?[...r,...t.notifications]:[...t.notifications,...r]);return v({context:t.context,notifications:s},n)}(c,v({},e,{lastFetchedAt:new Date}),n)}))}else console.error(`Store not found. Define a store with the ${o} ID`)},fetchAllStores:async(t={},o={})=>{const{stores:r,fetchStore:n}=e(),s=Object.keys(r).map(e=>n(e,t,o));await Promise.all(s)},markNotificationAsSeen:o=>{const{stores:r}=e(),n=o.id;N("notifications.seen",o,"local"),t(a(t=>{for(const e in r){const{notifications:o,unseenCount:s}=r[e],i=c(u("id",n),o);i>-1&&(o[i].seenAt||(t.stores[e].unseenCount=Math.max(0,s-1),t.stores[e].notifications[i]=l(o[i],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:o=>{const{stores:r,_repository:n}=e(),{id:s}=o,i=n.markAsRead(s);return N("notifications.read",o,"local"),t(a(t=>{const e={readAt:Date.now()/1e3};for(const n in r){const{total:i,notifications:a,unreadCount:d,context:f}=r[n],m=c(u("id",s),a);if(m>-1){t.stores[n].unreadCount=Math.max(0,d-1);const o=l(a[m],e);j(o,f).result?t.stores[n].notifications[m]=o:(t.stores[n].total=Math.max(0,i-1),t.stores[n].notifications.splice(m,1))}else{const r=l(o,e);j(r,f).result&&(t.stores[n].total+=1,t.stores[n].notifications.push(r))}}})),i},markNotificationAsUnread:o=>{const{stores:r,_repository:n}=e(),{id:s}=o,i=n.markAsUnread(s);return N("notifications.unread",o,"local"),t(a(t=>{const e={readAt:null};for(const n in r){const{total:i,notifications:a,context:d}=r[n],f=c(u("id",s),a);if(f>-1){const o=l(a[f],e);j(o,d).result?(t.stores[n].unreadCount+=1,t.stores[n].notifications[f]=o):(t.stores[n].total-=Math.max(0,i-1),t.stores[n].notifications.splice(f,1))}else{const r=l(o,e);j(r,d).result&&(t.stores[n].total+=1,t.stores[n].unreadCount+=1,t.stores[n].notifications.push(r))}}})),i},deleteNotification:(o,r={})=>{const{stores:n,_repository:s}=e(),i=o.id;let l=Promise.resolve(!0);return!1!==r.persist&&(l=s.delete(i),N("notifications.delete",o,"local")),t(a(t=>{for(const e in n){const{notifications:o,total:r,unseenCount:s,unreadCount:a}=n[e],l=c(u("id",i),o);if(l>-1){const n=o[l];n.seenAt||(t.stores[e].unseenCount=Math.max(0,s-1)),n.readAt||(t.stores[e].unreadCount=Math.max(0,a-1)),t.stores[e].total=Math.max(0,r-1),t.stores[e].notifications.splice(l,1)}}})),l},markAllAsSeen:(o={persist:!0,updateModels:!0})=>{const{stores:r,_repository:n}=e();let s=Promise.resolve(!0);return!1!==o.persist&&(s=n.markAllAsSeen(),N("notifications.seen.all",null,"local")),t(a(t=>{for(const e in r){const{notifications:n}=r[e];t.stores[e].unseenCount=0,!1!==o.updateModels&&n.forEach((o,r)=>{t.stores[e].notifications[r]=l(o,{seenAt:Date.now()/1e3})})}})),s},markAllAsRead:(o={persist:!0,updateModels:!0})=>{const{stores:r,_repository:n}=e();let s=Promise.resolve(!0);return!1!==o.persist&&(s=n.markAllAsRead(),N("notifications.read.all",null,"local")),t(a(t=>{for(const e in r){const{notifications:n}=r[e];t.stores[e].unreadCount=0,!1!==o.updateModels&&n.forEach((o,r)=>{t.stores[e].notifications[r]=l(o,{readAt:Date.now()/1e3})})}})),s}}));function z(t,o,r={source:"any"}){e(()=>{const e=(t={})=>{"remote"===r.source&&"remote"!==t.source||"local"===r.source&&"local"!==t.source||o(t.data,t.source)};return I.on(t,e),()=>{I.off(t,e)}},[])}function B(){const t=K(),o=()=>t.fetchAllStores({page:1},{reset:!0});return function(){const t=L();e(()=>t.ws?function(t){const{channel:e}=t,o=function(t){const{serverURL:e}=S.getState(),o=`${e}/${t.authUrl}`,r=k();return new d.Realtime({authUrl:o,authHeaders:r,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(t),r=()=>N("wakeup",null,"local");o.connection.on("disconnected",r),o.connection.on("suspended",r);const n=o.channels.get(e);return n.subscribe(_),()=>{n.unsubscribe(_),n.detach(),o.connection.off("disconnected"),o.connection.off("suspended"),o.close()}}(t.ws):()=>{},[t.ws])}(),z("wakeup",o),z("notifications.new",()=>t.fetchAllStores({page:1},{prepend:!0}),{source:"remote"}),z("notifications.seen.all",()=>t.markAllAsSeen({persist:!1}),{source:"remote"}),z("notifications.read.all",()=>t.markAllAsRead({persist:!1}),{source:"remote"}),z("notifications.read",o,{source:"remote"}),z("notifications.unread",o,{source:"remote"}),z("notifications.delete",e=>t.deleteNotification(e,{persist:!1}),{source:"remote"}),null}const X=["serverURL"],G=["children","stores","disableRealtime"];function T(t){let{serverURL:e}=t;const o=w(t,X);return e&&(o.serverURL=e),S.setState(o),o}function q(r){let{children:n,stores:s=[{id:"default",defaultQueryParams:{}}],disableRealtime:i}=r,a=w(r,G);o(()=>T(a)),o(()=>function(t){const e={};return t.forEach(t=>{const{defaultQueryParams:o,defaults:r={}}=t;e[t.id]=D(v({context:o},r))}),K.setState({stores:e}),e}(s));const c=L();return e(()=>{c.lastFetchedAt||c.fetch()},[c]),t.createElement(t.Fragment,null,i?null:t.createElement(B,null),n)}function H(t="default"){const{stores:o,fetchStore:r,markAllAsSeen:n,markAllAsRead:s}=K(),i=L(),a=o[t],c=(e,o)=>r(t,e,o);return e(()=>{a&&i.lastFetchedAt&&!a.lastFetchedAt&&c({page:1})},[i.lastFetchedAt]),a?v({},a,{isEmpty:0===a.notifications.length,hasNextPage:a.currentPage<a.totalPages,fetch:c,fetchNextPage:(e={},o)=>r(t,v({},e,{page:a.currentPage+1}),o),markAllAsSeen:n,markAllAsRead:s}):null}function J({storeId:t}={}){const e=H(t);return e?v({},e,{markAllAsSeen:()=>e&&e.unseenCount>0?null==e?void 0:e.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}):null}function Q(t){return t?Y(1e3*t):null}function Y(t){return p(t)}function V(t){return p(t).unix()}function W(t){if(h(t))return null;if("string"==typeof t)try{return JSON.parse(t)}catch(t){console.warn('"customAttributes" is not valid JSON')}return t}function Z(t){const{markNotificationAsRead:e,markNotificationAsSeen:o,markNotificationAsUnread:r,deleteNotification:n}=K();return v({},t,{customAttributes:W(t.customAttributes),readAt:Q(t.readAt),seenAt:Q(t.seenAt),sentAt:Q(t.sentAt),archivedAt:Q(t.archivedAt),isSeen:!h(t.seenAt),isRead:!h(t.readAt),isArchived:!h(t.archivedAt),sanitizedContent:t.content,markAsSeen:()=>o(t),markAsRead:()=>e(t),markAsUnread:()=>r(t),delete:()=>n(t)})}function tt(t,o){e(()=>()=>{o?o(t):t.markAsSeen()},[])}function et(t,e){const o=Z(t);return tt(o,e),o}p.extend(A),p.extend(y),p.extend(g);class ot{constructor(t="/notification_preferences"){this.remotePathOrUrl=void 0,this.remotePathOrUrl=t}async get(){const t=await x(this.remotePathOrUrl);return s.camelizeKeys(t)}update(t){return O(this.remotePathOrUrl,s.decamelizeKeys(t)).then(()=>!0).catch(()=>!1)}}const rt=n((t,e)=>({categories:{},_repository:new ot,fetch:async()=>{const{_repository:o}=e(),{notificationPreferences:r}=await o.get();t(v({},r,{lastFetchedAt:Date.now()}))},save:async o=>{const{_repository:r,categories:n}=e();r.update({notificationPreferences:o}),t({categories:P(n,o.categories),lastFetchedAt:Date.now()})}}));export{q as MagicBellProvider,B as RealtimeListener,D as buildStore,S as clientSettings,R as deleteAPI,I as eventAggregator,x as fetchAPI,E as postAPI,b as pushEventAggregator,O as putAPI,Q as secondsToDate,Y as toDate,V as toUnix,J as useBell,L as useConfig,z as useMagicBellEvent,et as useNotification,Z as useNotificationFactory,rt as useNotificationPreferences,K as useNotificationStoresCollection,tt as useNotificationUnmount,H as useNotifications};
//# sourceMappingURL=magicbell-react-headless.modern.js.map

@@ -1,2 +0,2 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("zustand/vanilla"),require("zustand"),require("humps"),require("axios"),require("immer"),require("ramda/src/findIndex"),require("ramda/src/mergeRight"),require("ramda/src/propEq"),require("ramda/src/uniqBy"),require("ramda/src/isNil"),require("ably"),require("mitt"),require("dayjs"),require("dayjs/plugin/localizedFormat"),require("dayjs/plugin/relativeTime"),require("dayjs/plugin/updateLocale"),require("ramda/src/mergeDeepRight")):"function"==typeof define&&define.amd?define(["exports","react","zustand/vanilla","zustand","humps","axios","immer","ramda/src/findIndex","ramda/src/mergeRight","ramda/src/propEq","ramda/src/uniqBy","ramda/src/isNil","ably","mitt","dayjs","dayjs/plugin/localizedFormat","dayjs/plugin/relativeTime","dayjs/plugin/updateLocale","ramda/src/mergeDeepRight"],t):t((e||self).reactHeadless={},e.react,e.create,e.zustand,e.humps,e.axios,e.immer,e.findIndex,e.mergeRight,e.propEq,e.uniqBy,e.isNil,e.ably,e.mitt,e.dayjs,e.localizedFormat,e.relativeTime,e.updateLocale,e.mergeDeepRight)}(this,function(e,t,r,n,o,i,a,u,s,c,f,l,d,m,h,v,p,A,y){function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function P(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}var S=/*#__PURE__*/g(t),E=/*#__PURE__*/g(r),k=/*#__PURE__*/g(n),O=/*#__PURE__*/g(o),b=/*#__PURE__*/g(i),x=/*#__PURE__*/g(a),U=/*#__PURE__*/g(u),R=/*#__PURE__*/g(s),j=/*#__PURE__*/g(c),w=/*#__PURE__*/g(f),C=/*#__PURE__*/g(l),I=/*#__PURE__*/P(d),L=/*#__PURE__*/g(m),M=/*#__PURE__*/g(h),N=/*#__PURE__*/g(v),q=/*#__PURE__*/g(p),_=/*#__PURE__*/g(A),D=/*#__PURE__*/g(y);function z(){return(z=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function B(e,t){return(B=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function F(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)t.indexOf(r=i[n])>=0||(o[r]=e[r]);return o}var K=E.default(function(){return{apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}});function T(){var e=K.getState(),t=e.apiSecret,r=e.userEmail,n=e.userExternalId,o=e.userKey,i={"X-MAGICBELL-CLIENT-ID":e.clientId,"X-MAGICBELL-API-KEY":e.apiKey};return t&&(i["X-MAGICBELL-API-SECRET"]=t),r&&(i["X-MAGICBELL-USER-EMAIL"]=r),o&&(i["X-MAGICBELL-USER-HMAC"]=o),n&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=n),i}function X(e,t,r,n){var o=K.getState().serverURL,i=T();return b.default({method:e,url:t,data:r,params:n,headers:i,baseURL:o}).then(function(e){return e.data},function(e){throw e})}function G(e,t){return void 0===t&&(t={}),X("get",e,void 0,t)}function H(e,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),X("post",e,t,r)}function J(e,t){return void 0===t&&(t={}),X("delete",e,void 0,t)}function Q(e,t,r){return void 0===r&&(r={}),X("put",e,t,r)}var Y=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/config"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}return e.prototype.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},e}(),V=k.default(function(e,t){return{channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new Y,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(z({},t,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}}}});function W(e){return R.default({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},e)}var Z=["notifications"];function $(e,t){return e===t||e!=e&&t!=t}function ee(e,t,r){void 0===r&&(r=$);var n=[];return Object.keys(t).forEach(function(o){var i=t[o];("read"===o&&!r(!C.default(e.readAt),i)||"seen"===o&&!r(!C.default(e.seenAt),i)||Object.hasOwnProperty.call(e,o)&&!r(e[o],i))&&n.push(o)}),{result:0===n.length,delta:n}}var te=/*#__PURE__*/function(e){var t,r;function n(t){return void 0===t&&(t="/notifications"),e.call(this,t)||this}r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,B(t,r);var o=n.prototype;return o.markAsRead=function(e){return H(this.remotePathOrUrl+"/"+e+"/read").then(function(){return!0}).catch(function(){return!1})},o.markAsUnread=function(e){return H(this.remotePathOrUrl+"/"+e+"/unread").then(function(){return!0}).catch(function(){return!1})},o.markAllAsSeen=function(){return H(this.remotePathOrUrl+"/seen").then(function(){return!0}).catch(function(){return!1})},o.markAllAsRead=function(){return H(this.remotePathOrUrl+"/read").then(function(){return!0}).catch(function(){return!1})},n}(/*#__PURE__*/function(){function e(e){this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(e){try{return Promise.resolve(G(this.remotePathOrUrl+"/"+e)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.findBy=function(e){try{var t=this;return Promise.resolve(function(r,n){try{var o=Promise.resolve(G(t.remotePathOrUrl,e)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){if(!/Network Error/.test(e.message))throw e}))}catch(e){return Promise.reject(e)}},t.delete=function(e){return J(this.remotePathOrUrl+"/"+e).then(function(){return!0}).catch(function(){return!1})},e}()),re=k.default(function(e,t){return{stores:{},_repository:new te,setStore:function(t,r,n){void 0===r&&(r={}),void 0===n&&(n={}),e(x.default(function(e){e.stores[t]=W(z({},n,{context:r}))}))},fetchStore:function(r,n,o){void 0===n&&(n={}),void 0===o&&(o={});try{var i=t(),a=i._repository,u=i.stores[r];return Promise.resolve(function(){if(u)return Promise.resolve(a.findBy(z({},u.context,n))).then(function(t){t&&e(x.default(function(e){e.stores[r]=function(e,t,r){void 0===r&&(r={reset:!1});var n=t.notifications,o=F(t,Z),i=r.reset?n:w.default(function(e){return e.id},r.prepend?[].concat(n,e.notifications):[].concat(e.notifications,n));return z({context:e.context,notifications:i},o)}(u,z({},t,{lastFetchedAt:new Date}),o)}))});console.error("Store not found. Define a store with the "+r+" ID")}())}catch(e){return Promise.reject(e)}},fetchAllStores:function(e,r){void 0===e&&(e={}),void 0===r&&(r={});try{var n=t(),o=n.fetchStore,i=Object.keys(n.stores).map(function(t){return o(t,e,r)});return Promise.resolve(Promise.all(i)).then(function(){})}catch(e){return Promise.reject(e)}},markNotificationAsSeen:function(r){var n=t().stores,o=r.id;e(x.default(function(e){for(var t in n){var r=n[t],i=r.notifications,a=r.unseenCount,u=U.default(j.default("id",o),i);u>-1&&(i[u].seenAt||(e.stores[t].unseenCount=Math.max(0,a-1),e.stores[t].notifications[u]=R.default(i[u],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsRead(i);return e(x.default(function(e){var t={readAt:Date.now()/1e3};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.unreadCount,f=a.context,l=U.default(j.default("id",i),s);if(l>-1){e.stores[n].unreadCount=Math.max(0,c-1);var d=R.default(s[l],t);ee(d,f).result?e.stores[n].notifications[l]=d:(e.stores[n].total=Math.max(0,u-1),e.stores[n].notifications.splice(l,1))}else{var m=R.default(r,t);ee(m,f).result&&(e.stores[n].total+=1,e.stores[n].notifications.push(m))}}})),a},markNotificationAsUnread:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsUnread(i);return e(x.default(function(e){var t={readAt:null};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.context,f=U.default(j.default("id",i),s);if(f>-1){var l=R.default(s[f],t);ee(l,c).result?(e.stores[n].unreadCount+=1,e.stores[n].notifications[f]=l):(e.stores[n].total-=Math.max(0,u-1),e.stores[n].notifications.splice(f,1))}else{var d=R.default(r,t);ee(d,c).result&&(e.stores[n].total+=1,e.stores[n].unreadCount+=1,e.stores[n].notifications.push(d))}}})),a},deleteNotification:function(r,n){void 0===n&&(n={});var o=t(),i=o.stores,a=o._repository,u=r.id,s=!1===n.persist?Promise.resolve(!0):a.delete(u);return e(x.default(function(e){for(var t in i){var r=i[t],n=r.notifications,o=r.total,a=r.unseenCount,s=r.unreadCount,c=U.default(j.default("id",u),n);if(c>-1){var f=n[c];f.seenAt||(e.stores[t].unseenCount=Math.max(0,a-1)),f.readAt||(e.stores[t].unreadCount=Math.max(0,s-1)),e.stores[t].total=Math.max(0,o-1),e.stores[t].notifications.splice(c,1)}}})),s},markAllAsSeen:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=!1!==r.persist?n._repository.markAllAsSeen():Promise.resolve(!0);return e(x.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unseenCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=R.default(r,{seenAt:Date.now()/1e3})})};for(var n in o)t(n)})),i},markAllAsRead:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=!1!==r.persist?n._repository.markAllAsRead():Promise.resolve(!0);return e(x.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unreadCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=R.default(r,{readAt:Date.now()/1e3})})};for(var n in o)t(n)})),i}}}),ne=L.default();function oe(e){var t=K.getState().clientId,r=e.name.replace(/\//gi,"."),n=e.data;return n.client_id&&n.client_id===t?Promise.resolve():"string"==typeof n.id?"notifications.delete"===r?(ne.emit(r,n),Promise.resolve(!0)):(new te).get(n.id).then(function(e){ne.emit(r,e.notification)}):(ne.emit(r,n),Promise.resolve())}function ie(e,r){t.useEffect(function(){return ne.on(e,r),function(){ne.off(e,r)}},[])}function ae(){var e,r=re(),n=function(){return r.fetchAllStores({page:1},{reset:!0})};return e=V(),t.useEffect(function(){return e.ws?function(e){var t=e.channel,r=function(e){var t=K.getState().serverURL+"/"+e.authUrl,r=T();return new I.Realtime({authUrl:t,authHeaders:r,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(e),n=function(){return ne.emit("wakeup")};r.connection.on("disconnected",n),r.connection.on("suspended",n);var o=r.channels.get(t);return o.subscribe(oe),function(){o.unsubscribe(oe),o.detach(),r.connection.off("disconnected"),r.connection.off("suspended"),r.close()}}(e.ws):function(){}},[e.ws]),ie("wakeup",n),ie("notifications.new",function(){return r.fetchAllStores({page:1},{prepend:!0})}),ie("notifications.seen.all",function(){return r.markAllAsSeen({persist:!1})}),ie("notifications.read.all",function(){return r.markAllAsRead({persist:!1})}),ie("notifications.read",n),ie("notifications.unread",n),ie("notifications.delete",function(e){return r.deleteNotification(e,{persist:!1})}),null}var ue=["serverURL"],se=["children","stores","disableRealtime"];function ce(e){var t=e.serverURL,r=F(e,ue);return t&&(r.serverURL=t),K.setState(r),r}function fe(e){void 0===e&&(e="default");var r=re(),n=r.stores,o=r.fetchStore,i=r.markAllAsSeen,a=r.markAllAsRead,u=V(),s=n[e],c=function(t,r){return o(e,t,r)};return t.useEffect(function(){s&&u.lastFetchedAt&&!s.lastFetchedAt&&c({page:1})},[u.lastFetchedAt]),s?z({},s,{isEmpty:0===s.notifications.length,hasNextPage:s.currentPage<s.totalPages,fetch:c,fetchNextPage:function(t,r){return void 0===t&&(t={}),o(e,z({},t,{page:s.currentPage+1}),r)},markAllAsSeen:i,markAllAsRead:a}):null}function le(e){return e?de(1e3*e):null}function de(e){return M.default(e)}function me(e){if(C.default(e))return null;if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.warn('"customAttributes" is not valid JSON')}return e}function he(e){var t=re(),r=t.markNotificationAsRead,n=t.markNotificationAsSeen,o=t.markNotificationAsUnread,i=t.deleteNotification;return z({},e,{customAttributes:me(e.customAttributes),readAt:le(e.readAt),seenAt:le(e.seenAt),sentAt:le(e.sentAt),archivedAt:le(e.archivedAt),isSeen:!C.default(e.seenAt),isRead:!C.default(e.readAt),isArchived:!C.default(e.archivedAt),sanitizedContent:e.content,markAsSeen:function(){return n(e)},markAsRead:function(){return r(e)},markAsUnread:function(){return o(e)},delete:function(){return i(e)}})}function ve(e,r){t.useEffect(function(){return function(){r?r(e):e.markAsSeen()}},[])}M.default.extend(N.default),M.default.extend(q.default),M.default.extend(_.default);var pe=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/notification_preferences"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.update=function(e){return Q(this.remotePathOrUrl,O.default.decamelizeKeys(e)).then(function(){return!0}).catch(function(){return!1})},e}(),Ae=k.default(function(e,t){return{categories:{},_repository:new pe,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(z({},t.notificationPreferences,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}},save:function(r){try{var n=t(),o=n.categories;return n._repository.update({notificationPreferences:r}),e({categories:D.default(o,r.categories),lastFetchedAt:Date.now()}),Promise.resolve()}catch(e){return Promise.reject(e)}}}});e.MagicBellProvider=function(e){var r=e.children,n=e.stores,o=void 0===n?[{id:"default",defaultQueryParams:{}}]:n,i=e.disableRealtime,a=F(e,se);t.useState(function(){return ce(a)}),t.useState(function(){return function(e){var t={};return e.forEach(function(e){var r=e.defaults;t[e.id]=W(z({context:e.defaultQueryParams},void 0===r?{}:r))}),re.setState({stores:t}),t}(o)});var u=V();return t.useEffect(function(){u.lastFetchedAt||u.fetch()},[u]),S.default.createElement(S.default.Fragment,null,i?null:S.default.createElement(ae,null),r)},e.RealtimeListener=ae,e.buildStore=W,e.clientSettings=K,e.deleteAPI=J,e.fetchAPI=G,e.postAPI=H,e.pushEventAggregator=ne,e.putAPI=Q,e.secondsToDate=le,e.toDate=de,e.toUnix=function(e){return M.default(e).unix()},e.useBell=function(e){var t=fe((void 0===e?{}:e).storeId);return t?z({},t,{markAllAsSeen:function(){return t&&t.unseenCount>0?null==t?void 0:t.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}}):null},e.useConfig=V,e.useMagicBellEvent=ie,e.useNotification=function(e,t){var r=he(e);return ve(r,t),r},e.useNotificationFactory=he,e.useNotificationPreferences=Ae,e.useNotificationStoresCollection=re,e.useNotificationUnmount=ve,e.useNotifications=fe});
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("zustand/vanilla"),require("zustand"),require("humps"),require("axios"),require("immer"),require("ramda/src/findIndex"),require("ramda/src/mergeRight"),require("ramda/src/propEq"),require("ably"),require("mitt"),require("ramda/src/uniqBy"),require("ramda/src/isNil"),require("dayjs"),require("dayjs/plugin/localizedFormat"),require("dayjs/plugin/relativeTime"),require("dayjs/plugin/updateLocale"),require("ramda/src/mergeDeepRight")):"function"==typeof define&&define.amd?define(["exports","react","zustand/vanilla","zustand","humps","axios","immer","ramda/src/findIndex","ramda/src/mergeRight","ramda/src/propEq","ably","mitt","ramda/src/uniqBy","ramda/src/isNil","dayjs","dayjs/plugin/localizedFormat","dayjs/plugin/relativeTime","dayjs/plugin/updateLocale","ramda/src/mergeDeepRight"],t):t((e||self).reactHeadless={},e.react,e.create,e.zustand,e.humps,e.axios,e.immer,e.findIndex,e.mergeRight,e.propEq,e.ably,e.mitt,e.uniqBy,e.isNil,e.dayjs,e.localizedFormat,e.relativeTime,e.updateLocale,e.mergeDeepRight)}(this,function(e,t,r,n,o,i,a,u,s,c,f,l,d,m,v,h,p,A,y){function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function P(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}var S=/*#__PURE__*/g(t),E=/*#__PURE__*/g(r),k=/*#__PURE__*/g(n),O=/*#__PURE__*/g(o),b=/*#__PURE__*/g(i),x=/*#__PURE__*/g(a),U=/*#__PURE__*/g(u),R=/*#__PURE__*/g(s),j=/*#__PURE__*/g(c),w=/*#__PURE__*/P(f),C=/*#__PURE__*/g(l),I=/*#__PURE__*/g(d),L=/*#__PURE__*/g(m),M=/*#__PURE__*/g(v),N=/*#__PURE__*/g(h),q=/*#__PURE__*/g(p),_=/*#__PURE__*/g(A),D=/*#__PURE__*/g(y);function z(){return(z=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function B(e,t){return(B=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function F(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)t.indexOf(r=i[n])>=0||(o[r]=e[r]);return o}var K=E.default(function(){return{apiKey:"",apiSecret:void 0,userEmail:void 0,userExternalId:void 0,userKey:void 0,clientId:Math.random().toString(36).substring(2)+Date.now(),serverURL:"https://api.magicbell.com"}});function T(){var e=K.getState(),t=e.apiSecret,r=e.userEmail,n=e.userExternalId,o=e.userKey,i={"X-MAGICBELL-CLIENT-ID":e.clientId,"X-MAGICBELL-API-KEY":e.apiKey};return t&&(i["X-MAGICBELL-API-SECRET"]=t),r&&(i["X-MAGICBELL-USER-EMAIL"]=r),o&&(i["X-MAGICBELL-USER-HMAC"]=o),n&&(i["X-MAGICBELL-USER-EXTERNAL-ID"]=n),i}function X(e,t,r,n){var o=K.getState().serverURL,i=T();return b.default({method:e,url:t,data:r,params:n,headers:i,baseURL:o}).then(function(e){return e.data},function(e){throw e})}function G(e,t){return void 0===t&&(t={}),X("get",e,void 0,t)}function H(e,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),X("post",e,t,r)}function J(e,t){return void 0===t&&(t={}),X("delete",e,void 0,t)}function Q(e,t,r){return void 0===r&&(r={}),X("put",e,t,r)}var Y=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/config"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}return e.prototype.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},e}(),V=k.default(function(e,t){return{channels:void 0,inbox:void 0,ws:void 0,lastFetchedAt:void 0,_repository:new Y,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(z({},t,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}}}}),W=/*#__PURE__*/function(e){var t,r;function n(t){return void 0===t&&(t="/notifications"),e.call(this,t)||this}r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,B(t,r);var o=n.prototype;return o.markAsRead=function(e){return H(this.remotePathOrUrl+"/"+e+"/read").then(function(){return!0}).catch(function(){return!1})},o.markAsUnread=function(e){return H(this.remotePathOrUrl+"/"+e+"/unread").then(function(){return!0}).catch(function(){return!1})},o.markAllAsSeen=function(){return H(this.remotePathOrUrl+"/seen").then(function(){return!0}).catch(function(){return!1})},o.markAllAsRead=function(){return H(this.remotePathOrUrl+"/read").then(function(){return!0}).catch(function(){return!1})},n}(/*#__PURE__*/function(){function e(e){this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(e){try{return Promise.resolve(G(this.remotePathOrUrl+"/"+e)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.findBy=function(e){try{var t=this;return Promise.resolve(function(r,n){try{var o=Promise.resolve(G(t.remotePathOrUrl,e)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){if(!/Network Error/.test(e.message))throw e}))}catch(e){return Promise.reject(e)}},t.delete=function(e){return J(this.remotePathOrUrl+"/"+e).then(function(){return!0}).catch(function(){return!1})},e}()),Z=C.default(),$=C.default();function ee(e,t,r){"remote"===r&&Z.emit(e,t),$.emit(e,{data:t,source:r})}function te(e){var t=K.getState().clientId,r=e.name.replace(/\//gi,"."),n=e.data;return n.client_id&&n.client_id===t?Promise.resolve(!1):"string"==typeof n.id?"notifications.delete"===r?(ee(r,n,"remote"),Promise.resolve(!0)):(new W).get(n.id).then(function(e){return ee(r,e.notification,"remote"),!0}):(ee(r,n,"remote"),Promise.resolve(!0))}function re(e){return R.default({context:{},total:0,totalPages:0,perPage:0,currentPage:1,unreadCount:0,unseenCount:0,notifications:[]},e)}var ne=["notifications"];function oe(e,t){return e===t||e!=e&&t!=t}function ie(e,t,r){void 0===r&&(r=oe);var n=[];return Object.keys(t).forEach(function(o){var i=t[o];("read"===o&&!r(!L.default(e.readAt),i)||"seen"===o&&!r(!L.default(e.seenAt),i)||Object.hasOwnProperty.call(e,o)&&!r(e[o],i))&&n.push(o)}),{result:0===n.length,delta:n}}var ae=k.default(function(e,t){return{stores:{},_repository:new W,setStore:function(t,r,n){void 0===r&&(r={}),void 0===n&&(n={}),e(x.default(function(e){e.stores[t]=re(z({},n,{context:r}))}))},fetchStore:function(r,n,o){void 0===n&&(n={}),void 0===o&&(o={});try{var i=t(),a=i._repository,u=i.stores[r];return Promise.resolve(function(){if(u)return Promise.resolve(a.findBy(z({},u.context,n))).then(function(t){t&&e(x.default(function(e){e.stores[r]=function(e,t,r){void 0===r&&(r={reset:!1});var n=t.notifications,o=F(t,ne),i=r.reset?n:I.default(function(e){return e.id},r.prepend?[].concat(n,e.notifications):[].concat(e.notifications,n));return z({context:e.context,notifications:i},o)}(u,z({},t,{lastFetchedAt:new Date}),o)}))});console.error("Store not found. Define a store with the "+r+" ID")}())}catch(e){return Promise.reject(e)}},fetchAllStores:function(e,r){void 0===e&&(e={}),void 0===r&&(r={});try{var n=t(),o=n.fetchStore,i=Object.keys(n.stores).map(function(t){return o(t,e,r)});return Promise.resolve(Promise.all(i)).then(function(){})}catch(e){return Promise.reject(e)}},markNotificationAsSeen:function(r){var n=t().stores,o=r.id;ee("notifications.seen",r,"local"),e(x.default(function(e){for(var t in n){var r=n[t],i=r.notifications,a=r.unseenCount,u=U.default(j.default("id",o),i);u>-1&&(i[u].seenAt||(e.stores[t].unseenCount=Math.max(0,a-1),e.stores[t].notifications[u]=R.default(i[u],{seenAt:Date.now()/1e3})))}}))},markNotificationAsRead:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsRead(i);return ee("notifications.read",r,"local"),e(x.default(function(e){var t={readAt:Date.now()/1e3};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.unreadCount,f=a.context,l=U.default(j.default("id",i),s);if(l>-1){e.stores[n].unreadCount=Math.max(0,c-1);var d=R.default(s[l],t);ie(d,f).result?e.stores[n].notifications[l]=d:(e.stores[n].total=Math.max(0,u-1),e.stores[n].notifications.splice(l,1))}else{var m=R.default(r,t);ie(m,f).result&&(e.stores[n].total+=1,e.stores[n].notifications.push(m))}}})),a},markNotificationAsUnread:function(r){var n=t(),o=n.stores,i=r.id,a=n._repository.markAsUnread(i);return ee("notifications.unread",r,"local"),e(x.default(function(e){var t={readAt:null};for(var n in o){var a=o[n],u=a.total,s=a.notifications,c=a.context,f=U.default(j.default("id",i),s);if(f>-1){var l=R.default(s[f],t);ie(l,c).result?(e.stores[n].unreadCount+=1,e.stores[n].notifications[f]=l):(e.stores[n].total-=Math.max(0,u-1),e.stores[n].notifications.splice(f,1))}else{var d=R.default(r,t);ie(d,c).result&&(e.stores[n].total+=1,e.stores[n].unreadCount+=1,e.stores[n].notifications.push(d))}}})),a},deleteNotification:function(r,n){void 0===n&&(n={});var o=t(),i=o.stores,a=o._repository,u=r.id,s=Promise.resolve(!0);return!1!==n.persist&&(s=a.delete(u),ee("notifications.delete",r,"local")),e(x.default(function(e){for(var t in i){var r=i[t],n=r.notifications,o=r.total,a=r.unseenCount,s=r.unreadCount,c=U.default(j.default("id",u),n);if(c>-1){var f=n[c];f.seenAt||(e.stores[t].unseenCount=Math.max(0,a-1)),f.readAt||(e.stores[t].unreadCount=Math.max(0,s-1)),e.stores[t].total=Math.max(0,o-1),e.stores[t].notifications.splice(c,1)}}})),s},markAllAsSeen:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=n._repository,a=Promise.resolve(!0);return!1!==r.persist&&(a=i.markAllAsSeen(),ee("notifications.seen.all",null,"local")),e(x.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unseenCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=R.default(r,{seenAt:Date.now()/1e3})})};for(var n in o)t(n)})),a},markAllAsRead:function(r){void 0===r&&(r={persist:!0,updateModels:!0});var n=t(),o=n.stores,i=n._repository,a=Promise.resolve(!0);return!1!==r.persist&&(a=i.markAllAsRead(),ee("notifications.read.all",null,"local")),e(x.default(function(e){var t=function(t){var n=o[t].notifications;e.stores[t].unreadCount=0,!1!==r.updateModels&&n.forEach(function(r,n){e.stores[t].notifications[n]=R.default(r,{readAt:Date.now()/1e3})})};for(var n in o)t(n)})),a}}});function ue(e,r,n){void 0===n&&(n={source:"any"}),t.useEffect(function(){var t=function(e){void 0===e&&(e={}),"remote"===n.source&&"remote"!==e.source||"local"===n.source&&"local"!==e.source||r(e.data,e.source)};return $.on(e,t),function(){$.off(e,t)}},[])}function se(){var e,r=ae(),n=function(){return r.fetchAllStores({page:1},{reset:!0})};return e=V(),t.useEffect(function(){return e.ws?function(e){var t=e.channel,r=function(e){var t=K.getState().serverURL+"/"+e.authUrl,r=T();return new w.Realtime({authUrl:t,authHeaders:r,authMethod:"POST",log:{level:0},transports:["web_socket"]})}(e),n=function(){return ee("wakeup",null,"local")};r.connection.on("disconnected",n),r.connection.on("suspended",n);var o=r.channels.get(t);return o.subscribe(te),function(){o.unsubscribe(te),o.detach(),r.connection.off("disconnected"),r.connection.off("suspended"),r.close()}}(e.ws):function(){}},[e.ws]),ue("wakeup",n),ue("notifications.new",function(){return r.fetchAllStores({page:1},{prepend:!0})},{source:"remote"}),ue("notifications.seen.all",function(){return r.markAllAsSeen({persist:!1})},{source:"remote"}),ue("notifications.read.all",function(){return r.markAllAsRead({persist:!1})},{source:"remote"}),ue("notifications.read",n,{source:"remote"}),ue("notifications.unread",n,{source:"remote"}),ue("notifications.delete",function(e){return r.deleteNotification(e,{persist:!1})},{source:"remote"}),null}var ce=["serverURL"],fe=["children","stores","disableRealtime"];function le(e){var t=e.serverURL,r=F(e,ce);return t&&(r.serverURL=t),K.setState(r),r}function de(e){void 0===e&&(e="default");var r=ae(),n=r.stores,o=r.fetchStore,i=r.markAllAsSeen,a=r.markAllAsRead,u=V(),s=n[e],c=function(t,r){return o(e,t,r)};return t.useEffect(function(){s&&u.lastFetchedAt&&!s.lastFetchedAt&&c({page:1})},[u.lastFetchedAt]),s?z({},s,{isEmpty:0===s.notifications.length,hasNextPage:s.currentPage<s.totalPages,fetch:c,fetchNextPage:function(t,r){return void 0===t&&(t={}),o(e,z({},t,{page:s.currentPage+1}),r)},markAllAsSeen:i,markAllAsRead:a}):null}function me(e){return e?ve(1e3*e):null}function ve(e){return M.default(e)}function he(e){if(L.default(e))return null;if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.warn('"customAttributes" is not valid JSON')}return e}function pe(e){var t=ae(),r=t.markNotificationAsRead,n=t.markNotificationAsSeen,o=t.markNotificationAsUnread,i=t.deleteNotification;return z({},e,{customAttributes:he(e.customAttributes),readAt:me(e.readAt),seenAt:me(e.seenAt),sentAt:me(e.sentAt),archivedAt:me(e.archivedAt),isSeen:!L.default(e.seenAt),isRead:!L.default(e.readAt),isArchived:!L.default(e.archivedAt),sanitizedContent:e.content,markAsSeen:function(){return n(e)},markAsRead:function(){return r(e)},markAsUnread:function(){return o(e)},delete:function(){return i(e)}})}function Ae(e,r){t.useEffect(function(){return function(){r?r(e):e.markAsSeen()}},[])}M.default.extend(N.default),M.default.extend(q.default),M.default.extend(_.default);var ye=/*#__PURE__*/function(){function e(e){void 0===e&&(e="/notification_preferences"),this.remotePathOrUrl=void 0,this.remotePathOrUrl=e}var t=e.prototype;return t.get=function(){try{return Promise.resolve(G(this.remotePathOrUrl)).then(function(e){return O.default.camelizeKeys(e)})}catch(e){return Promise.reject(e)}},t.update=function(e){return Q(this.remotePathOrUrl,O.default.decamelizeKeys(e)).then(function(){return!0}).catch(function(){return!1})},e}(),ge=k.default(function(e,t){return{categories:{},_repository:new ye,fetch:function(){try{var r=t();return Promise.resolve(r._repository.get()).then(function(t){e(z({},t.notificationPreferences,{lastFetchedAt:Date.now()}))})}catch(e){return Promise.reject(e)}},save:function(r){try{var n=t(),o=n.categories;return n._repository.update({notificationPreferences:r}),e({categories:D.default(o,r.categories),lastFetchedAt:Date.now()}),Promise.resolve()}catch(e){return Promise.reject(e)}}}});e.MagicBellProvider=function(e){var r=e.children,n=e.stores,o=void 0===n?[{id:"default",defaultQueryParams:{}}]:n,i=e.disableRealtime,a=F(e,fe);t.useState(function(){return le(a)}),t.useState(function(){return function(e){var t={};return e.forEach(function(e){var r=e.defaults;t[e.id]=re(z({context:e.defaultQueryParams},void 0===r?{}:r))}),ae.setState({stores:t}),t}(o)});var u=V();return t.useEffect(function(){u.lastFetchedAt||u.fetch()},[u]),S.default.createElement(S.default.Fragment,null,i?null:S.default.createElement(se,null),r)},e.RealtimeListener=se,e.buildStore=re,e.clientSettings=K,e.deleteAPI=J,e.eventAggregator=$,e.fetchAPI=G,e.postAPI=H,e.pushEventAggregator=Z,e.putAPI=Q,e.secondsToDate=me,e.toDate=ve,e.toUnix=function(e){return M.default(e).unix()},e.useBell=function(e){var t=de((void 0===e?{}:e).storeId);return t?z({},t,{markAllAsSeen:function(){return t&&t.unseenCount>0?null==t?void 0:t.markAllAsSeen({updateModels:!1}):Promise.resolve(!0)}}):null},e.useConfig=V,e.useMagicBellEvent=ue,e.useNotification=function(e,t){var r=pe(e);return Ae(r,t),r},e.useNotificationFactory=pe,e.useNotificationPreferences=ge,e.useNotificationStoresCollection=ae,e.useNotificationUnmount=Ae,e.useNotifications=de});
//# sourceMappingURL=magicbell-react-headless.umd.js.map
{
"name": "@magicbell/react-headless",
"version": "2.5.1",
"version": "2.6.0",
"description": "Hooks to build a notification inbox",

@@ -43,3 +43,3 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com/)",

"prepare": "yarn build && husky install",
"start": "microbundle watch --jsx React.createElement",
"start": "microbundle watch --jsx React.createElement --no-compress",
"test": "TZ=America/New_York jest --collectCoverage --no-cache",

@@ -102,3 +102,3 @@ "test:watch": "TZ=America/New_York jest --watch",

"mitt": "^3.0.0",
"ramda": "^0.27.1",
"ramda": "^0.27.2",
"tslib": "^2.3.1",

@@ -105,0 +105,0 @@ "zustand": "^3.6.4"

@@ -182,5 +182,5 @@ [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)

This is a hook to listen to realtime events. Use it to be notified when a
realtime event happens, for example to play a sound when a new notification
arrives (read more [in our guides](https://magicbell.com/docs/react/play-sound-new-notification)).
This is a hook to listen to events, including realtime ones (generated in other tabs). Use it to be notified when a
realtime event happens, for example to play a sound when a new notification arrives
(read more [in our guides](https://magicbell.com/docs/react/play-sound-new-notification)).

@@ -207,2 +207,16 @@ ```javascript

You can also limit the source of the events you want to listen to:
- `remote`, to listen to events generated _in other tabs_ or the _MagicBell server_ only
- `local`, to listen to events generated _in the same tab_ only
- `any`, to listen to all events regardless of where it was generated
It is set to `any` by default.
```javascript
import { useMagicBellEvent } from '@magicbell/react-headless';
useMagicBellEvent('notifications.new', callbackFn, { source: 'remote' });
```
## useNotification

@@ -209,0 +223,0 @@

import { useEffect } from 'react';
import { connectToAbly, handleAblyEvent, pushEventAggregator } from '../lib/realtime';
import { connectToAbly, emitEvent, handleAblyEvent } from '../lib/realtime';
import useConfig from '../stores/config';

@@ -11,3 +10,3 @@ import { WebSocketConfig } from '../types/IRemoteConfig';

const emitWakeup = () => pushEventAggregator.emit('wakeup');
const emitWakeup = () => emitEvent('wakeup', null, 'local');
ablyClient.connection.on('disconnected', emitWakeup);

@@ -14,0 +13,0 @@ ablyClient.connection.on('suspended', emitWakeup);

import { useEffect } from 'react';
import { eventAggregator, EventSource } from '../lib/realtime';
import { pushEventAggregator } from '../lib/realtime';
interface HookOptions {
source: EventSource | 'any';
}
/**
* React hook to listen to realtime events.
* React hook to listen to events.
*
* @param event Name of the event
* @param handler
* @param handler Callback function
* @param options
*/
export default function useMagicBellEvent(event: string, handler: (data?: any) => void) {
export default function useMagicBellEvent(
event: string,
handler: (data?: unknown, source?: EventSource) => void,
options: HookOptions = { source: 'any' },
) {
useEffect(() => {
pushEventAggregator.on(event, handler);
const callback = (args: Partial<{ data: unknown; source: EventSource }> = {}) => {
if (options.source === 'remote' && args.source !== 'remote') return;
if (options.source === 'local' && args.source !== 'local') return;
handler(args.data, args.source);
};
eventAggregator.on(event, callback);
return () => {
pushEventAggregator.off(event, handler);
eventAggregator.off(event, callback);
};
}, []);
}

@@ -11,9 +11,9 @@ export { default as MagicBellProvider } from './components/MagicBellProvider';

export { secondsToDate, toDate, toUnix } from './lib/date';
export { pushEventAggregator } from './lib/realtime';
export { eventAggregator, pushEventAggregator } from './lib/realtime';
export { default as clientSettings } from './stores/clientSettings';
export { default as useConfig } from './stores/config';
export { default as useNotificationPreferences } from './stores/notification_preferences';
export { useNotificationStoresCollection } from './stores/notifications';
export { default as buildStore } from './stores/notifications/helpers/buildStore';
export { default as useNotificationPreferences } from './stores/notification_preferences';
export * from './types';
export { INotification as Notification } from './types';
import * as Ably from 'ably';
import mitt from 'mitt';
import clientSettings from '../stores/clientSettings';

@@ -9,5 +8,19 @@ import NotificationRepository from '../stores/notifications/NotificationRepository';

const pushEventAggregator = mitt();
export { pushEventAggregator };
// Note that we have two event emitters. An internal emitter which is used to
// keep the store in sync with remote events. For example to mark a notification
// as read when the user reads it in a different tab. And a public emitter, which
// is not used by our code, but can be used by consumers such as the embeddable.
// Technically, a single emitter could serve both goals, but that would involve
// publishing a breaking change.
// The internal emitter that used to keep the store in sync with remote
/** @deprecated */
export const pushEventAggregator = mitt();
// A public emitter, that's not used by our internal code, but can be used by
// consumers, such as the embeddable.
export const eventAggregator = mitt();
export type EventSource = 'local' | 'remote';
/**

@@ -35,2 +48,20 @@ * Open an authenticated connection to ably.

/**
* Publish events to the internal and public event emitter, based on the event source.
*
* @param event The name of the event.
* @param data The data object to pass along with the event.
* @param source The origin of the event, local for an action that's triggered by the user in the current tab, remote if it's an event from another instance that should be mirrored.
*/
export function emitEvent(event: string, data: unknown, source: EventSource) {
if (source === 'remote') {
// Only to maintain backwards compatibility.
pushEventAggregator.emit(event, data);
}
// wrap the argument in an object, as mitt is limited to a single argument,
// and we don't want to change the interface of `data`.
eventAggregator.emit(event, { data, source });
}
/**
* Publish an ably event to the push event emitter. If the push event contains

@@ -45,8 +76,9 @@ * the ID of a notification, this is fetched before emitting the event.

const eventData = event.data;
const isLoopbackEvent = eventData.client_id && eventData.client_id === clientId;
if (eventData.client_id && eventData.client_id === clientId) return Promise.resolve();
if (isLoopbackEvent) return Promise.resolve(false);
if (typeof eventData.id === 'string') {
if (eventName === 'notifications.delete') {
pushEventAggregator.emit(eventName, eventData);
emitEvent(eventName, eventData, 'remote');
return Promise.resolve(true);

@@ -56,3 +88,4 @@ } else {

return repository.get(eventData.id).then((data) => {
pushEventAggregator.emit(eventName, data.notification);
emitEvent(eventName, data.notification, 'remote');
return true;
});

@@ -62,4 +95,4 @@ }

pushEventAggregator.emit(eventName, eventData);
return Promise.resolve();
emitEvent(eventName, eventData, 'remote');
return Promise.resolve(true);
}

@@ -6,3 +6,3 @@ import produce from 'immer';

import create from 'zustand';
import { emitEvent } from '../../lib/realtime';
import { INotificationsStoresCollection, INotificationStore, IRemoteNotification } from '../../types';

@@ -61,2 +61,3 @@ import buildStore from './helpers/buildStore';

const notificationId = notification.id;
emitEvent('notifications.seen', notification, 'local');

@@ -88,2 +89,3 @@ set(

const promise = _repository.markAsRead(notificationId);
emitEvent('notifications.read', notification, 'local');

@@ -129,2 +131,3 @@ set(

const promise = _repository.markAsUnread(notificationId);
emitEvent('notifications.unread', notification, 'local');

@@ -169,4 +172,11 @@ set(

const notificationId = notification.id;
const promise = options.persist === false ? Promise.resolve(true) : _repository.delete(notificationId);
let promise = Promise.resolve(true);
// Do not persist the state is this op is a consequence of a remote event.
// Neither emit a local event.
if (options.persist !== false) {
promise = _repository.delete(notificationId);
emitEvent('notifications.delete', notification, 'local');
}
set(

@@ -196,4 +206,11 @@ produce<INotificationsStoresCollection>((draft) => {

const { stores, _repository } = get();
const promise = options.persist !== false ? _repository.markAllAsSeen() : Promise.resolve(true);
let promise = Promise.resolve(true);
// Do not persist the state is this op is a consequence of a remote event.
// Neither emit a local event.
if (options.persist !== false) {
promise = _repository.markAllAsSeen();
emitEvent('notifications.seen.all', null, 'local');
}
set(

@@ -220,4 +237,11 @@ produce<INotificationsStoresCollection>((draft) => {

const { stores, _repository } = get();
const promise = options.persist !== false ? _repository.markAllAsRead() : Promise.resolve(true);
let promise = Promise.resolve(true);
// Do not persist the state is this op is a consequence of a remote event.
// Neither emit a local event.
if (options.persist !== false) {
promise = _repository.markAllAsRead();
emitEvent('notifications.read.all', null, 'local');
}
set(

@@ -224,0 +248,0 @@ produce<INotificationsStoresCollection>((draft) => {

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc