@burdenoff/microfe-notification 2026.1023.1 → 2026.1029.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/NotificationBell.js +35 -34
- package/dist/components/NotificationBell.js.map +1 -1
- package/dist/components/NotificationCard.js +9 -9
- package/dist/graphql/global-client.js +43 -28
- package/dist/graphql/global-client.js.map +1 -1
- package/dist/hooks/useNotificationTopics.js +40 -38
- package/dist/hooks/useNotificationTopics.js.map +1 -1
- package/dist/hooks/useNotifications.js +140 -129
- package/dist/hooks/useNotifications.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/pages/CreateNotificationPage.js +5 -5
- package/dist/pages/NotificationCenterPage.js +5 -5
- package/dist/pages/NotificationPreferencesPage.js +43 -39
- package/dist/pages/NotificationPreferencesPage.js.map +1 -1
- package/dist/pages/NotificationTopicsPage.js +35 -31
- package/dist/pages/NotificationTopicsPage.js.map +1 -1
- package/dist/pages/TemplateEditorPage.js +5 -5
- package/package.json +1 -1
|
@@ -1,69 +1,70 @@
|
|
|
1
1
|
import { useNotification as e } from "../providers/NotificationProvider.js";
|
|
2
|
-
import {
|
|
3
|
-
import { useNotificationStore as
|
|
4
|
-
import { GetMyUnreadNotificationCountDocument as
|
|
5
|
-
import { useTr as
|
|
6
|
-
import { useCallback as
|
|
7
|
-
import { Bell as
|
|
8
|
-
import { jsx as
|
|
2
|
+
import { USER_NOTIFICATION_CONTEXT as t, getGlobalNotificationClient as n } from "../graphql/global-client.js";
|
|
3
|
+
import { useNotificationStore as r } from "../store/notificationStore.js";
|
|
4
|
+
import { GetMyUnreadNotificationCountDocument as i, UnreadCountUpdatedDocument as a } from "../generated/global-operations.js";
|
|
5
|
+
import { useTr as o } from "../shared/hooks/useTr.js";
|
|
6
|
+
import { useCallback as s, useEffect as c } from "react";
|
|
7
|
+
import { Bell as l } from "lucide-react";
|
|
8
|
+
import { jsx as u, jsxs as d } from "react/jsx-runtime";
|
|
9
9
|
//#region src/components/NotificationBell.tsx
|
|
10
|
-
function
|
|
11
|
-
let
|
|
10
|
+
function f({ onClick: f }) {
|
|
11
|
+
let p = o(), { authToken: m, apiGatewayUrl: h, currentUser: g } = e(), { unreadCount: _, togglePanel: v, setUnreadCount: y } = r(), b = s(async () => {
|
|
12
12
|
try {
|
|
13
|
-
let e = await
|
|
14
|
-
|
|
13
|
+
let e = await n(h ?? void 0, m ?? void 0).query({
|
|
14
|
+
context: t,
|
|
15
|
+
query: i,
|
|
15
16
|
variables: { filter: { channel: "IN_APP" } },
|
|
16
17
|
fetchPolicy: "network-only"
|
|
17
18
|
});
|
|
18
|
-
typeof e.data?.myUnreadNotificationCount == "number" &&
|
|
19
|
+
typeof e.data?.myUnreadNotificationCount == "number" && y(e.data.myUnreadNotificationCount);
|
|
19
20
|
} catch {}
|
|
20
21
|
}, [
|
|
22
|
+
h,
|
|
21
23
|
m,
|
|
22
|
-
|
|
23
|
-
v
|
|
24
|
+
y
|
|
24
25
|
]);
|
|
25
|
-
return
|
|
26
|
-
|
|
27
|
-
}, [
|
|
28
|
-
if (!
|
|
29
|
-
let e =
|
|
30
|
-
query:
|
|
31
|
-
variables: { userId:
|
|
26
|
+
return c(() => {
|
|
27
|
+
b();
|
|
28
|
+
}, [b]), c(() => {
|
|
29
|
+
if (!g?.id) return;
|
|
30
|
+
let e = n(h ?? void 0, m ?? void 0).subscribe({
|
|
31
|
+
query: a,
|
|
32
|
+
variables: { userId: g.id }
|
|
32
33
|
}).subscribe({
|
|
33
34
|
next: (e) => {
|
|
34
35
|
let t = e.data?.unreadCountUpdated;
|
|
35
|
-
typeof t == "number" &&
|
|
36
|
+
typeof t == "number" && y(t);
|
|
36
37
|
},
|
|
37
38
|
error: () => {}
|
|
38
39
|
});
|
|
39
40
|
return () => e.unsubscribe();
|
|
40
41
|
}, [
|
|
42
|
+
h,
|
|
41
43
|
m,
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
]), s(() => {
|
|
44
|
+
g?.id,
|
|
45
|
+
y
|
|
46
|
+
]), c(() => {
|
|
46
47
|
let e = () => {
|
|
47
|
-
document.visibilityState === "visible" &&
|
|
48
|
+
document.visibilityState === "visible" && b();
|
|
48
49
|
};
|
|
49
50
|
return document.addEventListener("visibilitychange", e), () => document.removeEventListener("visibilitychange", e);
|
|
50
|
-
}, [
|
|
51
|
+
}, [b]), /* @__PURE__ */ d("button", {
|
|
51
52
|
"data-tour": "notification-bell",
|
|
52
53
|
onClick: () => {
|
|
53
|
-
|
|
54
|
+
f ? f() : v();
|
|
54
55
|
},
|
|
55
56
|
className: "relative inline-flex items-center justify-center p-2 rounded-md hover:bg-bg-sunken transition-all duration-150",
|
|
56
|
-
"aria-label": `${
|
|
57
|
-
children: [/* @__PURE__ */ l
|
|
57
|
+
"aria-label": `${p("notifCommon.notifications", "Notifications")}${_ > 0 ? ` (${_} ${p("notifCommon.unread", "unread")})` : ""}`,
|
|
58
|
+
children: [/* @__PURE__ */ u(l, {
|
|
58
59
|
size: 20,
|
|
59
60
|
className: "text-primary"
|
|
60
|
-
}),
|
|
61
|
+
}), _ > 0 && /* @__PURE__ */ u("span", {
|
|
61
62
|
className: "absolute top-1 right-1 flex items-center justify-center min-w-[18px] h-[18px] px-1 text-xs font-semibold tabular-nums text-white bg-error rounded-full motion-safe:animate-vc-glow-pulse",
|
|
62
|
-
children:
|
|
63
|
+
children: _ > 99 ? "99+" : _
|
|
63
64
|
})]
|
|
64
65
|
});
|
|
65
66
|
}
|
|
66
67
|
//#endregion
|
|
67
|
-
export {
|
|
68
|
+
export { f as NotificationBell };
|
|
68
69
|
|
|
69
70
|
//# sourceMappingURL=NotificationBell.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationBell.js","names":[],"sources":["../../src/components/NotificationBell.tsx"],"sourcesContent":["import { useCallback, useEffect } from 'react';\nimport { Bell } from 'lucide-react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport {\n GetMyUnreadNotificationCountDocument,\n UnreadCountUpdatedDocument,\n} from '../generated/global-operations';\nimport type {\n GetMyUnreadNotificationCountQuery,\n UnreadCountUpdatedSubscription,\n} from '../generated/global-operations';\nimport { useNotificationStore } from '../store/notificationStore';\nimport { useTr } from '../shared/hooks/useTr';\n\n/**\n * Notification bell icon with unread count badge\n *\n * This component should be placed in the global header/navbar\n *\n * @example\n * ```tsx\n * <NotificationBell onClick={() => navigate('/notifications/center')} />\n * ```\n */\nexport function NotificationBell({ onClick }: { onClick?: () => void }) {\n const tr = useTr();\n const { authToken, apiGatewayUrl, currentUser } = useNotification();\n const { unreadCount, togglePanel, setUnreadCount } = useNotificationStore();\n\n const refreshUnreadCount = useCallback(async () => {\n try {\n const client = getGlobalNotificationClient(\n apiGatewayUrl ?? undefined,\n authToken ?? undefined\n );\n const result = await client.query<GetMyUnreadNotificationCountQuery>({\n query: GetMyUnreadNotificationCountDocument,\n variables: { filter: { channel: 'IN_APP' } },\n fetchPolicy: 'network-only',\n });\n\n if (typeof result.data?.myUnreadNotificationCount === 'number') {\n setUnreadCount(result.data.myUnreadNotificationCount);\n }\n } catch {\n // Keep bell resilient; do not surface errors here.\n }\n }, [apiGatewayUrl, authToken, setUnreadCount]);\n\n useEffect(() => {\n refreshUnreadCount();\n }, [refreshUnreadCount]);\n\n useEffect(() => {\n if (!currentUser?.id) return undefined;\n\n const client = getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n const subscription = client\n .subscribe<UnreadCountUpdatedSubscription>({\n query: UnreadCountUpdatedDocument,\n variables: { userId: currentUser.id },\n })\n .subscribe({\n next: (result) => {\n const nextCount = result.data?.unreadCountUpdated;\n if (typeof nextCount === 'number') {\n setUnreadCount(nextCount);\n }\n },\n error: () => {\n // Keep the header resilient; visibility refresh below handles recovery.\n },\n });\n\n return () => subscription.unsubscribe();\n }, [apiGatewayUrl, authToken, currentUser?.id, setUnreadCount]);\n\n useEffect(() => {\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'visible') {\n refreshUnreadCount();\n }\n };\n\n document.addEventListener('visibilitychange', handleVisibilityChange);\n return () => document.removeEventListener('visibilitychange', handleVisibilityChange);\n }, [refreshUnreadCount]);\n\n const handleClick = () => {\n if (onClick) {\n onClick();\n } else {\n togglePanel();\n }\n };\n\n return (\n <button\n data-tour=\"notification-bell\"\n onClick={handleClick}\n className=\"relative inline-flex items-center justify-center p-2 rounded-md hover:bg-bg-sunken transition-all duration-150\"\n aria-label={`${tr('notifCommon.notifications', 'Notifications')}${unreadCount > 0 ? ` (${unreadCount} ${tr('notifCommon.unread', 'unread')})` : ''}`}\n >\n <Bell size={20} className=\"text-primary\" />\n {unreadCount > 0 && (\n <span className=\"absolute top-1 right-1 flex items-center justify-center min-w-[18px] h-[18px] px-1 text-xs font-semibold tabular-nums text-white bg-error rounded-full motion-safe:animate-vc-glow-pulse\">\n {unreadCount > 99 ? '99+' : unreadCount}\n </span>\n )}\n </button>\n );\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgB,EAAiB,EAAE,cAAqC;CACtE,IAAM,IAAK,GAAO,EACZ,EAAE,cAAW,kBAAe,mBAAgB,GAAiB,EAC7D,EAAE,gBAAa,gBAAa,sBAAmB,GAAsB,EAErE,IAAqB,EAAY,YAAY;AACjD,MAAI;GAKF,IAAM,IAAS,MAJA,EACb,KAAiB,KAAA,GACjB,KAAa,KAAA,EACd,CAC2B,MAAyC;IACnE,OAAO;IACP,WAAW,EAAE,QAAQ,EAAE,SAAS,UAAU,EAAE;IAC5C,aAAa;IACd,CAAC;AAEF,GAAI,OAAO,EAAO,MAAM,6BAA8B,YACpD,EAAe,EAAO,KAAK,0BAA0B;UAEjD;IAGP;EAAC;EAAe;EAAW;EAAe,CAAC;AAiD9C,QA/CA,QAAgB;AACd,KAAoB;IACnB,CAAC,EAAmB,CAAC,EAExB,QAAgB;AACd,MAAI,CAAC,GAAa,GAAI;EAGtB,IAAM,IADS,EAA4B,KAAiB,KAAA,GAAW,KAAa,KAAA,EAAU,CAE3F,UAA0C;GACzC,OAAO;GACP,WAAW,EAAE,QAAQ,EAAY,IAAI;GACtC,CAAC,CACD,UAAU;GACT,OAAO,MAAW;IAChB,IAAM,IAAY,EAAO,MAAM;AAC/B,IAAI,OAAO,KAAc,YACvB,EAAe,EAAU;;GAG7B,aAAa;GAGd,CAAC;AAEJ,eAAa,EAAa,aAAa;IACtC;EAAC;EAAe;EAAW,GAAa;EAAI;EAAe,CAAC,EAE/D,QAAgB;EACd,IAAM,UAA+B;AACnC,GAAI,SAAS,oBAAoB,aAC/B,GAAoB;;AAKxB,SADA,SAAS,iBAAiB,oBAAoB,EAAuB,QACxD,SAAS,oBAAoB,oBAAoB,EAAuB;IACpF,CAAC,EAAmB,CAAC,EAWtB,kBAAC,UAAD;EACE,aAAU;EACV,eAXsB;AACxB,GAAI,IACF,GAAS,GAET,GAAa;;EAQb,WAAU;EACV,cAAY,GAAG,EAAG,6BAA6B,gBAAgB,GAAG,IAAc,IAAI,KAAK,EAAY,GAAG,EAAG,sBAAsB,SAAS,CAAC,KAAK;YAJlJ,CAME,kBAAC,GAAD;GAAM,MAAM;GAAI,WAAU;GAAiB,CAAA,EAC1C,IAAc,KACb,kBAAC,QAAD;GAAM,WAAU;aACb,IAAc,KAAK,QAAQ;GACvB,CAAA,CAEF"}
|
|
1
|
+
{"version":3,"file":"NotificationBell.js","names":[],"sources":["../../src/components/NotificationBell.tsx"],"sourcesContent":["import { useCallback, useEffect } from 'react';\nimport { Bell } from 'lucide-react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient, USER_NOTIFICATION_CONTEXT } from '../graphql/global-client';\nimport {\n GetMyUnreadNotificationCountDocument,\n UnreadCountUpdatedDocument,\n} from '../generated/global-operations';\nimport type {\n GetMyUnreadNotificationCountQuery,\n UnreadCountUpdatedSubscription,\n} from '../generated/global-operations';\nimport { useNotificationStore } from '../store/notificationStore';\nimport { useTr } from '../shared/hooks/useTr';\n\n/**\n * Notification bell icon with unread count badge\n *\n * This component should be placed in the global header/navbar\n *\n * @example\n * ```tsx\n * <NotificationBell onClick={() => navigate('/notifications/center')} />\n * ```\n */\nexport function NotificationBell({ onClick }: { onClick?: () => void }) {\n const tr = useTr();\n const { authToken, apiGatewayUrl, currentUser } = useNotification();\n const { unreadCount, togglePanel, setUnreadCount } = useNotificationStore();\n\n const refreshUnreadCount = useCallback(async () => {\n try {\n const client = getGlobalNotificationClient(\n apiGatewayUrl ?? undefined,\n authToken ?? undefined\n );\n const result = await client.query<GetMyUnreadNotificationCountQuery>({\n context: USER_NOTIFICATION_CONTEXT,\n query: GetMyUnreadNotificationCountDocument,\n variables: { filter: { channel: 'IN_APP' } },\n fetchPolicy: 'network-only',\n });\n\n if (typeof result.data?.myUnreadNotificationCount === 'number') {\n setUnreadCount(result.data.myUnreadNotificationCount);\n }\n } catch {\n // Keep bell resilient; do not surface errors here.\n }\n }, [apiGatewayUrl, authToken, setUnreadCount]);\n\n useEffect(() => {\n refreshUnreadCount();\n }, [refreshUnreadCount]);\n\n useEffect(() => {\n if (!currentUser?.id) return undefined;\n\n const client = getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n const subscription = client\n .subscribe<UnreadCountUpdatedSubscription>({\n query: UnreadCountUpdatedDocument,\n variables: { userId: currentUser.id },\n })\n .subscribe({\n next: (result) => {\n const nextCount = result.data?.unreadCountUpdated;\n if (typeof nextCount === 'number') {\n setUnreadCount(nextCount);\n }\n },\n error: () => {\n // Keep the header resilient; visibility refresh below handles recovery.\n },\n });\n\n return () => subscription.unsubscribe();\n }, [apiGatewayUrl, authToken, currentUser?.id, setUnreadCount]);\n\n useEffect(() => {\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'visible') {\n refreshUnreadCount();\n }\n };\n\n document.addEventListener('visibilitychange', handleVisibilityChange);\n return () => document.removeEventListener('visibilitychange', handleVisibilityChange);\n }, [refreshUnreadCount]);\n\n const handleClick = () => {\n if (onClick) {\n onClick();\n } else {\n togglePanel();\n }\n };\n\n return (\n <button\n data-tour=\"notification-bell\"\n onClick={handleClick}\n className=\"relative inline-flex items-center justify-center p-2 rounded-md hover:bg-bg-sunken transition-all duration-150\"\n aria-label={`${tr('notifCommon.notifications', 'Notifications')}${unreadCount > 0 ? ` (${unreadCount} ${tr('notifCommon.unread', 'unread')})` : ''}`}\n >\n <Bell size={20} className=\"text-primary\" />\n {unreadCount > 0 && (\n <span className=\"absolute top-1 right-1 flex items-center justify-center min-w-[18px] h-[18px] px-1 text-xs font-semibold tabular-nums text-white bg-error rounded-full motion-safe:animate-vc-glow-pulse\">\n {unreadCount > 99 ? '99+' : unreadCount}\n </span>\n )}\n </button>\n );\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgB,EAAiB,EAAE,cAAqC;CACtE,IAAM,IAAK,GAAO,EACZ,EAAE,cAAW,kBAAe,mBAAgB,GAAiB,EAC7D,EAAE,gBAAa,gBAAa,sBAAmB,GAAsB,EAErE,IAAqB,EAAY,YAAY;AACjD,MAAI;GAKF,IAAM,IAAS,MAJA,EACb,KAAiB,KAAA,GACjB,KAAa,KAAA,EACd,CAC2B,MAAyC;IACnE,SAAS;IACT,OAAO;IACP,WAAW,EAAE,QAAQ,EAAE,SAAS,UAAU,EAAE;IAC5C,aAAa;IACd,CAAC;AAEF,GAAI,OAAO,EAAO,MAAM,6BAA8B,YACpD,EAAe,EAAO,KAAK,0BAA0B;UAEjD;IAGP;EAAC;EAAe;EAAW;EAAe,CAAC;AAiD9C,QA/CA,QAAgB;AACd,KAAoB;IACnB,CAAC,EAAmB,CAAC,EAExB,QAAgB;AACd,MAAI,CAAC,GAAa,GAAI;EAGtB,IAAM,IADS,EAA4B,KAAiB,KAAA,GAAW,KAAa,KAAA,EAAU,CAE3F,UAA0C;GACzC,OAAO;GACP,WAAW,EAAE,QAAQ,EAAY,IAAI;GACtC,CAAC,CACD,UAAU;GACT,OAAO,MAAW;IAChB,IAAM,IAAY,EAAO,MAAM;AAC/B,IAAI,OAAO,KAAc,YACvB,EAAe,EAAU;;GAG7B,aAAa;GAGd,CAAC;AAEJ,eAAa,EAAa,aAAa;IACtC;EAAC;EAAe;EAAW,GAAa;EAAI;EAAe,CAAC,EAE/D,QAAgB;EACd,IAAM,UAA+B;AACnC,GAAI,SAAS,oBAAoB,aAC/B,GAAoB;;AAKxB,SADA,SAAS,iBAAiB,oBAAoB,EAAuB,QACxD,SAAS,oBAAoB,oBAAoB,EAAuB;IACpF,CAAC,EAAmB,CAAC,EAWtB,kBAAC,UAAD;EACE,aAAU;EACV,eAXsB;AACxB,GAAI,IACF,GAAS,GAET,GAAa;;EAQb,WAAU;EACV,cAAY,GAAG,EAAG,6BAA6B,gBAAgB,GAAG,IAAc,IAAI,KAAK,EAAY,GAAG,EAAG,sBAAsB,SAAS,CAAC,KAAK;YAJlJ,CAME,kBAAC,GAAD;GAAM,MAAM;GAAI,WAAU;GAAiB,CAAA,EAC1C,IAAc,KACb,kBAAC,QAAD;GAAM,WAAU;aACb,IAAc,KAAK,QAAQ;GACvB,CAAA,CAEF"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { useNotificationAnalytics as e } from "../hooks/useNotificationAnalytics.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { formatRelativeTime as t, getNotificationTypeIcon as n, getPriorityColor as r, getPriorityIcon as i, truncateText as a } from "../utils/index.js";
|
|
3
|
+
import { useTr as o } from "../shared/hooks/useTr.js";
|
|
4
4
|
import { nativeImpact as s, nativeOpenUrl as c } from "../utils/nativeBridge.js";
|
|
5
5
|
import { navigateInApp as l } from "../utils/inAppNavigation.js";
|
|
6
6
|
import { ExternalLink as u, X as d } from "lucide-react";
|
|
7
7
|
import { Fragment as f, jsx as p, jsxs as m } from "react/jsx-runtime";
|
|
8
8
|
//#region src/components/NotificationCard.tsx
|
|
9
9
|
function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClick: y, showArchivedState: b = !1, compact: x = !1, analyticsSource: S = "center" }) {
|
|
10
|
-
let C =
|
|
10
|
+
let C = o(), { trackNotificationOpened: w } = e(), T = !h.readAt, E = !!h.archivedAt, D = () => {
|
|
11
11
|
w(h, S, "card"), y && y(h), T && g && g(h.id);
|
|
12
12
|
}, O = (e) => {
|
|
13
13
|
e.stopPropagation(), _ && _(h.id);
|
|
@@ -39,16 +39,16 @@ function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClic
|
|
|
39
39
|
/* @__PURE__ */ p("span", {
|
|
40
40
|
className: "text-base",
|
|
41
41
|
"aria-hidden": "true",
|
|
42
|
-
children:
|
|
42
|
+
children: n(h.type)
|
|
43
43
|
}),
|
|
44
44
|
/* @__PURE__ */ p("h3", {
|
|
45
45
|
className: `text-sm truncate ${T ? "font-bold text-primary" : "font-medium text-secondary"}`,
|
|
46
|
-
children: x ?
|
|
46
|
+
children: x ? a(h.title, 60) : h.title
|
|
47
47
|
}),
|
|
48
48
|
/* @__PURE__ */ p("span", {
|
|
49
49
|
className: "text-xs",
|
|
50
50
|
"aria-label": `Priority: ${h.priority}`,
|
|
51
|
-
children:
|
|
51
|
+
children: i(h.priority)
|
|
52
52
|
})
|
|
53
53
|
]
|
|
54
54
|
}), _ && /* @__PURE__ */ p("button", {
|
|
@@ -72,7 +72,7 @@ function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClic
|
|
|
72
72
|
}),
|
|
73
73
|
/* @__PURE__ */ p("p", {
|
|
74
74
|
className: `text-sm text-secondary ${x ? "line-clamp-2" : ""}`,
|
|
75
|
-
children: x ?
|
|
75
|
+
children: x ? a(h.body, 120) : h.body
|
|
76
76
|
}),
|
|
77
77
|
h.topic && /* @__PURE__ */ p("div", {
|
|
78
78
|
className: "mt-2 inline-flex items-center rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary",
|
|
@@ -94,14 +94,14 @@ function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClic
|
|
|
94
94
|
className: "flex items-center gap-2 text-xs text-tertiary",
|
|
95
95
|
children: [
|
|
96
96
|
/* @__PURE__ */ p("span", {
|
|
97
|
-
className:
|
|
97
|
+
className: r(h.priority),
|
|
98
98
|
children: h.priority
|
|
99
99
|
}),
|
|
100
100
|
b && E && /* @__PURE__ */ m(f, { children: [/* @__PURE__ */ p("span", { children: "•" }), /* @__PURE__ */ p("span", { children: C("notifCommon.archived", "Archived") })] }),
|
|
101
101
|
/* @__PURE__ */ p("span", { children: "•" }),
|
|
102
102
|
/* @__PURE__ */ p("time", {
|
|
103
103
|
dateTime: h.createdAt,
|
|
104
|
-
children:
|
|
104
|
+
children: t(h.createdAt, C)
|
|
105
105
|
})
|
|
106
106
|
]
|
|
107
107
|
}), h.actionUrl && /* @__PURE__ */ m("button", {
|
|
@@ -5,28 +5,29 @@ import { ApolloClient as r, ApolloLink as i, HttpLink as a, InMemoryCache as o,
|
|
|
5
5
|
import { setContext as u } from "@apollo/client/link/context";
|
|
6
6
|
import { onError as d } from "@apollo/client/link/error";
|
|
7
7
|
import { isAuthNetworkError as f, redirectToLogin as p } from "@burdenoff/fe-libs/shared/utils";
|
|
8
|
+
import { getStoredOrganizationId as m, getStoredWorkspaceId as h, getStoredWorkspaceToken as g, isWorkspaceTokenValidForContext as _ } from "@burdenoff/fe-libs/shared/graphql";
|
|
8
9
|
//#region src/graphql/global-client.ts
|
|
9
|
-
function
|
|
10
|
+
function v(e = []) {
|
|
10
11
|
return e.some((e) => {
|
|
11
12
|
let t = typeof e.extensions?.code == "string" ? e.extensions.code : "", n = typeof e.extensions?.errorCode == "string" ? e.extensions.errorCode : "", r = (e.message ?? "").toLowerCase();
|
|
12
13
|
return t === "UNAUTHENTICATED" || n === "TOKEN_EXPIRED" || r.includes("token_expired") || r.includes("token expired") || r.includes("session expired") || r.includes("unauthorized") || r.includes("unauthenticated") || r.includes("authentication required") || r.includes("workspace context missing");
|
|
13
14
|
});
|
|
14
15
|
}
|
|
15
|
-
function
|
|
16
|
+
function y(t) {
|
|
16
17
|
let n = e(t);
|
|
17
18
|
return n.kind === "OperationDefinition" && n.operation === "mutation";
|
|
18
19
|
}
|
|
19
|
-
function
|
|
20
|
+
function b(e) {
|
|
20
21
|
let t = e.errors;
|
|
21
22
|
return Array.isArray(t) && t.length > 0;
|
|
22
23
|
}
|
|
23
|
-
function
|
|
24
|
+
function x(e) {
|
|
24
25
|
return new i((t, n) => {
|
|
25
|
-
let r =
|
|
26
|
+
let r = y(t.query) && t.getContext().autoRefreshAfterMutation !== !1 && t.getContext().skipMutationAutoRefresh !== !0;
|
|
26
27
|
return new s((i) => {
|
|
27
28
|
let a = n(t).subscribe({
|
|
28
29
|
next: (t) => {
|
|
29
|
-
i.next(t), !(!r ||
|
|
30
|
+
i.next(t), !(!r || b(t)) && e()?.refetchQueries({ include: "active" });
|
|
30
31
|
},
|
|
31
32
|
error: (e) => {
|
|
32
33
|
i.error(e);
|
|
@@ -41,43 +42,57 @@ function _(e) {
|
|
|
41
42
|
});
|
|
42
43
|
});
|
|
43
44
|
}
|
|
44
|
-
var
|
|
45
|
-
function
|
|
45
|
+
var S = null, C = null, w = null;
|
|
46
|
+
function T(e) {
|
|
46
47
|
let t = e.replace(/\/$/, "");
|
|
47
48
|
return t.endsWith("/graphql") ? t : t.endsWith("/global") ? `${t}/graphql` : `${t}/global/graphql`;
|
|
48
49
|
}
|
|
49
|
-
function
|
|
50
|
+
function E(e) {
|
|
50
51
|
return e.startsWith("https://") ? e.replace("https://", "wss://") : e.startsWith("http://") ? e.replace("http://", "ws://") : e;
|
|
51
52
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
let
|
|
57
|
-
|
|
53
|
+
var D = { preferWorkspaceAuth: !0 };
|
|
54
|
+
function O() {
|
|
55
|
+
let e = h();
|
|
56
|
+
if (!e) return null;
|
|
57
|
+
let t = g();
|
|
58
|
+
return _(t, {
|
|
59
|
+
workspaceId: e,
|
|
60
|
+
organizationId: m()
|
|
61
|
+
}) ? t : null;
|
|
62
|
+
}
|
|
63
|
+
function k(i, s) {
|
|
64
|
+
let m = T(i || "https://gw-global.local.burdenoff.com/global/graphql"), h = s ?? null;
|
|
65
|
+
if (S && C === m && w === h) return S;
|
|
66
|
+
C = m, w = h;
|
|
67
|
+
let g = new a({ uri: m }), _ = typeof window < "u" ? new t(n({
|
|
68
|
+
url: E(m),
|
|
58
69
|
connectionParams: () => ({ authorization: s ? `Bearer ${s}` : "" }),
|
|
59
70
|
lazy: !0,
|
|
60
71
|
retryAttempts: 3
|
|
61
|
-
})) : null,
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
72
|
+
})) : null, y = u((e, t) => {
|
|
73
|
+
let n = t.preferWorkspaceAuth === !0 ? O() : null;
|
|
74
|
+
return { headers: {
|
|
75
|
+
...t.headers,
|
|
76
|
+
authorization: s ? `Bearer ${s}` : "",
|
|
77
|
+
...n ? { "x-workspace-authorization": `Bearer ${n}` } : {}
|
|
78
|
+
} };
|
|
79
|
+
}), b = d(({ error: e }) => {
|
|
65
80
|
if (e) {
|
|
66
|
-
if (
|
|
81
|
+
if (v("errors" in e && Array.isArray(e.errors) ? e.errors : [])) {
|
|
67
82
|
p();
|
|
68
83
|
return;
|
|
69
84
|
}
|
|
70
85
|
e instanceof Error && f(e) && p();
|
|
71
86
|
}
|
|
72
|
-
}), D =
|
|
87
|
+
}), D = _ ? l(({ query: t }) => {
|
|
73
88
|
let n = e(t);
|
|
74
89
|
return n.kind === "OperationDefinition" && n.operation === "subscription";
|
|
75
|
-
},
|
|
76
|
-
return
|
|
90
|
+
}, _, g) : g;
|
|
91
|
+
return S = new r({
|
|
77
92
|
link: c([
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
93
|
+
b,
|
|
94
|
+
x(() => S),
|
|
95
|
+
y,
|
|
81
96
|
D
|
|
82
97
|
]),
|
|
83
98
|
cache: new o({ typePolicies: {
|
|
@@ -97,9 +112,9 @@ function C(i, s) {
|
|
|
97
112
|
query: { fetchPolicy: "cache-first" },
|
|
98
113
|
mutate: { fetchPolicy: "network-only" }
|
|
99
114
|
}
|
|
100
|
-
}),
|
|
115
|
+
}), S;
|
|
101
116
|
}
|
|
102
117
|
//#endregion
|
|
103
|
-
export {
|
|
118
|
+
export { D as USER_NOTIFICATION_CONTEXT, k as getGlobalNotificationClient };
|
|
104
119
|
|
|
105
120
|
//# sourceMappingURL=global-client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"global-client.js","names":[],"sources":["../../src/graphql/global-client.ts"],"sourcesContent":["import {\n ApolloClient,\n ApolloLink,\n type FetchResult,\n InMemoryCache,\n HttpLink,\n Observable,\n from,\n split,\n} from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { onError } from '@apollo/client/link/error';\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { isAuthNetworkError, redirectToLogin } from '@burdenoff/fe-libs/shared/utils';\nimport { createClient } from 'graphql-ws';\n\nfunction hasSessionAuthErrors(\n errors: ReadonlyArray<{ message?: string; extensions?: Record<string, unknown> }> = []\n): boolean {\n return errors.some((error) => {\n const code = typeof error.extensions?.code === 'string' ? error.extensions.code : '';\n const errorCode =\n typeof error.extensions?.errorCode === 'string' ? error.extensions.errorCode : '';\n const message = (error.message ?? '').toLowerCase();\n\n return (\n code === 'UNAUTHENTICATED' ||\n errorCode === 'TOKEN_EXPIRED' ||\n message.includes('token_expired') ||\n message.includes('token expired') ||\n message.includes('session expired') ||\n message.includes('unauthorized') ||\n message.includes('unauthenticated') ||\n message.includes('authentication required') ||\n message.includes('workspace context missing')\n );\n });\n}\n\nfunction isMutationOperation(query: Parameters<typeof getMainDefinition>[0]): boolean {\n const definition = getMainDefinition(query);\n return definition.kind === 'OperationDefinition' && definition.operation === 'mutation';\n}\n\nfunction hasGraphQLResultErrors(result: FetchResult<Record<string, unknown>>): boolean {\n const errors = result.errors;\n return Array.isArray(errors) && errors.length > 0;\n}\n\nfunction createMutationAutoRefreshLink(\n getClient: () => InstanceType<typeof ApolloClient> | null\n): ApolloLink {\n return new ApolloLink((operation, forward) => {\n const shouldRefreshAfterMutation =\n isMutationOperation(operation.query) &&\n operation.getContext().autoRefreshAfterMutation !== false &&\n operation.getContext().skipMutationAutoRefresh !== true;\n\n return new Observable<FetchResult<Record<string, unknown>>>((observer) => {\n const subscription = forward(operation).subscribe({\n next: (result) => {\n observer.next(result as FetchResult<Record<string, unknown>>);\n if (!shouldRefreshAfterMutation || hasGraphQLResultErrors(result)) return;\n\n void getClient()?.refetchQueries({ include: 'active' });\n },\n error: (error: unknown) => {\n observer.error(error);\n },\n complete: () => {\n observer.complete();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n });\n });\n}\n\nlet globalClientInstance: InstanceType<typeof ApolloClient> | null = null;\nlet currentGlobalUrl: string | null = null;\nlet currentAuthToken: string | null = null;\n\n/**\n * Default Global Gateway URL\n * Notifications are a GLOBAL service and must use the global gateway\n */\nexport const DEFAULT_GLOBAL_GATEWAY_URL = 'https://gw-global.local.burdenoff.com/global/graphql';\n\nfunction toGraphqlUrl(url: string): string {\n const normalized = url.replace(/\\/$/, '');\n if (normalized.endsWith('/graphql')) return normalized;\n if (normalized.endsWith('/global')) return `${normalized}/graphql`;\n return `${normalized}/global/graphql`;\n}\n\nfunction toSubscriptionUrl(url: string): string {\n if (url.startsWith('https://')) return url.replace('https://', 'wss://');\n if (url.startsWith('http://')) return url.replace('http://', 'ws://');\n return url;\n}\n\n/**\n * Get or create the singleton Apollo client for global notification operations\n *\n * @param globalGatewayUrl - Global Gateway GraphQL URL (default: https://gw-global.local.burdenoff.com/global/graphql)\n * @param authToken - Optional JWT auth token\n */\nexport function getGlobalNotificationClient(\n globalGatewayUrl?: string,\n authToken?: string\n): InstanceType<typeof ApolloClient> {\n const url = toGraphqlUrl(globalGatewayUrl || DEFAULT_GLOBAL_GATEWAY_URL);\n const nextAuthToken = authToken ?? null;\n\n // Return existing instance if config hasn't changed\n if (globalClientInstance && currentGlobalUrl === url && currentAuthToken === nextAuthToken) {\n return globalClientInstance;\n }\n\n // Update current config\n currentGlobalUrl = url;\n currentAuthToken = nextAuthToken;\n\n const httpLink = new HttpLink({\n uri: url,\n });\n\n const wsLink =\n typeof window !== 'undefined'\n ? new GraphQLWsLink(\n createClient({\n url: toSubscriptionUrl(url),\n connectionParams: () => ({\n authorization: authToken ? `Bearer ${authToken}` : '',\n }),\n lazy: true,\n retryAttempts: 3,\n })\n )\n : null;\n\n const authLink = setContext((_, prevContext) => {\n return {\n headers: {\n ...(prevContext.headers as Record<string, string>),\n authorization: authToken ? `Bearer ${authToken}` : '',\n },\n };\n });\n\n const errorLink = onError(({ error }) => {\n if (!error) return;\n\n const graphQLErrors = 'errors' in error && Array.isArray(error.errors) ? error.errors : [];\n\n if (hasSessionAuthErrors(graphQLErrors)) {\n redirectToLogin();\n return;\n }\n\n if (error instanceof Error && isAuthNetworkError(error)) {\n redirectToLogin();\n }\n });\n\n const transportLink = wsLink\n ? split(\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' && definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink\n )\n : httpLink;\n\n const mutationAutoRefreshLink = createMutationAutoRefreshLink(() => globalClientInstance);\n\n globalClientInstance = new ApolloClient({\n link: from([errorLink, mutationAutoRefreshLink, authLink, transportLink]),\n cache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n notifications: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n notificationTemplates: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n },\n },\n Notification: {\n keyFields: ['id'],\n },\n NotificationTemplate: {\n keyFields: ['id'],\n },\n },\n }),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'cache-and-network',\n },\n query: {\n fetchPolicy: 'cache-first',\n },\n mutate: {\n fetchPolicy: 'network-only',\n },\n },\n });\n\n return globalClientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing or re-initialization)\n */\nexport function resetGlobalNotificationClient(): void {\n if (globalClientInstance) {\n globalClientInstance.clearStore();\n globalClientInstance = null;\n currentGlobalUrl = null;\n currentAuthToken = null;\n }\n}\n"],"mappings":";;;;;;;;AAiBA,SAAS,EACP,IAAoF,EAAE,EAC7E;AACT,QAAO,EAAO,MAAM,MAAU;EAC5B,IAAM,IAAO,OAAO,EAAM,YAAY,QAAS,WAAW,EAAM,WAAW,OAAO,IAC5E,IACJ,OAAO,EAAM,YAAY,aAAc,WAAW,EAAM,WAAW,YAAY,IAC3E,KAAW,EAAM,WAAW,IAAI,aAAa;AAEnD,SACE,MAAS,qBACT,MAAc,mBACd,EAAQ,SAAS,gBAAgB,IACjC,EAAQ,SAAS,gBAAgB,IACjC,EAAQ,SAAS,kBAAkB,IACnC,EAAQ,SAAS,eAAe,IAChC,EAAQ,SAAS,kBAAkB,IACnC,EAAQ,SAAS,0BAA0B,IAC3C,EAAQ,SAAS,4BAA4B;GAE/C;;AAGJ,SAAS,EAAoB,GAAyD;CACpF,IAAM,IAAa,EAAkB,EAAM;AAC3C,QAAO,EAAW,SAAS,yBAAyB,EAAW,cAAc;;AAG/E,SAAS,EAAuB,GAAuD;CACrF,IAAM,IAAS,EAAO;AACtB,QAAO,MAAM,QAAQ,EAAO,IAAI,EAAO,SAAS;;AAGlD,SAAS,EACP,GACY;AACZ,QAAO,IAAI,GAAY,GAAW,MAAY;EAC5C,IAAM,IACJ,EAAoB,EAAU,MAAM,IACpC,EAAU,YAAY,CAAC,6BAA6B,MACpD,EAAU,YAAY,CAAC,4BAA4B;AAErD,SAAO,IAAI,GAAkD,MAAa;GACxE,IAAM,IAAe,EAAQ,EAAU,CAAC,UAAU;IAChD,OAAO,MAAW;AAChB,OAAS,KAAK,EAA+C,EACzD,GAAC,KAA8B,EAAuB,EAAO,KAE5D,GAAW,EAAE,eAAe,EAAE,SAAS,UAAU,CAAC;;IAEzD,QAAQ,MAAmB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b,IAAM,IAAa,EAAkB,EAAM;AAC3C,SACE,EAAW,SAAS,yBAAyB,EAAW,cAAc;IAG1E,GACA,EACD,GACD;AA2CJ,QAvCA,IAAuB,IAAI,EAAa;EACtC,MAAM,EAAK;GAAC;GAHkB,QAAoC,EAAqB;GAGvC;GAAU;GAAc,CAAC;EACzE,OAAO,IAAI,EAAc,EACvB,cAAc;GACZ,OAAO,EACL,QAAQ;IACN,eAAe,EACb,MAAM,GAAoB,GAAmB;AAC3C,YAAO;OAEV;IACD,uBAAuB,EACrB,MAAM,GAAoB,GAAmB;AAC3C,YAAO;OAEV;IACF,EACF;GACD,cAAc,EACZ,WAAW,CAAC,KAAK,EAClB;GACD,sBAAsB,EACpB,WAAW,CAAC,KAAK,EAClB;GACF,EACF,CAAC;EACF,gBAAgB;GACd,YAAY,EACV,aAAa,qBACd;GACD,OAAO,EACL,aAAa,eACd;GACD,QAAQ,EACN,aAAa,gBACd;GACF;EACF,CAAC,EAEK"}
|
|
1
|
+
{"version":3,"file":"global-client.js","names":[],"sources":["../../src/graphql/global-client.ts"],"sourcesContent":["import {\n ApolloClient,\n ApolloLink,\n type FetchResult,\n InMemoryCache,\n HttpLink,\n Observable,\n from,\n split,\n} from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { onError } from '@apollo/client/link/error';\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { isAuthNetworkError, redirectToLogin } from '@burdenoff/fe-libs/shared/utils';\nimport {\n getStoredOrganizationId,\n getStoredWorkspaceId,\n getStoredWorkspaceToken,\n isWorkspaceTokenValidForContext,\n} from '@burdenoff/fe-libs/shared/graphql';\nimport { createClient } from 'graphql-ws';\n\nfunction hasSessionAuthErrors(\n errors: ReadonlyArray<{ message?: string; extensions?: Record<string, unknown> }> = []\n): boolean {\n return errors.some((error) => {\n const code = typeof error.extensions?.code === 'string' ? error.extensions.code : '';\n const errorCode =\n typeof error.extensions?.errorCode === 'string' ? error.extensions.errorCode : '';\n const message = (error.message ?? '').toLowerCase();\n\n return (\n code === 'UNAUTHENTICATED' ||\n errorCode === 'TOKEN_EXPIRED' ||\n message.includes('token_expired') ||\n message.includes('token expired') ||\n message.includes('session expired') ||\n message.includes('unauthorized') ||\n message.includes('unauthenticated') ||\n message.includes('authentication required') ||\n message.includes('workspace context missing')\n );\n });\n}\n\nfunction isMutationOperation(query: Parameters<typeof getMainDefinition>[0]): boolean {\n const definition = getMainDefinition(query);\n return definition.kind === 'OperationDefinition' && definition.operation === 'mutation';\n}\n\nfunction hasGraphQLResultErrors(result: FetchResult<Record<string, unknown>>): boolean {\n const errors = result.errors;\n return Array.isArray(errors) && errors.length > 0;\n}\n\nfunction createMutationAutoRefreshLink(\n getClient: () => InstanceType<typeof ApolloClient> | null\n): ApolloLink {\n return new ApolloLink((operation, forward) => {\n const shouldRefreshAfterMutation =\n isMutationOperation(operation.query) &&\n operation.getContext().autoRefreshAfterMutation !== false &&\n operation.getContext().skipMutationAutoRefresh !== true;\n\n return new Observable<FetchResult<Record<string, unknown>>>((observer) => {\n const subscription = forward(operation).subscribe({\n next: (result) => {\n observer.next(result as FetchResult<Record<string, unknown>>);\n if (!shouldRefreshAfterMutation || hasGraphQLResultErrors(result)) return;\n\n void getClient()?.refetchQueries({ include: 'active' });\n },\n error: (error: unknown) => {\n observer.error(error);\n },\n complete: () => {\n observer.complete();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n });\n });\n}\n\nlet globalClientInstance: InstanceType<typeof ApolloClient> | null = null;\nlet currentGlobalUrl: string | null = null;\nlet currentAuthToken: string | null = null;\n\n/**\n * Default Global Gateway URL\n * Notifications are a GLOBAL service and must use the global gateway\n */\nexport const DEFAULT_GLOBAL_GATEWAY_URL = 'https://gw-global.local.burdenoff.com/global/graphql';\n\nfunction toGraphqlUrl(url: string): string {\n const normalized = url.replace(/\\/$/, '');\n if (normalized.endsWith('/graphql')) return normalized;\n if (normalized.endsWith('/global')) return `${normalized}/graphql`;\n return `${normalized}/global/graphql`;\n}\n\nfunction toSubscriptionUrl(url: string): string {\n if (url.startsWith('https://')) return url.replace('https://', 'wss://');\n if (url.startsWith('http://')) return url.replace('http://', 'ws://');\n return url;\n}\n\n/**\n * Get or create the singleton Apollo client for global notification operations\n *\n * @param globalGatewayUrl - Global Gateway GraphQL URL (default: https://gw-global.local.burdenoff.com/global/graphql)\n * @param authToken - Optional JWT auth token\n */\n/**\n * Context for a user's own notification reads and writes.\n *\n * Notifications are scoped to an ORGANIZATION, and product services file a\n * user's rows under the active workspace's organization. On the global gateway\n * a user session's organization comes from the account token, which differs\n * whenever the active workspace belongs to another organization the user is a\n * member of. With this context the request also carries the shell's workspace\n * token (when it is valid for the active workspace), so the gateway scopes it\n * to the active workspace's organization, as the shell's notification bell\n * does. Without a valid token the account organization applies, as before.\n */\nexport const USER_NOTIFICATION_CONTEXT = { preferWorkspaceAuth: true } as const;\n\n/** The shell's workspace token, when it is still valid for the active workspace. */\nfunction activeWorkspaceToken(): string | null {\n const workspaceId = getStoredWorkspaceId();\n if (!workspaceId) return null;\n const token = getStoredWorkspaceToken();\n return isWorkspaceTokenValidForContext(token, {\n workspaceId,\n organizationId: getStoredOrganizationId(),\n })\n ? token\n : null;\n}\n\nexport function getGlobalNotificationClient(\n globalGatewayUrl?: string,\n authToken?: string\n): InstanceType<typeof ApolloClient> {\n const url = toGraphqlUrl(globalGatewayUrl || DEFAULT_GLOBAL_GATEWAY_URL);\n const nextAuthToken = authToken ?? null;\n\n // Return existing instance if config hasn't changed\n if (globalClientInstance && currentGlobalUrl === url && currentAuthToken === nextAuthToken) {\n return globalClientInstance;\n }\n\n // Update current config\n currentGlobalUrl = url;\n currentAuthToken = nextAuthToken;\n\n const httpLink = new HttpLink({\n uri: url,\n });\n\n const wsLink =\n typeof window !== 'undefined'\n ? new GraphQLWsLink(\n createClient({\n url: toSubscriptionUrl(url),\n connectionParams: () => ({\n authorization: authToken ? `Bearer ${authToken}` : '',\n }),\n lazy: true,\n retryAttempts: 3,\n })\n )\n : null;\n\n const authLink = setContext((_, prevContext) => {\n const workspaceToken = prevContext.preferWorkspaceAuth === true ? activeWorkspaceToken() : null;\n return {\n headers: {\n ...(prevContext.headers as Record<string, string>),\n authorization: authToken ? `Bearer ${authToken}` : '',\n ...(workspaceToken ? { 'x-workspace-authorization': `Bearer ${workspaceToken}` } : {}),\n },\n };\n });\n\n const errorLink = onError(({ error }) => {\n if (!error) return;\n\n const graphQLErrors = 'errors' in error && Array.isArray(error.errors) ? error.errors : [];\n\n if (hasSessionAuthErrors(graphQLErrors)) {\n redirectToLogin();\n return;\n }\n\n if (error instanceof Error && isAuthNetworkError(error)) {\n redirectToLogin();\n }\n });\n\n const transportLink = wsLink\n ? split(\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' && definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink\n )\n : httpLink;\n\n const mutationAutoRefreshLink = createMutationAutoRefreshLink(() => globalClientInstance);\n\n globalClientInstance = new ApolloClient({\n link: from([errorLink, mutationAutoRefreshLink, authLink, transportLink]),\n cache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n notifications: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n notificationTemplates: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n },\n },\n Notification: {\n keyFields: ['id'],\n },\n NotificationTemplate: {\n keyFields: ['id'],\n },\n },\n }),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'cache-and-network',\n },\n query: {\n fetchPolicy: 'cache-first',\n },\n mutate: {\n fetchPolicy: 'network-only',\n },\n },\n });\n\n return globalClientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing or re-initialization)\n */\nexport function resetGlobalNotificationClient(): void {\n if (globalClientInstance) {\n globalClientInstance.clearStore();\n globalClientInstance = null;\n currentGlobalUrl = null;\n currentAuthToken = null;\n }\n}\n"],"mappings":";;;;;;;;;AAuBA,S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AAM,OAAO,GAAG,EAAM,SAAS,EAAE,CAEnD,EAAE;AACvC,OAAiB;AACjB;;AAGF,GAAI,aAAiB,SAAS,EAAmB,EAAM,IACrD,GAAiB;;GAEnB,EAEI,IAAgB,IAClB,GACG,EAAE,eAAY;EACb,IAAM,IAAa,EAAkB,EAAM;AAC3C,SACE,EAAW,SAAS,yBAAyB,EAAW,cAAc;IAG1E,GACA,EACD,GACD;AA2CJ,QAvCA,IAAuB,IAAI,EAAa;EACtC,MAAM,EAAK;GAAC;GAHkB,QAAoC,EAAqB;GAGvC;GAAU;GAAc,CAAC;EACzE,OAAO,IAAI,EAAc,EACvB,cAAc;GACZ,OAAO,EACL,QAAQ;IACN,eAAe,EACb,MAAM,GAAoB,GAAmB;AAC3C,YAAO;OAEV;IACD,uBAAuB,EACrB,MAAM,GAAoB,GAAmB;AAC3C,YAAO;OAEV;IACF,EACF;GACD,cAAc,EACZ,WAAW,CAAC,KAAK,EAClB;GACD,sBAAsB,EACpB,WAAW,CAAC,KAAK,EAClB;GACF,EACF,CAAC;EACF,gBAAgB;GACd,YAAY,EACV,aAAa,qBACd;GACD,OAAO,EACL,aAAa,eACd;GACD,QAAQ,EACN,aAAa,gBACd;GACF;EACF,CAAC,EAEK"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { useNotification as e } from "../providers/NotificationProvider.js";
|
|
2
2
|
import { getGlobalNotificationClient as t } from "../graphql/global-client.js";
|
|
3
3
|
import { CreateNotificationTopicDocument as n, DeleteNotificationTopicDocument as r, GetNotificationTopicsDocument as i, SetNotificationTopicSubscriptionDocument as a, UpdateNotificationTopicDocument as o } from "../generated/global-operations.js";
|
|
4
|
-
import {
|
|
4
|
+
import { isPermissionError as s } from "../utils/index.js";
|
|
5
|
+
import { useCallback as c, useEffect as l, useState as u } from "react";
|
|
5
6
|
//#region src/hooks/useNotificationTopics.ts
|
|
6
|
-
function
|
|
7
|
+
function d(e) {
|
|
7
8
|
return {
|
|
8
9
|
id: e.id,
|
|
9
10
|
slug: e.slug,
|
|
@@ -24,44 +25,45 @@ function u(e) {
|
|
|
24
25
|
updatedAt: e.updatedAt
|
|
25
26
|
};
|
|
26
27
|
}
|
|
27
|
-
function
|
|
28
|
-
let { authToken:
|
|
29
|
-
|
|
28
|
+
function f(f) {
|
|
29
|
+
let { authToken: p, apiGatewayUrl: m } = e(), [h, g] = u([]), [_, v] = u(!1), [y, b] = u(null), [x, S] = u(!1), [C, w] = u(f || {}), T = c(() => t(m ?? void 0, p ?? void 0), [m, p]), E = c(async () => {
|
|
30
|
+
v(!0), b(null), S(!1);
|
|
30
31
|
try {
|
|
31
|
-
|
|
32
|
+
g(((await T().query({
|
|
32
33
|
query: i,
|
|
33
34
|
variables: {
|
|
34
35
|
filter: {
|
|
35
|
-
...
|
|
36
|
-
...
|
|
37
|
-
...
|
|
36
|
+
...C.search ? { search: C.search } : {},
|
|
37
|
+
...C.type ? { type: C.type } : {},
|
|
38
|
+
...C.isActive === void 0 ? {} : { isActive: C.isActive }
|
|
38
39
|
},
|
|
39
40
|
limit: 100,
|
|
40
41
|
offset: 0
|
|
41
42
|
},
|
|
42
|
-
fetchPolicy: "
|
|
43
|
-
})).data?.notificationTopics.items || []).map(
|
|
43
|
+
fetchPolicy: "network-only"
|
|
44
|
+
})).data?.notificationTopics.items || []).map(d));
|
|
44
45
|
} catch (e) {
|
|
45
|
-
console.error("[useNotificationTopics] Failed to fetch topics:", e),
|
|
46
|
+
s(e) ? S(!0) : (console.error("[useNotificationTopics] Failed to fetch topics:", e), b(e instanceof Error ? e.message : "Failed to fetch topics")), g([]);
|
|
46
47
|
} finally {
|
|
47
|
-
|
|
48
|
+
v(!1);
|
|
48
49
|
}
|
|
49
|
-
}, [
|
|
50
|
-
return
|
|
51
|
-
|
|
52
|
-
}, [
|
|
53
|
-
topics:
|
|
54
|
-
isLoading:
|
|
55
|
-
error:
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
50
|
+
}, [C, T]);
|
|
51
|
+
return l(() => {
|
|
52
|
+
E();
|
|
53
|
+
}, [E]), {
|
|
54
|
+
topics: h,
|
|
55
|
+
isLoading: _,
|
|
56
|
+
error: y,
|
|
57
|
+
isForbidden: x,
|
|
58
|
+
filter: C,
|
|
59
|
+
setFilter: w,
|
|
60
|
+
refetch: E,
|
|
61
|
+
createTopic: c(async (e) => {
|
|
62
|
+
let t = await T().mutate({
|
|
61
63
|
mutation: n,
|
|
62
64
|
variables: { input: e }
|
|
63
65
|
});
|
|
64
|
-
await
|
|
66
|
+
await E();
|
|
65
67
|
let r = t.data?.createNotificationTopic;
|
|
66
68
|
return r ? {
|
|
67
69
|
id: r.id,
|
|
@@ -74,16 +76,16 @@ function d(d) {
|
|
|
74
76
|
createdAt: r.createdAt,
|
|
75
77
|
updatedAt: r.updatedAt
|
|
76
78
|
} : null;
|
|
77
|
-
}, [
|
|
78
|
-
updateTopic:
|
|
79
|
-
let n = await
|
|
79
|
+
}, [E, T]),
|
|
80
|
+
updateTopic: c(async (e, t) => {
|
|
81
|
+
let n = await T().mutate({
|
|
80
82
|
mutation: o,
|
|
81
83
|
variables: {
|
|
82
84
|
id: e,
|
|
83
85
|
input: t
|
|
84
86
|
}
|
|
85
87
|
});
|
|
86
|
-
await
|
|
88
|
+
await E();
|
|
87
89
|
let r = n.data?.updateNotificationTopic;
|
|
88
90
|
return r ? {
|
|
89
91
|
id: r.id,
|
|
@@ -96,20 +98,20 @@ function d(d) {
|
|
|
96
98
|
createdAt: r.createdAt,
|
|
97
99
|
updatedAt: r.updatedAt
|
|
98
100
|
} : null;
|
|
99
|
-
}, [
|
|
100
|
-
deleteTopic:
|
|
101
|
+
}, [E, T]),
|
|
102
|
+
deleteTopic: c(async (e) => (await T().mutate({
|
|
101
103
|
mutation: r,
|
|
102
104
|
variables: { id: e }
|
|
103
|
-
}), await
|
|
104
|
-
setTopicSubscription:
|
|
105
|
-
let n = await
|
|
105
|
+
}), await E(), !0), [E, T]),
|
|
106
|
+
setTopicSubscription: c(async (e, t) => {
|
|
107
|
+
let n = await T().mutate({
|
|
106
108
|
mutation: a,
|
|
107
109
|
variables: { input: {
|
|
108
110
|
topicId: e,
|
|
109
111
|
subscribed: t
|
|
110
112
|
} }
|
|
111
113
|
});
|
|
112
|
-
await
|
|
114
|
+
await E();
|
|
113
115
|
let r = n.data?.setNotificationTopicSubscription;
|
|
114
116
|
return r ? {
|
|
115
117
|
id: r.id,
|
|
@@ -118,10 +120,10 @@ function d(d) {
|
|
|
118
120
|
topicId: r.topicId,
|
|
119
121
|
userId: r.userId
|
|
120
122
|
} : null;
|
|
121
|
-
}, [
|
|
123
|
+
}, [E, T])
|
|
122
124
|
};
|
|
123
125
|
}
|
|
124
126
|
//#endregion
|
|
125
|
-
export {
|
|
127
|
+
export { f as useNotificationTopics };
|
|
126
128
|
|
|
127
129
|
//# sourceMappingURL=useNotificationTopics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationTopics.js","names":[],"sources":["../../src/hooks/useNotificationTopics.ts"],"sourcesContent":["import { useState, useEffect, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationTopic, NotificationTopicSubscription } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTopicsQuery,\n CreateNotificationTopicMutation,\n UpdateNotificationTopicMutation,\n SetNotificationTopicSubscriptionMutation,\n} from '../generated/global-operations';\n\nexport interface NotificationTopicFilter {\n search?: string;\n type?: string;\n isActive?: boolean;\n}\n\nexport interface CreateNotificationTopicInput {\n name: string;\n slug: string;\n description?: string;\n type: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface UpdateNotificationTopicInput {\n name?: string;\n slug?: string;\n description?: string;\n type?: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nfunction mapTopic(\n topic: GetNotificationTopicsQuery['notificationTopics']['items'][number]\n): NotificationTopic {\n return {\n id: topic.id,\n slug: topic.slug,\n name: topic.name,\n description: topic.description ?? undefined,\n type: topic.type as NotificationTopic['type'],\n isActive: topic.isActive,\n metadata: topic.metadata ?? undefined,\n subscriberCount: topic.subscriberCount ?? 0,\n mySubscription: topic.mySubscription\n ? {\n id: topic.mySubscription.id,\n subscribed: topic.mySubscription.subscribed,\n unsubscribedAt: topic.mySubscription.unsubscribedAt ?? undefined,\n topicId: topic.mySubscription.topicId,\n userId: topic.mySubscription.userId,\n }\n : undefined,\n createdAt: topic.createdAt,\n updatedAt: topic.updatedAt,\n };\n}\n\nexport function useNotificationTopics(initialFilter?: NotificationTopicFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [topics, setTopics] = useState<NotificationTopic[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [filter, setFilter] = useState<NotificationTopicFilter>(initialFilter || {});\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchTopics = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTopicsQuery>({\n query: NotificationOps.GetNotificationTopicsDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search } : {}),\n ...(filter.type ? { type: filter.type } : {}),\n ...(filter.isActive !== undefined ? { isActive: filter.isActive } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: 'cache-first',\n });\n\n setTopics((result.data?.notificationTopics.items || []).map(mapTopic));\n } catch (err) {\n console.error('[useNotificationTopics] Failed to fetch topics:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch topics');\n setTopics([]);\n } finally {\n setIsLoading(false);\n }\n }, [filter, getClient]);\n\n useEffect(() => {\n fetchTopics();\n }, [fetchTopics]);\n\n const createTopic = useCallback(\n async (input: CreateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTopicMutation>({\n mutation: NotificationOps.CreateNotificationTopicDocument,\n variables: { input },\n });\n await fetchTopics();\n const created = result.data?.createNotificationTopic;\n return created\n ? {\n id: created.id,\n slug: created.slug,\n name: created.name,\n description: created.description ?? undefined,\n type: created.type as NotificationTopic['type'],\n isActive: created.isActive,\n subscriberCount: 0,\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const updateTopic = useCallback(\n async (id: string, input: UpdateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTopicMutation>({\n mutation: NotificationOps.UpdateNotificationTopicDocument,\n variables: { id, input },\n });\n await fetchTopics();\n const updated = result.data?.updateNotificationTopic;\n return updated\n ? {\n id: updated.id,\n slug: updated.slug,\n name: updated.name,\n description: updated.description ?? undefined,\n type: updated.type as NotificationTopic['type'],\n isActive: updated.isActive,\n subscriberCount: 0,\n createdAt: updated.createdAt,\n updatedAt: updated.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const deleteTopic = useCallback(\n async (id: string): Promise<boolean> => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTopicDocument,\n variables: { id },\n });\n await fetchTopics();\n return true;\n },\n [fetchTopics, getClient]\n );\n\n const setTopicSubscription = useCallback(\n async (topicId: string, subscribed: boolean): Promise<NotificationTopicSubscription | null> => {\n const client = getClient();\n const result = await client.mutate<SetNotificationTopicSubscriptionMutation>({\n mutation: NotificationOps.SetNotificationTopicSubscriptionDocument,\n variables: {\n input: {\n topicId,\n subscribed,\n },\n },\n });\n await fetchTopics();\n\n const subscription = result.data?.setNotificationTopicSubscription;\n return subscription\n ? {\n id: subscription.id,\n subscribed: subscription.subscribed,\n unsubscribedAt: subscription.unsubscribedAt ?? undefined,\n topicId: subscription.topicId,\n userId: subscription.userId,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n return {\n topics,\n isLoading,\n error,\n filter,\n setFilter,\n refetch: fetchTopics,\n createTopic,\n updateTopic,\n deleteTopic,\n setTopicSubscription,\n };\n}\n"],"mappings":";;;;;AAoCA,SAAS,EACP,GACmB;AACnB,QAAO;EACL,IAAI,EAAM;EACV,MAAM,EAAM;EACZ,MAAM,EAAM;EACZ,aAAa,EAAM,eAAe,KAAA;EAClC,MAAM,EAAM;EACZ,UAAU,EAAM;EAChB,UAAU,EAAM,YAAY,KAAA;EAC5B,iBAAiB,EAAM,mBAAmB;EAC1C,gBAAgB,EAAM,iBAClB;GACE,IAAI,EAAM,eAAe;GACzB,YAAY,EAAM,eAAe;GACjC,gBAAgB,EAAM,eAAe,kBAAkB,KAAA;GACvD,SAAS,EAAM,eAAe;GAC9B,QAAQ,EAAM,eAAe;GAC9B,GACD,KAAA;EACJ,WAAW,EAAM;EACjB,WAAW,EAAM;EAClB;;AAGH,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,EAAE,cAAW,qBAAkB,GAAiB,EAChD,CAAC,GAAQ,KAAa,EAA8B,EAAE,CAAC,EACvD,CAAC,GAAW,KAAgB,EAAS,GAAM,EAC3C,CAAC,GAAO,KAAY,EAAwB,KAAK,EACjD,CAAC,GAAQ,KAAa,EAAkC,KAAiB,EAAE,CAAC,EAE5E,IAAY,QACT,EAA4B,KAAiB,KAAA,GAAW,KAAa,KAAA,EAAU,EACrF,CAAC,GAAe,EAAU,CAAC,EAExB,IAAc,EAAY,YAAY;AAE1C,EADA,EAAa,GAAK,EAClB,EAAS,KAAK;AAEd,MAAI;AAgBF,OAde,MADA,GAAW,CACE,MAAkC;IAC5D,OAAO;IACP,WAAW;KACT,QAAQ;MACN,GAAI,EAAO,SAAS,EAAE,QAAQ,EAAO,QAAQ,GAAG,EAAE;MAClD,GAAI,EAAO,OAAO,EAAE,MAAM,EAAO,MAAM,GAAG,EAAE;MAC5C,GAAI,EAAO,aAAa,KAAA,IAA4C,EAAE,GAAlC,EAAE,UAAU,EA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DkB,EAClB,OAAO,OAEL,MADe,GAAW,CACb,OAAO;GAClB,UAAU;GACV,WAAW,EAAE,OAAI;GAClB,CAAC,EACF,MAAM,GAAa,EACZ,KAET,CAAC,GAAa,EAAU,CACzB;EAwCC,sBAtC2B,EAC3B,OAAO,GAAiB,MAAuE;GAE7F,IAAM,IAAS,MADA,GAAW,CACE,OAAiD;IAC3E,UAAU;IACV,WAAW,EACT,OAAO;KACL;KACA;KACD,EACF;IACF,CAAC;AACF,SAAM,GAAa;GAEnB,IAAM,IAAe,EAAO,MAAM;AAClC,UAAO,IACH;IACE,IAAI,EAAa;IACjB,YAAY,EAAa;IACzB,gBAAgB,EAAa,kBAAkB,KAAA;IAC/C,SAAS,EAAa;IACtB,QAAQ,EAAa;IACtB,GACD;KAEN,CAAC,GAAa,EAAU,CACzB;EAaA"}
|
|
1
|
+
{"version":3,"file":"useNotificationTopics.js","names":[],"sources":["../../src/hooks/useNotificationTopics.ts"],"sourcesContent":["import { useState, useEffect, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationTopic, NotificationTopicSubscription } from '../types';\nimport { isPermissionError } from '../utils';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTopicsQuery,\n CreateNotificationTopicMutation,\n UpdateNotificationTopicMutation,\n SetNotificationTopicSubscriptionMutation,\n} from '../generated/global-operations';\n\nexport interface NotificationTopicFilter {\n search?: string;\n type?: string;\n isActive?: boolean;\n}\n\nexport interface CreateNotificationTopicInput {\n name: string;\n slug: string;\n description?: string;\n type: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface UpdateNotificationTopicInput {\n name?: string;\n slug?: string;\n description?: string;\n type?: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nfunction mapTopic(\n topic: GetNotificationTopicsQuery['notificationTopics']['items'][number]\n): NotificationTopic {\n return {\n id: topic.id,\n slug: topic.slug,\n name: topic.name,\n description: topic.description ?? undefined,\n type: topic.type as NotificationTopic['type'],\n isActive: topic.isActive,\n metadata: topic.metadata ?? undefined,\n subscriberCount: topic.subscriberCount ?? 0,\n mySubscription: topic.mySubscription\n ? {\n id: topic.mySubscription.id,\n subscribed: topic.mySubscription.subscribed,\n unsubscribedAt: topic.mySubscription.unsubscribedAt ?? undefined,\n topicId: topic.mySubscription.topicId,\n userId: topic.mySubscription.userId,\n }\n : undefined,\n createdAt: topic.createdAt,\n updatedAt: topic.updatedAt,\n };\n}\n\nexport function useNotificationTopics(initialFilter?: NotificationTopicFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [topics, setTopics] = useState<NotificationTopic[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n // True when the gateway denied `notificationTopics` (no notification-topic\n // read). Pages show a no-access state instead of \"no topics\" (BOFF-10104).\n const [isForbidden, setIsForbidden] = useState(false);\n const [filter, setFilter] = useState<NotificationTopicFilter>(initialFilter || {});\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchTopics = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n setIsForbidden(false);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTopicsQuery>({\n query: NotificationOps.GetNotificationTopicsDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search } : {}),\n ...(filter.type ? { type: filter.type } : {}),\n ...(filter.isActive !== undefined ? { isActive: filter.isActive } : {}),\n },\n limit: 100,\n offset: 0,\n },\n // Always revalidate: access to topics can be revoked while the app is\n // open, and a cached list would hide the FORBIDDEN (BOFF-10104).\n fetchPolicy: 'network-only',\n });\n\n setTopics((result.data?.notificationTopics.items || []).map(mapTopic));\n } catch (err) {\n // A denial is a handled state (isForbidden), not a load error.\n if (isPermissionError(err)) {\n setIsForbidden(true);\n } else {\n console.error('[useNotificationTopics] Failed to fetch topics:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch topics');\n }\n setTopics([]);\n } finally {\n setIsLoading(false);\n }\n }, [filter, getClient]);\n\n useEffect(() => {\n fetchTopics();\n }, [fetchTopics]);\n\n const createTopic = useCallback(\n async (input: CreateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTopicMutation>({\n mutation: NotificationOps.CreateNotificationTopicDocument,\n variables: { input },\n });\n await fetchTopics();\n const created = result.data?.createNotificationTopic;\n return created\n ? {\n id: created.id,\n slug: created.slug,\n name: created.name,\n description: created.description ?? undefined,\n type: created.type as NotificationTopic['type'],\n isActive: created.isActive,\n subscriberCount: 0,\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const updateTopic = useCallback(\n async (id: string, input: UpdateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTopicMutation>({\n mutation: NotificationOps.UpdateNotificationTopicDocument,\n variables: { id, input },\n });\n await fetchTopics();\n const updated = result.data?.updateNotificationTopic;\n return updated\n ? {\n id: updated.id,\n slug: updated.slug,\n name: updated.name,\n description: updated.description ?? undefined,\n type: updated.type as NotificationTopic['type'],\n isActive: updated.isActive,\n subscriberCount: 0,\n createdAt: updated.createdAt,\n updatedAt: updated.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const deleteTopic = useCallback(\n async (id: string): Promise<boolean> => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTopicDocument,\n variables: { id },\n });\n await fetchTopics();\n return true;\n },\n [fetchTopics, getClient]\n );\n\n const setTopicSubscription = useCallback(\n async (topicId: string, subscribed: boolean): Promise<NotificationTopicSubscription | null> => {\n const client = getClient();\n const result = await client.mutate<SetNotificationTopicSubscriptionMutation>({\n mutation: NotificationOps.SetNotificationTopicSubscriptionDocument,\n variables: {\n input: {\n topicId,\n subscribed,\n },\n },\n });\n await fetchTopics();\n\n const subscription = result.data?.setNotificationTopicSubscription;\n return subscription\n ? {\n id: subscription.id,\n subscribed: subscription.subscribed,\n unsubscribedAt: subscription.unsubscribedAt ?? undefined,\n topicId: subscription.topicId,\n userId: subscription.userId,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n return {\n topics,\n isLoading,\n error,\n isForbidden,\n filter,\n setFilter,\n refetch: fetchTopics,\n createTopic,\n updateTopic,\n deleteTopic,\n setTopicSubscription,\n };\n}\n"],"mappings":";;;;;;AAqCA,SAAS,EACP,GACmB;AACnB,QAAO;EACL,IAAI,EAAM;EACV,MAAM,EAAM;EACZ,MAAM,EAAM;EACZ,aAAa,EAAM,eAAe,KAAA;EAClC,MAAM,EAAM;EACZ,UAAU,EAAM;EAChB,UAAU,EAAM,YAAY,KAAA;EAC5B,iBAAiB,EAAM,mBAAmB;EAC1C,gBAAgB,EAAM,iBAClB;GACE,IAAI,EAAM,eAAe;GACzB,YAAY,EAAM,eAAe;GACjC,gBAAgB,EAAM,eAAe,kBAAkB,KAAA;GACvD,SAAS,EAAM,eAAe;GAC9B,QAAQ,EAAM,eAAe;GAC9B,GACD,KAAA;EACJ,WAAW,EAAM;EACjB,WAAW,EAAM;EAClB;;AAGH,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,EAAE,cAAW,qBAAkB,GAAiB,EAChD,CAAC,GAAQ,KAAa,EAA8B,EAAE,CAAC,EACvD,CAAC,GAAW,KAAgB,EAAS,GAAM,EAC3C,CAAC,GAAO,KAAY,EAAwB,KAAK,EAGjD,CAAC,GAAa,KAAkB,EAAS,GAAM,EAC/C,CAAC,GAAQ,KAAa,EAAkC,KAAiB,EAAE,CAAC,EAE5E,IAAY,QACT,EAA4B,KAAiB,KAAA,GAAW,KAAa,KAAA,EAAU,EACrF,CAAC,GAAe,EAAU,CAAC,EAExB,IAAc,EAAY,YAAY;AAG1C,EAFA,EAAa,GAAK,EAClB,EAAS,KAAK,EACd,EAAe,GAAM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