@flamingo-stack/openframe-frontend-core 0.0.686-2464.7467.1 → 0.0.686
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/{chunk-JTC4RPS3.js → chunk-2G2CB7ZZ.js} +5 -5
- package/dist/{chunk-QIYQMEP3.cjs → chunk-3DO76UAB.cjs} +20 -20
- package/dist/{chunk-QIYQMEP3.cjs.map → chunk-3DO76UAB.cjs.map} +1 -1
- package/dist/{chunk-S6C5GBQ4.js → chunk-3NIZ2VLQ.js} +3 -3
- package/dist/{chunk-P2AE46BQ.cjs → chunk-4LBCUBVL.cjs} +50 -50
- package/dist/{chunk-P2AE46BQ.cjs.map → chunk-4LBCUBVL.cjs.map} +1 -1
- package/dist/{chunk-U5LNGS5P.js → chunk-4RJQMOQW.js} +8 -8
- package/dist/{chunk-TV6YNAVH.cjs → chunk-AF4XOURN.cjs} +3 -3
- package/dist/{chunk-TV6YNAVH.cjs.map → chunk-AF4XOURN.cjs.map} +1 -1
- package/dist/{chunk-637VBBHC.js → chunk-ASBBGP36.js} +7 -7
- package/dist/{chunk-6MDNGGCJ.js → chunk-C5TFPMOM.js} +6 -6
- package/dist/{chunk-J5O5KIHL.cjs → chunk-GETQTNRV.cjs} +22 -22
- package/dist/{chunk-J5O5KIHL.cjs.map → chunk-GETQTNRV.cjs.map} +1 -1
- package/dist/{chunk-XML4CLL3.cjs → chunk-IBUFFKAK.cjs} +411 -411
- package/dist/{chunk-XML4CLL3.cjs.map → chunk-IBUFFKAK.cjs.map} +1 -1
- package/dist/{chunk-74TJJQMT.js → chunk-IELOPDTA.js} +3 -3
- package/dist/{chunk-RMNWN5RC.cjs → chunk-II5GVLTN.cjs} +5 -5
- package/dist/{chunk-RMNWN5RC.cjs.map → chunk-II5GVLTN.cjs.map} +1 -1
- package/dist/{chunk-D2XLLWIU.cjs → chunk-IJUQQTMV.cjs} +2 -4
- package/dist/chunk-IJUQQTMV.cjs.map +1 -0
- package/dist/{chunk-LMZW2KZF.js → chunk-JBJZL5PI.js} +4 -4
- package/dist/{chunk-WYB27NKC.js → chunk-JNUL3ZWK.js} +3 -5
- package/dist/chunk-JNUL3ZWK.js.map +1 -0
- package/dist/{chunk-JA6NYUF3.js → chunk-LCOMNQLX.js} +5 -5
- package/dist/{chunk-NRH4IHI4.js → chunk-MHTB67ZH.js} +4 -4
- package/dist/{chunk-HSWEUDKR.cjs → chunk-MZAZUSPQ.cjs} +10 -10
- package/dist/{chunk-HSWEUDKR.cjs.map → chunk-MZAZUSPQ.cjs.map} +1 -1
- package/dist/{chunk-IQDUMR3K.cjs → chunk-N3I53B5W.cjs} +5 -5
- package/dist/{chunk-IQDUMR3K.cjs.map → chunk-N3I53B5W.cjs.map} +1 -1
- package/dist/{chunk-3NBKFWHG.js → chunk-NINO3PI7.js} +3 -3
- package/dist/{chunk-CCLO5R5A.cjs → chunk-P4SBHO7U.cjs} +17 -17
- package/dist/{chunk-CCLO5R5A.cjs.map → chunk-P4SBHO7U.cjs.map} +1 -1
- package/dist/{chunk-BOIYZ2L6.js → chunk-PG65AE3I.js} +5 -5
- package/dist/{chunk-SFYBD456.js → chunk-QOH45QSE.js} +4 -4
- package/dist/{chunk-KBH7EWFW.cjs → chunk-QTXDXHMD.cjs} +26 -26
- package/dist/{chunk-KBH7EWFW.cjs.map → chunk-QTXDXHMD.cjs.map} +1 -1
- package/dist/{chunk-3XZHZ4LD.cjs → chunk-RBCMBRI7.cjs} +39 -39
- package/dist/{chunk-3XZHZ4LD.cjs.map → chunk-RBCMBRI7.cjs.map} +1 -1
- package/dist/{chunk-CJNYQ6FK.cjs → chunk-RKH7DEDF.cjs} +12 -12
- package/dist/{chunk-CJNYQ6FK.cjs.map → chunk-RKH7DEDF.cjs.map} +1 -1
- package/dist/{chunk-PLLY62XF.js → chunk-RSMAVO2Z.js} +2 -2
- package/dist/{chunk-SIAGFCKP.cjs → chunk-SI77HF4U.cjs} +53 -53
- package/dist/{chunk-SIAGFCKP.cjs.map → chunk-SI77HF4U.cjs.map} +1 -1
- package/dist/{chunk-NMFBC7CC.js → chunk-U6JC3RS2.js} +2 -2
- package/dist/{chunk-OWSFP7LX.cjs → chunk-UBXEETWQ.cjs} +80 -80
- package/dist/{chunk-OWSFP7LX.cjs.map → chunk-UBXEETWQ.cjs.map} +1 -1
- package/dist/{chunk-ZQDJPLRS.js → chunk-V5REIMSE.js} +2 -2
- package/dist/{chunk-VAHO2DTJ.js → chunk-WFH52OVQ.js} +6 -6
- package/dist/{chunk-GQ4FKLFC.cjs → chunk-WJX3ZSOE.cjs} +43 -43
- package/dist/{chunk-GQ4FKLFC.cjs.map → chunk-WJX3ZSOE.cjs.map} +1 -1
- package/dist/{chunk-IWJEJBML.cjs → chunk-XF5TJ4P2.cjs} +12 -12
- package/dist/{chunk-IWJEJBML.cjs.map → chunk-XF5TJ4P2.cjs.map} +1 -1
- package/dist/{chunk-IXLO6K3T.js → chunk-YPXXXX6R.js} +2 -2
- package/dist/{chunk-RHBJIFAJ.cjs → chunk-ZS3YCJYY.cjs} +7 -7
- package/dist/{chunk-RHBJIFAJ.cjs.map → chunk-ZS3YCJYY.cjs.map} +1 -1
- package/dist/components/case-studies/index.cjs +17 -17
- package/dist/components/case-studies/index.js +5 -5
- package/dist/components/chat/index.cjs +3 -3
- package/dist/components/chat/index.js +2 -2
- package/dist/components/contact/index.cjs +6 -6
- package/dist/components/contact/index.js +5 -5
- package/dist/components/docs/index.cjs +9 -9
- package/dist/components/docs/index.js +8 -8
- package/dist/components/embeds/index.cjs +6 -6
- package/dist/components/embeds/index.js +5 -5
- package/dist/components/faq/index.cjs +6 -6
- package/dist/components/faq/index.js +5 -5
- package/dist/components/features/index.cjs +5 -5
- package/dist/components/features/index.js +4 -4
- package/dist/components/help-center-pages/index.cjs +83 -83
- package/dist/components/help-center-pages/index.js +16 -16
- package/dist/components/index.cjs +46 -46
- package/dist/components/index.js +15 -15
- package/dist/components/meeting-scheduler/index.cjs +32 -32
- package/dist/components/meeting-scheduler/index.js +4 -4
- package/dist/components/navigation/index.cjs +8 -8
- package/dist/components/navigation/index.js +7 -7
- package/dist/components/onboarding-guides/index.cjs +8 -8
- package/dist/components/onboarding-guides/index.js +7 -7
- package/dist/components/tickets/index.cjs +9 -9
- package/dist/components/tickets/index.js +8 -8
- package/dist/components/tool-icon.d.ts.map +1 -1
- package/dist/components/ui/index.cjs +5 -5
- package/dist/components/ui/index.js +4 -4
- package/dist/hooks/index.cjs +3 -3
- package/dist/hooks/index.js +2 -2
- package/dist/index.cjs +10 -10
- package/dist/index.js +8 -8
- package/package.json +1 -1
- package/src/components/tool-icon.tsx +2 -4
- package/dist/chunk-D2XLLWIU.cjs.map +0 -1
- package/dist/chunk-WYB27NKC.js.map +0 -1
- /package/dist/{chunk-JTC4RPS3.js.map → chunk-2G2CB7ZZ.js.map} +0 -0
- /package/dist/{chunk-S6C5GBQ4.js.map → chunk-3NIZ2VLQ.js.map} +0 -0
- /package/dist/{chunk-U5LNGS5P.js.map → chunk-4RJQMOQW.js.map} +0 -0
- /package/dist/{chunk-637VBBHC.js.map → chunk-ASBBGP36.js.map} +0 -0
- /package/dist/{chunk-6MDNGGCJ.js.map → chunk-C5TFPMOM.js.map} +0 -0
- /package/dist/{chunk-74TJJQMT.js.map → chunk-IELOPDTA.js.map} +0 -0
- /package/dist/{chunk-LMZW2KZF.js.map → chunk-JBJZL5PI.js.map} +0 -0
- /package/dist/{chunk-JA6NYUF3.js.map → chunk-LCOMNQLX.js.map} +0 -0
- /package/dist/{chunk-NRH4IHI4.js.map → chunk-MHTB67ZH.js.map} +0 -0
- /package/dist/{chunk-3NBKFWHG.js.map → chunk-NINO3PI7.js.map} +0 -0
- /package/dist/{chunk-BOIYZ2L6.js.map → chunk-PG65AE3I.js.map} +0 -0
- /package/dist/{chunk-SFYBD456.js.map → chunk-QOH45QSE.js.map} +0 -0
- /package/dist/{chunk-PLLY62XF.js.map → chunk-RSMAVO2Z.js.map} +0 -0
- /package/dist/{chunk-NMFBC7CC.js.map → chunk-U6JC3RS2.js.map} +0 -0
- /package/dist/{chunk-ZQDJPLRS.js.map → chunk-V5REIMSE.js.map} +0 -0
- /package/dist/{chunk-VAHO2DTJ.js.map → chunk-WFH52OVQ.js.map} +0 -0
- /package/dist/{chunk-IXLO6K3T.js.map → chunk-YPXXXX6R.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import {
|
|
3
3
|
createSseSubscription
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-MHTB67ZH.js";
|
|
5
5
|
import {
|
|
6
6
|
useChatIdentity
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-YPXXXX6R.js";
|
|
8
8
|
import {
|
|
9
9
|
embedAuthedFetch
|
|
10
10
|
} from "./chunk-2KILTCND.js";
|
|
@@ -275,4 +275,4 @@ export {
|
|
|
275
275
|
TICKET_MARK_READ_DEBOUNCE_MS,
|
|
276
276
|
TOAST_COPY
|
|
277
277
|
};
|
|
278
|
-
//# sourceMappingURL=chunk-
|
|
278
|
+
//# sourceMappingURL=chunk-IELOPDTA.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client";
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkIBUFFKAKcjs = require('./chunk-IBUFFKAK.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
|
-
var
|
|
7
|
+
var _chunkSI77HF4Ucjs = require('./chunk-SI77HF4U.cjs');
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
var _chunkYCKGUQA2cjs = require('./chunk-YCKGUQA2.cjs');
|
|
@@ -44,7 +44,7 @@ function isSummaryData(value) {
|
|
|
44
44
|
}
|
|
45
45
|
function TicketLiveProvider({ children, enabled = true }) {
|
|
46
46
|
const runtime = _chunkU2YLMFJKcjs.useChatRuntime.call(void 0, );
|
|
47
|
-
const identity =
|
|
47
|
+
const identity = _chunkSI77HF4Ucjs.useChatIdentity.call(void 0, enabled);
|
|
48
48
|
const queryClient = _reactquery.useQueryClient.call(void 0, );
|
|
49
49
|
const streamUrl = _nullishCoalesce(_optionalChain([runtime, 'optionalAccess', _ => _.endpoints, 'access', _2 => _2.ticketStreamUrl]), () => ( TICKET_STREAM_ENDPOINT));
|
|
50
50
|
const readUrl = _nullishCoalesce(_optionalChain([runtime, 'optionalAccess', _3 => _3.endpoints, 'access', _4 => _4.ticketReadUrl]), () => ( TICKET_READ_ENDPOINT));
|
|
@@ -160,7 +160,7 @@ function TicketLiveProvider({ children, enabled = true }) {
|
|
|
160
160
|
_react2.default.useEffect(() => {
|
|
161
161
|
if (!streamEnabled) return void 0;
|
|
162
162
|
if (typeof window === "undefined") return void 0;
|
|
163
|
-
subscriptionRef.current =
|
|
163
|
+
subscriptionRef.current = _chunkIBUFFKAKcjs.createSseSubscription.call(void 0, {
|
|
164
164
|
url: streamUrl,
|
|
165
165
|
onEvent: (name, data) => handlersRef.current.onEvent(name, data),
|
|
166
166
|
onStatusChange: (status) => handlersRef.current.onStatus(status),
|
|
@@ -275,4 +275,4 @@ var TOAST_COPY = {
|
|
|
275
275
|
|
|
276
276
|
|
|
277
277
|
exports.useOptionalTicketLive = useOptionalTicketLive; exports.useTicketLive = useTicketLive; exports.TicketLiveProvider = TicketLiveProvider; exports.isOptimistic = isOptimistic; exports.TICKET_TEXT_MAX_CHARS = TICKET_TEXT_MAX_CHARS; exports.TICKET_MARK_READ_DEBOUNCE_MS = TICKET_MARK_READ_DEBOUNCE_MS; exports.TOAST_COPY = TOAST_COPY;
|
|
278
|
-
//# sourceMappingURL=chunk-
|
|
278
|
+
//# sourceMappingURL=chunk-II5GVLTN.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-RMNWN5RC.cjs","../src/components/tickets/ticket-live-provider.tsx","../src/components/tickets/types.ts"],"names":[],"mappings":"AAAA,6xBAAY;AACZ;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACiBA,mDAA+B;AAC/B,4EAAkB;AA2YT,+CAAA;AAjYT,IAAM,uBAAA,EAAyB,qBAAA;AAC/B,IAAM,qBAAA,EAAuB,mBAAA;AAE7B,IAAM,cAAA,EAAqC,EAAE,WAAA,EAAa,CAAA,EAAG,OAAA,EAAS,CAAC,CAAA,EAAG,cAAA,EAAgB,CAAC,EAAE,CAAA;AAM7F,IAAM,QAAA,EAAU,CAAC,KAAA,EAAA,GAA6C;AAC5D,EAAA,GAAA,CAAI,CAAC,KAAA,EAAO,OAAO,CAAA;AACnB,EAAA,MAAM,GAAA,EAAK,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA;AAC3B,EAAA,OAAO,MAAA,CAAO,KAAA,CAAM,EAAE,EAAA,EAAI,EAAA,EAAI,EAAA;AAChC,CAAA;AAIA,IAAM,uBAAA,EAAyB,IAAA;AA6B/B,IAAM,kBAAA,EAAoB,eAAA,CAAM,aAAA,CAA6C,IAAI,CAAA;AAE1E,SAAS,qBAAA,CAAA,EAAuD;AACrE,EAAA,OAAO,eAAA,CAAM,UAAA,CAAW,iBAAiB,CAAA;AAC3C;AAEO,S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AM,WAAA,EAAa;AAAA,EACxB,YAAA,EAAc,EAAE,KAAA,EAAO,eAAA,EAAiB,WAAA,EAAa,uDAAuD,CAAA;AAAA,EAC5G,mBAAA,EAAqB,EAAE,KAAA,EAAO,eAAA,EAAiB,WAAA,EAAa,sDAAiD,CAAA;AAAA,EAC7G,aAAA,EAAe,EAAE,KAAA,EAAO,gBAAgB,CAAA;AAAA,EACxC,cAAA,EAAgB,EAAE,KAAA,EAAO,kBAAkB,CAAA;AAAA,EAC3C,eAAA,EAAiB,EAAE,KAAA,EAAO,gBAAgB,CAAA;AAAA,EAC1C,cAAA,EAAgB,EAAE,KAAA,EAAO,iBAAiB;AAAA;AAE5C,CAAA;AF1DA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,gVAAC","file":"/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-RMNWN5RC.cjs","sourcesContent":[null,"'use client';\n\n/**\n * TicketLiveProvider — the ONE client home for support-ticket realtime.\n *\n * DOMAIN logic only — connection lifecycle (subscribed-confirm, server\n * retry grace, failed-reconnect pacing, hidden-tab suspend/resume) is\n * owned entirely by the common SSE client (`createSseSubscription`);\n * this provider consumes its consolidated `onConnectedChange` signal.\n *\n * Owns:\n * - the unread summary — delivered EXCLUSIVELY by the stream\n * (`ticket-summary` frames on connect + debounced after events) and\n * by `ticket-read` responses. The client holds NO summary fetch\n * path: resync-on-(re)connect is served by the SERVER (every\n * connect pushes a fresh summary);\n * - query invalidation on events (list + open drawer refresh live);\n * - `markRead` with local write-through zeroing for 0-latency,\n * reconciled by the response's server-computed summary;\n * - the ticket-contract `no-stream` (204) retry policy.\n *\n * There is NO polling anywhere and NO summary endpoint. Hosts whose\n * stream endpoint 404s (terminal) or is absent get no unread indication\n * — the indication IS a realtime feature.\n *\n * Invalidation semantics on events — deliberately `invalidateQueries`,\n * NOT `setQueryData` patches: the ticket hooks run `gcTime: 0`, so\n * there is usually no cache entry to patch, and `TicketsCacheSlot`\n * shape rules apply when there is.\n */\n\nimport { useQueryClient } from '@tanstack/react-query';\nimport React from 'react';\nimport { useChatRuntime } from '../../contexts/chat-runtime-context';\nimport { embedAuthedFetch } from '../../utils/embed-authed-fetch';\nimport { createSseSubscription, type SseSubscription, type SseTransportStatus } from '../../utils/sse-subscription';\nimport { useChatIdentity } from '../chat/hooks/use-chat-identity';\nimport type { TicketMessageStreamData, TicketStreamEvent, TicketUnreadSummary } from './types';\n\n// Ticket realtime is its OWN api surface — deliberately NOT under\n// `/api/chat/agent/*` (that prefix is the chat agent's tool surface;\n// ticket streaming/read-receipts are unrelated to chat).\nconst TICKET_STREAM_ENDPOINT = '/api/tickets/stream';\nconst TICKET_READ_ENDPOINT = '/api/tickets/read';\n\nconst EMPTY_SUMMARY: TicketUnreadSummary = { totalUnread: 0, tickets: {}, latestUnreadAt: {} };\n\n/** ISO stamps can carry mixed timezone offsets (server `+00:00` vs an\n * optimistic local `Z`) — lexicographic string comparison mis-orders\n * those, so every stamp comparison goes through parsed epoch ms.\n * Missing/unparseable stamps sort oldest. */\nconst stampMs = (stamp: string | null | undefined): number => {\n if (!stamp) return 0;\n const ms = Date.parse(stamp);\n return Number.isNaN(ms) ? 0 : ms;\n};\n\n/** Trailing debounce for event-burst invalidations (an agent pasting 5\n * messages must not fire 5 list refetches). */\nconst INVALIDATE_DEBOUNCE_MS = 1_500;\n\nexport interface TicketLiveContextValue {\n /** Viewer has a resolved, non-anon chat identity. Surfaces (e.g. the\n * header cell) hide themselves when false — computed here so they\n * don't each spin up their own identity resolution. */\n authed: boolean;\n /** Realtime-subscribed (server-confirmed), not merely HTTP-open. */\n connected: boolean;\n /** Unread total across tickets — drives the header count badge. */\n unreadTotal: number;\n /** Per-ticket unread counts (missing key = 0) — drives row dots.\n * The currently-open ticket is masked to 0. */\n unreadByTicket: Record<string, number>;\n /** The ticket with the NEWEST unread reply (open ticket excluded) —\n * the header cell routes to it via the SSOT deep link\n * (`buildTicketOpenHref`). Null when nothing is unread. */\n nextUnreadTicketId: string | null;\n /** Mark a ticket read: POSTs the receipt, zeroes the ticket locally\n * (0-latency), then applies the response's server-computed summary. */\n markRead: (ticketExternalId: string) => Promise<void>;\n /** Drawer open/close registration — suppresses unread bumps for the\n * open ticket and masks it in the derived map. */\n setOpenTicketId: (ticketExternalId: string | null) => void;\n /** Hint that the viewer just created a ticket — reconnects the stream\n * (fresh ownership set + fresh server-pushed summary). */\n notifyTicketCreated: () => void;\n}\n\nconst TicketLiveContext = React.createContext<TicketLiveContextValue | null>(null);\n\nexport function useOptionalTicketLive(): TicketLiveContextValue | null {\n return React.useContext(TicketLiveContext);\n}\n\nexport function useTicketLive(): TicketLiveContextValue {\n const ctx = React.useContext(TicketLiveContext);\n if (!ctx) {\n throw new Error('useTicketLive must be used within <TicketLiveProvider>');\n }\n return ctx;\n}\n\nfunction isTicketMessageData(value: unknown): value is TicketMessageStreamData {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as TicketMessageStreamData).ticket_external_id === 'string'\n );\n}\n\nfunction isSummaryData(value: unknown): value is TicketUnreadSummary {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as TicketUnreadSummary).totalUnread === 'number' &&\n typeof (value as TicketUnreadSummary).tickets === 'object'\n );\n}\n\nexport interface TicketLiveProviderProps {\n children: React.ReactNode;\n /**\n * Whether ticket realtime is available to this host at all (feature flag,\n * session, entitlement). `false` provides NO context — `useOptionalTicketLive()`\n * reads `null`, `useTicketLive()` throws, and no identity or stream request is\n * made: byte-for-byte what a host got by not mounting this at all.\n *\n * It exists so a host never has to mount this CONDITIONALLY. A host that writes\n * `enabled ? <TicketLiveProvider>{children}</TicketLiveProvider> : <>{children}</>`\n * changes the element TYPE at that position the moment its flag answers, and React\n * tears down and remounts everything below. In openframe-frontend that wrapper sat\n * around the whole `AppLayout`, so every cold load remounted the app shell and the\n * page under it — visibly, as a chat drawer opened by a deep link replaying its\n * open animation. Mount it always and pass the answer here instead.\n *\n * One consequence of mounting it always: a `ChatRuntime` must be above it even\n * while disabled. The identity resolver reads one unconditionally (Rules of\n * Hooks) and throws without it; `enabled` gates the request, not the read.\n */\n enabled?: boolean;\n}\n\nexport function TicketLiveProvider({ children, enabled = true }: TicketLiveProviderProps) {\n const runtime = useChatRuntime();\n const identity = useChatIdentity(enabled);\n const queryClient = useQueryClient();\n\n const streamUrl = runtime?.endpoints.ticketStreamUrl ?? TICKET_STREAM_ENDPOINT;\n const readUrl = runtime?.endpoints.ticketReadUrl ?? TICKET_READ_ENDPOINT;\n\n // Gates the stream below (via `streamEnabled`) as well as every surface that\n // reads `authed` — one predicate, so a disabled provider is also a silent one.\n const authed = enabled && identity.authTier !== 'anon' && !!identity.user?.email;\n\n const [connected, setConnected] = React.useState(false);\n // The SINGLE unread source — written ONLY from server-computed\n // summaries (stream frames + markRead responses) plus the two\n // 0-latency optimistic writes (event bump, markRead zero), both\n // reconciled by the next server summary.\n const [summary, setSummary] = React.useState<TicketUnreadSummary>(EMPTY_SUMMARY);\n // State + ref for the open drawer: state drives the derived map,\n // the ref lets stream callbacks read it without re-subscribing.\n const [openTicketIdState, setOpenTicketIdState] = React.useState<string | null>(null);\n const openTicketIdRef = React.useRef<string | null>(null);\n\n // ---- Debounced (trailing) invalidation of ticket queries on events ----\n const pendingTicketIdsRef = React.useRef<Set<string>>(new Set());\n const invalidateTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const flushInvalidations = React.useCallback(() => {\n invalidateTimerRef.current = null;\n const ids = Array.from(pendingTicketIdsRef.current);\n pendingTicketIdsRef.current.clear();\n void queryClient.invalidateQueries({ queryKey: ['tickets'] });\n for (const id of ids) {\n void queryClient.invalidateQueries({ queryKey: ['ticket-engagements', id] });\n }\n }, [queryClient]);\n const scheduleInvalidation = React.useCallback(\n (ticketId?: string) => {\n if (ticketId) pendingTicketIdsRef.current.add(ticketId);\n if (invalidateTimerRef.current) return;\n invalidateTimerRef.current = setTimeout(flushInvalidations, INVALIDATE_DEBOUNCE_MS);\n },\n [flushInvalidations],\n );\n\n // ---- Optimistic unread writes (reconciled by server summaries) ----\n const bumpUnread = React.useCallback((ticketId: string, createdAt?: string | null) => {\n setSummary(prev => {\n const stamp = createdAt ?? new Date().toISOString();\n const existing = prev.latestUnreadAt[ticketId];\n return {\n totalUnread: prev.totalUnread + 1,\n tickets: { ...prev.tickets, [ticketId]: (prev.tickets[ticketId] ?? 0) + 1 },\n latestUnreadAt: {\n ...prev.latestUnreadAt,\n [ticketId]: existing && stampMs(existing) > stampMs(stamp) ? existing : stamp,\n },\n };\n });\n }, []);\n\n const zeroUnread = React.useCallback((ticketId: string) => {\n setSummary(prev => {\n const current = prev.tickets[ticketId] ?? 0;\n if (current === 0) return prev;\n const tickets = { ...prev.tickets };\n delete tickets[ticketId];\n const latestUnreadAt = { ...prev.latestUnreadAt };\n delete latestUnreadAt[ticketId];\n return { totalUnread: Math.max(0, prev.totalUnread - current), tickets, latestUnreadAt };\n });\n }, []);\n\n // ---- Stream lifecycle (owned by the SSE CLIENT — the provider only\n // consumes its consolidated signals) ----\n const subscriptionRef = React.useRef<SseSubscription | null>(null);\n const noStreamRef = React.useRef(false);\n\n // Stable handler refs so the subscription effect doesn't churn.\n const handlersRef = React.useRef<{\n onEvent: (eventName: string, data: unknown) => void;\n onStatus: (status: SseTransportStatus) => void;\n onConnected: (connected: boolean) => void;\n }>({ onEvent: () => {}, onStatus: () => {}, onConnected: () => {} });\n\n const handleConnected = (isConnected: boolean) => {\n setConnected(isConnected);\n if (isConnected) {\n // Event-gap healing on every (re)connect: the SERVER pushes a\n // fresh summary; the open drawer refetches through the ACL'd path.\n const openId = openTicketIdRef.current;\n if (openId) {\n void queryClient.invalidateQueries({ queryKey: ['ticket-engagements', openId] });\n }\n }\n };\n\n const handleEvent = (eventName: string, data: unknown) => {\n if (eventName === 'ticket-summary') {\n const frame = data as TicketStreamEvent | null;\n if (isSummaryData(frame?.data)) {\n setSummary({\n totalUnread: frame.data.totalUnread,\n tickets: frame.data.tickets ?? {},\n latestUnreadAt: frame.data.latestUnreadAt ?? {},\n });\n }\n return;\n }\n\n if (eventName === 'ticket-resync') {\n // Ownership gained / degraded payload — a fresh ticket-summary\n // frame follows from the server; refresh the query surfaces.\n scheduleInvalidation();\n return;\n }\n\n if (eventName === 'ticket-status') {\n // Meaningful ticket-row change (close/reopen/pipeline move). The\n // server pushes an updated summary right after (closures count as\n // unread server-side); here we just refresh the query surfaces so\n // the status badge flips live.\n const frame = data as TicketStreamEvent | null;\n const ticketId = (frame?.data as { ticket_external_id?: string } | undefined)?.ticket_external_id;\n scheduleInvalidation(ticketId);\n return;\n }\n\n if (eventName === 'ticket-message') {\n const frame = data as TicketStreamEvent | null;\n const payload = frame?.data;\n if (!isTicketMessageData(payload)) {\n scheduleInvalidation();\n return;\n }\n // Always invalidate (own replies from another tab render live);\n // bump unread ONLY on the server-stamped predicate, and never for\n // the ticket whose drawer is open. The server's debounced summary\n // push reconciles moments later.\n scheduleInvalidation(payload.ticket_external_id);\n if (payload.countsAsUnread && payload.ticket_external_id !== openTicketIdRef.current) {\n bumpUnread(payload.ticket_external_id, payload.hubspot_created_at);\n }\n }\n };\n\n const handleStatus = (status: SseTransportStatus) => {\n // The client owns connection lifecycle (confirm timeout, server\n // retry grace, failed-reconnect pacing, hidden-suspend). The only\n // transport status with DOMAIN meaning is the ticket contract's\n // `no-stream` (204 = zero owned tickets): remember it so a domain\n // signal (own create_ticket, window focus) can retry.\n if (status === 'open') noStreamRef.current = false;\n if (status === 'no-stream') noStreamRef.current = true;\n };\n\n // Publish the three handlers into the stable ref. In an unconditional effect\n // rather than in the render body: every caller is an SSE transport callback,\n // which can only fire after a commit, and a render attempt React discards\n // must not be able to leave a handler behind that closes over state the user\n // never saw. Declared BEFORE the subscription effect so it is filled first\n // in the same flush.\n React.useEffect(() => {\n handlersRef.current.onConnected = handleConnected;\n handlersRef.current.onEvent = handleEvent;\n handlersRef.current.onStatus = handleStatus;\n });\n\n // Mount/unmount of the subscription — gated on auth + a usable URL.\n const streamEnabled = authed && !!streamUrl;\n React.useEffect(() => {\n if (!streamEnabled) return undefined;\n if (typeof window === 'undefined') return undefined;\n\n subscriptionRef.current = createSseSubscription({\n url: streamUrl,\n onEvent: (name, data) => handlersRef.current.onEvent(name, data),\n onStatusChange: status => handlersRef.current.onStatus(status),\n onConnectedChange: isConnected => handlersRef.current.onConnected(isConnected),\n // Long-lived per-user stream: suspend while hidden (scale relief),\n // resume + reconnect on visible/online — all inside the client.\n pauseWhenHidden: true,\n });\n\n const retryIfIdle = () => {\n // After a 204 (no-stream), a focus signal is the retry trigger.\n if (noStreamRef.current) {\n noStreamRef.current = false;\n subscriptionRef.current?.reconnectNow();\n }\n };\n window.addEventListener('focus', retryIfIdle);\n\n return () => {\n window.removeEventListener('focus', retryIfIdle);\n if (invalidateTimerRef.current) {\n clearTimeout(invalidateTimerRef.current);\n invalidateTimerRef.current = null;\n }\n subscriptionRef.current?.close();\n subscriptionRef.current = null;\n setConnected(false);\n setSummary(EMPTY_SUMMARY);\n };\n // handlersRef is stable; streamUrl/auth changes remount the stream.\n }, [streamEnabled, streamUrl]);\n\n // ---- Public API ----\n const markRead = React.useCallback(\n async (ticketExternalId: string) => {\n try {\n const response = await embedAuthedFetch(readUrl, {\n method: 'POST',\n body: JSON.stringify({ ticket_id: ticketExternalId }),\n });\n if (!response.ok) return;\n // 0-latency local zero, then reconcile with the response's\n // server-computed summary (THE truth — includes closure\n // accounting and other tickets).\n zeroUnread(ticketExternalId);\n const body = (await response.json().catch(() => null)) as { summary?: TicketUnreadSummary } | null;\n if (isSummaryData(body?.summary)) {\n setSummary({\n totalUnread: body.summary.totalUnread,\n tickets: body.summary.tickets ?? {},\n latestUnreadAt: body.summary.latestUnreadAt ?? {},\n });\n }\n } catch {\n // Non-fatal — the receipt lands on the next markRead; unread\n // state reconciles via the next server summary push.\n }\n },\n [readUrl, zeroUnread],\n );\n\n const setOpenTicketId = React.useCallback((ticketExternalId: string | null) => {\n openTicketIdRef.current = ticketExternalId;\n setOpenTicketIdState(ticketExternalId);\n }, []);\n\n const notifyTicketCreated = React.useCallback(() => {\n // Fresh connect → fresh ownership set + fresh server summary\n // (covers both the no-stream 204 wait state and an already-live\n // stream whose set predates the new ticket).\n noStreamRef.current = false;\n subscriptionRef.current?.reconnectNow();\n }, []);\n\n // Derived unread map — open ticket masked to 0 so a server summary\n // landing inside the markRead debounce window can't transiently\n // re-badge it.\n const value = React.useMemo<TicketLiveContextValue>(() => {\n let unreadByTicket = summary.tickets;\n let unreadTotal = summary.totalUnread;\n if (openTicketIdState && unreadByTicket[openTicketIdState]) {\n const masked = unreadByTicket[openTicketIdState];\n unreadByTicket = { ...unreadByTicket };\n delete unreadByTicket[openTicketIdState];\n unreadTotal = Math.max(0, unreadTotal - masked);\n }\n // Ticket with the NEWEST unread reply (compared as parsed epoch ms\n // via `stampMs` — mixed timezone offsets break string ordering) —\n // header cell routes there. Falls back to any unread key if a\n // timestamp is missing.\n let nextUnreadTicketId: string | null = null;\n let nextStampMs = 0;\n for (const id of Object.keys(unreadByTicket)) {\n const ms = stampMs(summary.latestUnreadAt[id]);\n if (nextUnreadTicketId === null || ms > nextStampMs) {\n nextUnreadTicketId = id;\n nextStampMs = ms;\n }\n }\n return {\n authed,\n connected,\n unreadTotal,\n unreadByTicket,\n nextUnreadTicketId,\n markRead,\n setOpenTicketId,\n notifyTicketCreated,\n };\n }, [summary, authed, connected, openTicketIdState, markRead, setOpenTicketId, notifyTicketCreated]);\n\n return <TicketLiveContext.Provider value={enabled ? value : null}>{children}</TicketLiveContext.Provider>;\n}\n","/**\n * Wire shape of a row returned by `POST /api/chat/agent/find-ticket`.\n * Mirrors the executor's projection at `lib/data/hubspot-tools.ts`\n * (`FIND_TICKET_SELECT` / `FindTicketResult`).\n *\n * Cross-repo duplication is INTENTIONAL: this lib ships independently\n * of the hub, so we can't import `FindTicketResult` from\n * `hubspot-tools.ts` directly. If the server adds a column to\n * `FIND_TICKET_SELECT`, also add it here. The smoke test in §F of the\n * plan covers the happy path; a wire-contract test belongs in the hub.\n *\n * `find-ticket` returns `customer_emails: string[]` (jsonb array), NOT\n * a single `customer_email`. The list is server-self-scoped to the\n * caller's session email; the array is exposed for admin/staff\n * surfaces, which the ticket center doesn't render.\n */\nexport interface TicketData {\n id: string;\n /** HubSpot ticket id (display number, e.g. \"1234\"). */\n external_id: string;\n subject: string | null;\n /** Short (≤400 char) HTML-stripped preview of the ticket body —\n * used for the list-card subtitle when needed. */\n preview: string | null;\n /** Longer (≤4k char) sanitized body. INCLUDES every appended\n * `content_addendum` comment because the `update_ticket` executor\n * reads + re-writes the `content` property server-side with a\n * `---` separator. Render this in the drawer's description block\n * and the user sees both the original message + every comment they\n * (or staff) added. */\n body: string | null;\n /** Canonical OPEN | CLOSED (HubSpot pipeline derived). */\n status: string | null;\n /** Human label like \"New\" / \"Working on it\" / \"Waiting on contact\" /\n * \"Closed\". Drives the badge text; canonical status drives color. */\n pipeline_stage_label: string | null;\n clickup_task_id: string | null;\n /** Snapshot of the linked ClickUp delivery task — populated server-side\n * via the `clickup_tasks` mirror when `clickup_task_id` is set. Drives\n * the \"Linked delivery\" card surface on the ticket drawer (status\n * badge + ClickUp deep link). `null` when no link OR the ClickUp row\n * was deleted / not yet synced. */\n clickup: TicketClickupSummary | null;\n priority: string | null;\n customer_emails: string[];\n customer_company: string | null;\n /** HubSpot contact's display name. Drives the customer attribution\n * on the drawer when the viewer is NOT the customer themselves\n * (admin browsing / multi-contact second viewer). Conversations\n * API messages don't carry per-message sender info on Custom\n * Channels, so this is the only reliable source for \"what's the\n * customer's name.\" */\n customer_name: string | null;\n /** HubSpot owner id of the agent assigned to this ticket. Carried as\n * raw id for debugging; rendering goes through `assignedOwner`. Null\n * when unassigned. */\n assigned_to: string | null;\n /** Resolved assigned-owner profile — name + email + avatar. Populated\n * server-side via `attachOwnerProfiles` which joins through the\n * `hubspot_owners` mirror to `profiles` by email. Drives the\n * \"Assigned to\" attribution in the drawer header. Null when\n * unassigned OR the owner couldn't be resolved (rare — only when\n * the agent was deleted from HubSpot between the ticket update and\n * the next owners reconcile). */\n assignedOwner: TicketAssignedOwner | null;\n hubspot_updated_at: string;\n}\n\n/** Resolved profile of a ticket's assigned agent — surfaced in the\n * drawer header. Subset of the server's `MirroredOwnerProfile`\n * trimmed to just the rendering fields. */\nexport interface TicketAssignedOwner {\n name: string | null;\n email: string | null;\n avatarUrl: string | null;\n}\n\n/** Compact projection of a linked ClickUp task — matches the server's\n * `ClickupSummary` and aligns with `DeliveryItem` so the linked-card\n * on a ticket can render through the same `DeliveryRow` primitive used\n * on `/bug-fixes-and-enhancements`. */\nexport interface TicketClickupSummary {\n /** ClickUp task external_id (e.g. \"86ad4e022\"). Used as the\n * `?focus=<id>` URL param to scroll the public delivery page to\n * this row. */\n external_id: string;\n title: string | null;\n description: string | null;\n /** ClickUp status name — e.g. \"complete\" / \"working\" / \"design approved\"\n * / \"waiting for release\". Used as the badge label. */\n status: string | null;\n /** ClickUp's per-status hex color (e.g. \"#008844\"). Forwarded to the\n * badge so colors match the ClickUp board exactly. */\n status_color: string | null;\n /** Bucket — `'backlog' | 'working' | 'complete' | 'unknown'`. Used as\n * a fallback when status_color is missing. */\n status_category: string | null;\n /** ClickUp custom item label (`'Bug'` / `'Request'`) — drives the\n * type badge (\"BUG-FIX\" / \"ENHANCEMENT\"). */\n task_type: string | null;\n custom_item_id: number | null;\n /** Every ClickUp list the task is associated with. UI joins with \", \". */\n list_names: string[];\n /** Unix-ms timestamps so the row's \"ACTIVE X ago\" subtitle uses the\n * shared `getRelativeTime()` helper. */\n date_opened: number | null;\n date_updated: number | null;\n date_closed: number | null;\n /** Direct https://app.clickup.com/t/<id> deep link. Kept on the wire\n * for admin surfaces; the customer-facing linked card navigates\n * internally instead. */\n clickup_url: string | null;\n /** Composed server-side via the SAME `buildDevSectionUrl` helper the\n * chat-inline delivery card uses. Carries `?search=<id>` so the\n * delivery list filters to that single task on landing. */\n delivery_href: string;\n /** Target platform name for the host's `useNavLink` to decide\n * same-tab vs new-tab on cross-platform links. */\n delivery_target_platform: string;\n /** Release version label set by the delivery team, e.g. \"0.9\" / \"1.0\".\n * Shown beside the status when present. */\n target_version: string | null;\n}\n\n/**\n * Optimistic placeholder a `submitTicket` call prepends to the list\n * BEFORE the server roundtrip resolves. Drawer is hidden until the\n * real id arrives. The wrapper destructures `_optimistic` before\n * forwarding to `<ChatTicketItem>` so the DOM doesn't see an unknown\n * prop.\n */\nexport interface OptimisticTicket extends TicketData {\n _optimistic: true;\n}\n\nexport type AnyTicket = TicketData | OptimisticTicket;\n\nexport function isOptimistic(t: AnyTicket): t is OptimisticTicket {\n return (t as OptimisticTicket)._optimistic === true;\n}\n\n/**\n * Shape of a single `['tickets', …]` TanStack-Query cache slot.\n * Mirrors `FindTicketResponse` in `hooks/use-tickets-list.ts` — kept\n * here because the cache-mutation call sites in `useTicketActions` and\n * `<HelpCenterList>` would otherwise have to redeclare the shape inline.\n *\n * A 2026-05-29 prod regression (`t.map is not a function` on\n * close/reopen) was caused by assuming the cache held a bare\n * `TicketData[]` instead of this wrapper — every helper that calls\n * `queryClient.setQueriesData` / `getQueriesData` on `['tickets']`\n * MUST type the value through this shape and project / reassemble\n * `tickets` explicitly.\n */\nexport interface TicketsCacheSlot {\n tickets?: TicketData[];\n count?: number;\n totalCount?: number;\n page?: number;\n pageSize?: number;\n totalPages?: number;\n scope?: 'self' | 'all';\n}\n\n/**\n * Stable server-side error codes the ticket-action helpers route\n * through `mapTicketActionError`. Anything else is treated as a generic\n * server error.\n *\n * Reply-specific codes (`HUBSPOT_5XX` / `HUBSPOT_400_VALIDATION` /\n * `HUBSPOT_404_THREAD` / `HUBSPOT_REPLY_UNKNOWN`) drive the drawer\n * banner that appears above the composer when a customer reply fails.\n * Distinct from `HUBSPOT_DISCONNECTED` (whole-system) and\n * `TICKET_NOT_FOUND` (terminal-row) — the reply codes are per-attempt\n * + retryable except for `HUBSPOT_404_THREAD`.\n */\nexport type TicketActionErrorCode =\n | 'PROPOSAL_NOT_CLAIMABLE'\n | 'TICKET_NOT_FOUND'\n | 'TICKET_OWNERSHIP_DENIED'\n | 'HUBSPOT_DISCONNECTED'\n | 'RATE_LIMITED'\n | 'INVALID_TOOL_ARGS'\n | 'HUBSPOT_5XX'\n | 'HUBSPOT_400_VALIDATION'\n | 'HUBSPOT_404_THREAD'\n | 'HUBSPOT_REPLY_UNKNOWN'\n | 'UNKNOWN';\n\nexport interface MappedTicketActionError {\n code: TicketActionErrorCode;\n /** Human-readable copy safe to show in a toast. */\n message: string;\n /** When true, the form should disable submit + show the\n * support-down banner. Set only for HUBSPOT_DISCONNECTED. */\n supportSystemDown: boolean;\n /** When true, the helper should remove the affected row optimistically\n * (TICKET_NOT_FOUND). */\n removeRowFromCache: boolean;\n /** Retry hint surfaced from a 429 response. Caller decides whether\n * to mention it in the toast. */\n retryAfterSeconds?: number;\n}\n\n/**\n * Defensive client-side cap on ticket text (initial content + comment\n * addendums). HubSpot Note engagements accept more, but a 100KB paste\n * should fail fast at the UI rather than burning a server round-trip.\n * Both the open-ticket form and the per-row comment textarea import\n * this so a future server-side hardening only touches one place.\n */\nexport const TICKET_TEXT_MAX_CHARS = 5000;\n\n/**\n * Wire contract of the ticket live stream (`GET /api/chat/agent/\n * ticket-stream`, SSE). Producer (the hub route's `mapEvent`) imports\n * THIS type — same producer/consumer SSOT pattern as\n * `ConversationEngagementWire = TicketEngagement`. A schema drift here\n * would be a silent serialization bug; keep one named contract.\n *\n * Frames carry METADATA ONLY — never message bodies. Content is always\n * refetched through the ACL'd `list-engagements` path (one read path).\n *\n * Event names (`eventType`):\n * - `ticket-message` — a message row landed in the mirror for one of\n * the viewer's tickets. `data` carries the metadata.\n * - `ticket-status` — a MEANINGFUL ticket-row change (status /\n * pipeline stage / closure) landed in the mirror. Server-side\n * old-vs-new diffing drops no-op writes (sync stamps). Clients\n * invalidate + refetch the summary (closures count as unread\n * server-side via `closed_at` vs the read receipt).\n * - `ticket-summary` — the server-computed `TicketUnreadSummary`.\n * THE stream is the summary webservice: pushed on connect (server-\n * side resync-on-reconnect) and re-pushed (debounced) after every\n * delivered event. Clients hold NO summary fetch path.\n * - `ticket-resync` — degraded frame: something happened that the\n * server couldn't fully describe (truncated Realtime payload, or\n * the connection's ownership set just gained tickets). A fresh\n * `ticket-summary` follows it; clients invalidate queries.\n *\n * The server also emits `status` frames (`subscribed` / `retrying` /\n * `reconnect_failed`) from the shared SSE utility — clients derive\n * `connected` from those, NOT from the HTTP stream being open.\n */\nexport type TicketStreamEventType = 'ticket-message' | 'ticket-status' | 'ticket-summary' | 'ticket-resync';\n\n/** Metadata payload of a `ticket-message` frame. */\nexport type TicketMessageStreamData = {\n ticket_external_id: string;\n /** Mirror row's HubSpot message id. */\n message_id: string;\n /** Server-stamped via the same direction predicate the wire mapper\n * uses. Clients never re-derive author classification. */\n authorRole: 'customer' | 'support';\n /** Server-stamped via the visibility+direction unread predicate\n * (`countsAsUnread` in the hub's conversations DAL). ONLY frames\n * with `true` may bump client-side unread state. */\n countsAsUnread: boolean;\n hubspot_created_at: string | null;\n};\n\n/** Metadata payload of a `ticket-status` frame. */\nexport type TicketStatusStreamData = {\n ticket_external_id: string;\n /** Canonical OPEN | CLOSED after the change. */\n status: string | null;\n pipeline_stage_label: string | null;\n closed_at: string | null;\n};\n\nexport interface TicketStreamEvent {\n eventType: TicketStreamEventType;\n /** Human-readable label (SSE envelope compat) — clients ignore it. */\n message: string;\n /** `ticket-message` → TicketMessageStreamData; `ticket-status` →\n * TicketStatusStreamData; `ticket-summary` → TicketUnreadSummary;\n * absent on `ticket-resync`. */\n data?: TicketMessageStreamData | TicketStatusStreamData | TicketUnreadSummary;\n}\n\n/**\n * The SINGLE unread source, delivered EXCLUSIVELY over the stream\n * (`ticket-summary` frames on connect + after events) and in\n * `ticket-read` responses. There is no summary fetch endpoint. Header\n * badge total AND per-row dots both read this via the\n * `TicketLiveProvider` map; missing keys mean 0.\n */\nexport type TicketUnreadSummary = {\n totalUnread: number;\n tickets: Record<string, number>;\n /** ISO timestamp of the NEWEST unread message per ticket (same keys as\n * `tickets`). Drives \"route to the most recent update\" on the header\n * cell: the ticket with the max value here is `nextUnreadTicketId`. */\n latestUnreadAt: Record<string, string>;\n};\n\n/**\n * Trailing debounce for `markRead` while the drawer is open and new\n * messages stream in — flushed on drawer close so a fast open/close\n * still persists the receipt. Named beside its sibling cadences so\n * every timing knob lives in one file.\n */\nexport const TICKET_MARK_READ_DEBOUNCE_MS = 2000;\n\n/**\n * Ticket deep-link SSOT — DEFINED in the server-safe param-keys module\n * (`utils/dev-sections/dev-section-param-keys.ts`, beside its sibling\n * `devSectionAnchorId`) because producers span both worlds: the hub's\n * SERVER-side chat-ref builder and the client header cell. Re-exported\n * here so ticket-surface consumers keep one import home.\n */\nexport { TICKET_OPEN_PARAM, buildTicketOpenHref } from '../../utils/dev-sections/dev-section-param-keys';\n\n/**\n * Centralized toast copy. Keep all wording here so QA / localization\n * can find every user-visible string in one file.\n */\nexport const TOAST_COPY = {\n open_success: { title: 'Ticket opened', description: 'We received your message and will follow up shortly.' },\n open_mirror_pending: { title: 'Ticket opened', description: 'Syncing — your ticket will appear momentarily.' },\n close_success: { title: 'Ticket closed' },\n reopen_success: { title: 'Ticket reopened' },\n comment_success: { title: 'Comment added' },\n attach_success: { title: 'Files attached' },\n // Failure variants are constructed dynamically from MappedTicketActionError.\n} as const;\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-II5GVLTN.cjs","../src/components/tickets/ticket-live-provider.tsx","../src/components/tickets/types.ts"],"names":[],"mappings":"AAAA,6xBAAY;AACZ;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACiBA,mDAA+B;AAC/B,4EAAkB;AA2YT,+CAAA;AAjYT,IAAM,uBAAA,EAAyB,qBAAA;AAC/B,IAAM,qBAAA,EAAuB,mBAA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ACL,MAAA;AAAA,MACA,SAAA;AAAA,MACA,WAAA;AAAA,MACA,cAAA;AAAA,MACA,kBAAA;AAAA,MACA,QAAA;AAAA,MACA,eAAA;AAAA,MACA;AAAA,IACF,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,OAAA,EAAS,MAAA,EAAQ,SAAA,EAAW,iBAAA,EAAmB,QAAA,EAAU,eAAA,EAAiB,mBAAmB,CAAC,CAAA;AAElG,EAAA,uBAAO,6BAAA,iBAAC,CAAkB,QAAA,EAAlB,EAA2B,KAAA,EAAO,QAAA,EAAU,MAAA,EAAQ,IAAA,EAAO,SAAA,CAAS,CAAA;AAC9E;ADjLA;AACA;AEnHO,SAAS,YAAA,CAAa,CAAA,EAAqC;AAChE,EAAA,OAAQ,CAAA,CAAuB,YAAA,IAAgB,IAAA;AACjD;AAwEO,IAAM,sBAAA,EAAwB,GAAA;AA2F9B,IAAM,6BAAA,EAA+B,GAAA;AAerC,IAAM,WAAA,EAAa;AAAA,EACxB,YAAA,EAAc,EAAE,KAAA,EAAO,eAAA,EAAiB,WAAA,EAAa,uDAAuD,CAAA;AAAA,EAC5G,mBAAA,EAAqB,EAAE,KAAA,EAAO,eAAA,EAAiB,WAAA,EAAa,sDAAiD,CAAA;AAAA,EAC7G,aAAA,EAAe,EAAE,KAAA,EAAO,gBAAgB,CAAA;AAAA,EACxC,cAAA,EAAgB,EAAE,KAAA,EAAO,kBAAkB,CAAA;AAAA,EAC3C,eAAA,EAAiB,EAAE,KAAA,EAAO,gBAAgB,CAAA;AAAA,EAC1C,cAAA,EAAgB,EAAE,KAAA,EAAO,iBAAiB;AAAA;AAE5C,CAAA;AF1DA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,gVAAC","file":"/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-II5GVLTN.cjs","sourcesContent":[null,"'use client';\n\n/**\n * TicketLiveProvider — the ONE client home for support-ticket realtime.\n *\n * DOMAIN logic only — connection lifecycle (subscribed-confirm, server\n * retry grace, failed-reconnect pacing, hidden-tab suspend/resume) is\n * owned entirely by the common SSE client (`createSseSubscription`);\n * this provider consumes its consolidated `onConnectedChange` signal.\n *\n * Owns:\n * - the unread summary — delivered EXCLUSIVELY by the stream\n * (`ticket-summary` frames on connect + debounced after events) and\n * by `ticket-read` responses. The client holds NO summary fetch\n * path: resync-on-(re)connect is served by the SERVER (every\n * connect pushes a fresh summary);\n * - query invalidation on events (list + open drawer refresh live);\n * - `markRead` with local write-through zeroing for 0-latency,\n * reconciled by the response's server-computed summary;\n * - the ticket-contract `no-stream` (204) retry policy.\n *\n * There is NO polling anywhere and NO summary endpoint. Hosts whose\n * stream endpoint 404s (terminal) or is absent get no unread indication\n * — the indication IS a realtime feature.\n *\n * Invalidation semantics on events — deliberately `invalidateQueries`,\n * NOT `setQueryData` patches: the ticket hooks run `gcTime: 0`, so\n * there is usually no cache entry to patch, and `TicketsCacheSlot`\n * shape rules apply when there is.\n */\n\nimport { useQueryClient } from '@tanstack/react-query';\nimport React from 'react';\nimport { useChatRuntime } from '../../contexts/chat-runtime-context';\nimport { embedAuthedFetch } from '../../utils/embed-authed-fetch';\nimport { createSseSubscription, type SseSubscription, type SseTransportStatus } from '../../utils/sse-subscription';\nimport { useChatIdentity } from '../chat/hooks/use-chat-identity';\nimport type { TicketMessageStreamData, TicketStreamEvent, TicketUnreadSummary } from './types';\n\n// Ticket realtime is its OWN api surface — deliberately NOT under\n// `/api/chat/agent/*` (that prefix is the chat agent's tool surface;\n// ticket streaming/read-receipts are unrelated to chat).\nconst TICKET_STREAM_ENDPOINT = '/api/tickets/stream';\nconst TICKET_READ_ENDPOINT = '/api/tickets/read';\n\nconst EMPTY_SUMMARY: TicketUnreadSummary = { totalUnread: 0, tickets: {}, latestUnreadAt: {} };\n\n/** ISO stamps can carry mixed timezone offsets (server `+00:00` vs an\n * optimistic local `Z`) — lexicographic string comparison mis-orders\n * those, so every stamp comparison goes through parsed epoch ms.\n * Missing/unparseable stamps sort oldest. */\nconst stampMs = (stamp: string | null | undefined): number => {\n if (!stamp) return 0;\n const ms = Date.parse(stamp);\n return Number.isNaN(ms) ? 0 : ms;\n};\n\n/** Trailing debounce for event-burst invalidations (an agent pasting 5\n * messages must not fire 5 list refetches). */\nconst INVALIDATE_DEBOUNCE_MS = 1_500;\n\nexport interface TicketLiveContextValue {\n /** Viewer has a resolved, non-anon chat identity. Surfaces (e.g. the\n * header cell) hide themselves when false — computed here so they\n * don't each spin up their own identity resolution. */\n authed: boolean;\n /** Realtime-subscribed (server-confirmed), not merely HTTP-open. */\n connected: boolean;\n /** Unread total across tickets — drives the header count badge. */\n unreadTotal: number;\n /** Per-ticket unread counts (missing key = 0) — drives row dots.\n * The currently-open ticket is masked to 0. */\n unreadByTicket: Record<string, number>;\n /** The ticket with the NEWEST unread reply (open ticket excluded) —\n * the header cell routes to it via the SSOT deep link\n * (`buildTicketOpenHref`). Null when nothing is unread. */\n nextUnreadTicketId: string | null;\n /** Mark a ticket read: POSTs the receipt, zeroes the ticket locally\n * (0-latency), then applies the response's server-computed summary. */\n markRead: (ticketExternalId: string) => Promise<void>;\n /** Drawer open/close registration — suppresses unread bumps for the\n * open ticket and masks it in the derived map. */\n setOpenTicketId: (ticketExternalId: string | null) => void;\n /** Hint that the viewer just created a ticket — reconnects the stream\n * (fresh ownership set + fresh server-pushed summary). */\n notifyTicketCreated: () => void;\n}\n\nconst TicketLiveContext = React.createContext<TicketLiveContextValue | null>(null);\n\nexport function useOptionalTicketLive(): TicketLiveContextValue | null {\n return React.useContext(TicketLiveContext);\n}\n\nexport function useTicketLive(): TicketLiveContextValue {\n const ctx = React.useContext(TicketLiveContext);\n if (!ctx) {\n throw new Error('useTicketLive must be used within <TicketLiveProvider>');\n }\n return ctx;\n}\n\nfunction isTicketMessageData(value: unknown): value is TicketMessageStreamData {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as TicketMessageStreamData).ticket_external_id === 'string'\n );\n}\n\nfunction isSummaryData(value: unknown): value is TicketUnreadSummary {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as TicketUnreadSummary).totalUnread === 'number' &&\n typeof (value as TicketUnreadSummary).tickets === 'object'\n );\n}\n\nexport interface TicketLiveProviderProps {\n children: React.ReactNode;\n /**\n * Whether ticket realtime is available to this host at all (feature flag,\n * session, entitlement). `false` provides NO context — `useOptionalTicketLive()`\n * reads `null`, `useTicketLive()` throws, and no identity or stream request is\n * made: byte-for-byte what a host got by not mounting this at all.\n *\n * It exists so a host never has to mount this CONDITIONALLY. A host that writes\n * `enabled ? <TicketLiveProvider>{children}</TicketLiveProvider> : <>{children}</>`\n * changes the element TYPE at that position the moment its flag answers, and React\n * tears down and remounts everything below. In openframe-frontend that wrapper sat\n * around the whole `AppLayout`, so every cold load remounted the app shell and the\n * page under it — visibly, as a chat drawer opened by a deep link replaying its\n * open animation. Mount it always and pass the answer here instead.\n *\n * One consequence of mounting it always: a `ChatRuntime` must be above it even\n * while disabled. The identity resolver reads one unconditionally (Rules of\n * Hooks) and throws without it; `enabled` gates the request, not the read.\n */\n enabled?: boolean;\n}\n\nexport function TicketLiveProvider({ children, enabled = true }: TicketLiveProviderProps) {\n const runtime = useChatRuntime();\n const identity = useChatIdentity(enabled);\n const queryClient = useQueryClient();\n\n const streamUrl = runtime?.endpoints.ticketStreamUrl ?? TICKET_STREAM_ENDPOINT;\n const readUrl = runtime?.endpoints.ticketReadUrl ?? TICKET_READ_ENDPOINT;\n\n // Gates the stream below (via `streamEnabled`) as well as every surface that\n // reads `authed` — one predicate, so a disabled provider is also a silent one.\n const authed = enabled && identity.authTier !== 'anon' && !!identity.user?.email;\n\n const [connected, setConnected] = React.useState(false);\n // The SINGLE unread source — written ONLY from server-computed\n // summaries (stream frames + markRead responses) plus the two\n // 0-latency optimistic writes (event bump, markRead zero), both\n // reconciled by the next server summary.\n const [summary, setSummary] = React.useState<TicketUnreadSummary>(EMPTY_SUMMARY);\n // State + ref for the open drawer: state drives the derived map,\n // the ref lets stream callbacks read it without re-subscribing.\n const [openTicketIdState, setOpenTicketIdState] = React.useState<string | null>(null);\n const openTicketIdRef = React.useRef<string | null>(null);\n\n // ---- Debounced (trailing) invalidation of ticket queries on events ----\n const pendingTicketIdsRef = React.useRef<Set<string>>(new Set());\n const invalidateTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n const flushInvalidations = React.useCallback(() => {\n invalidateTimerRef.current = null;\n const ids = Array.from(pendingTicketIdsRef.current);\n pendingTicketIdsRef.current.clear();\n void queryClient.invalidateQueries({ queryKey: ['tickets'] });\n for (const id of ids) {\n void queryClient.invalidateQueries({ queryKey: ['ticket-engagements', id] });\n }\n }, [queryClient]);\n const scheduleInvalidation = React.useCallback(\n (ticketId?: string) => {\n if (ticketId) pendingTicketIdsRef.current.add(ticketId);\n if (invalidateTimerRef.current) return;\n invalidateTimerRef.current = setTimeout(flushInvalidations, INVALIDATE_DEBOUNCE_MS);\n },\n [flushInvalidations],\n );\n\n // ---- Optimistic unread writes (reconciled by server summaries) ----\n const bumpUnread = React.useCallback((ticketId: string, createdAt?: string | null) => {\n setSummary(prev => {\n const stamp = createdAt ?? new Date().toISOString();\n const existing = prev.latestUnreadAt[ticketId];\n return {\n totalUnread: prev.totalUnread + 1,\n tickets: { ...prev.tickets, [ticketId]: (prev.tickets[ticketId] ?? 0) + 1 },\n latestUnreadAt: {\n ...prev.latestUnreadAt,\n [ticketId]: existing && stampMs(existing) > stampMs(stamp) ? existing : stamp,\n },\n };\n });\n }, []);\n\n const zeroUnread = React.useCallback((ticketId: string) => {\n setSummary(prev => {\n const current = prev.tickets[ticketId] ?? 0;\n if (current === 0) return prev;\n const tickets = { ...prev.tickets };\n delete tickets[ticketId];\n const latestUnreadAt = { ...prev.latestUnreadAt };\n delete latestUnreadAt[ticketId];\n return { totalUnread: Math.max(0, prev.totalUnread - current), tickets, latestUnreadAt };\n });\n }, []);\n\n // ---- Stream lifecycle (owned by the SSE CLIENT — the provider only\n // consumes its consolidated signals) ----\n const subscriptionRef = React.useRef<SseSubscription | null>(null);\n const noStreamRef = React.useRef(false);\n\n // Stable handler refs so the subscription effect doesn't churn.\n const handlersRef = React.useRef<{\n onEvent: (eventName: string, data: unknown) => void;\n onStatus: (status: SseTransportStatus) => void;\n onConnected: (connected: boolean) => void;\n }>({ onEvent: () => {}, onStatus: () => {}, onConnected: () => {} });\n\n const handleConnected = (isConnected: boolean) => {\n setConnected(isConnected);\n if (isConnected) {\n // Event-gap healing on every (re)connect: the SERVER pushes a\n // fresh summary; the open drawer refetches through the ACL'd path.\n const openId = openTicketIdRef.current;\n if (openId) {\n void queryClient.invalidateQueries({ queryKey: ['ticket-engagements', openId] });\n }\n }\n };\n\n const handleEvent = (eventName: string, data: unknown) => {\n if (eventName === 'ticket-summary') {\n const frame = data as TicketStreamEvent | null;\n if (isSummaryData(frame?.data)) {\n setSummary({\n totalUnread: frame.data.totalUnread,\n tickets: frame.data.tickets ?? {},\n latestUnreadAt: frame.data.latestUnreadAt ?? {},\n });\n }\n return;\n }\n\n if (eventName === 'ticket-resync') {\n // Ownership gained / degraded payload — a fresh ticket-summary\n // frame follows from the server; refresh the query surfaces.\n scheduleInvalidation();\n return;\n }\n\n if (eventName === 'ticket-status') {\n // Meaningful ticket-row change (close/reopen/pipeline move). The\n // server pushes an updated summary right after (closures count as\n // unread server-side); here we just refresh the query surfaces so\n // the status badge flips live.\n const frame = data as TicketStreamEvent | null;\n const ticketId = (frame?.data as { ticket_external_id?: string } | undefined)?.ticket_external_id;\n scheduleInvalidation(ticketId);\n return;\n }\n\n if (eventName === 'ticket-message') {\n const frame = data as TicketStreamEvent | null;\n const payload = frame?.data;\n if (!isTicketMessageData(payload)) {\n scheduleInvalidation();\n return;\n }\n // Always invalidate (own replies from another tab render live);\n // bump unread ONLY on the server-stamped predicate, and never for\n // the ticket whose drawer is open. The server's debounced summary\n // push reconciles moments later.\n scheduleInvalidation(payload.ticket_external_id);\n if (payload.countsAsUnread && payload.ticket_external_id !== openTicketIdRef.current) {\n bumpUnread(payload.ticket_external_id, payload.hubspot_created_at);\n }\n }\n };\n\n const handleStatus = (status: SseTransportStatus) => {\n // The client owns connection lifecycle (confirm timeout, server\n // retry grace, failed-reconnect pacing, hidden-suspend). The only\n // transport status with DOMAIN meaning is the ticket contract's\n // `no-stream` (204 = zero owned tickets): remember it so a domain\n // signal (own create_ticket, window focus) can retry.\n if (status === 'open') noStreamRef.current = false;\n if (status === 'no-stream') noStreamRef.current = true;\n };\n\n // Publish the three handlers into the stable ref. In an unconditional effect\n // rather than in the render body: every caller is an SSE transport callback,\n // which can only fire after a commit, and a render attempt React discards\n // must not be able to leave a handler behind that closes over state the user\n // never saw. Declared BEFORE the subscription effect so it is filled first\n // in the same flush.\n React.useEffect(() => {\n handlersRef.current.onConnected = handleConnected;\n handlersRef.current.onEvent = handleEvent;\n handlersRef.current.onStatus = handleStatus;\n });\n\n // Mount/unmount of the subscription — gated on auth + a usable URL.\n const streamEnabled = authed && !!streamUrl;\n React.useEffect(() => {\n if (!streamEnabled) return undefined;\n if (typeof window === 'undefined') return undefined;\n\n subscriptionRef.current = createSseSubscription({\n url: streamUrl,\n onEvent: (name, data) => handlersRef.current.onEvent(name, data),\n onStatusChange: status => handlersRef.current.onStatus(status),\n onConnectedChange: isConnected => handlersRef.current.onConnected(isConnected),\n // Long-lived per-user stream: suspend while hidden (scale relief),\n // resume + reconnect on visible/online — all inside the client.\n pauseWhenHidden: true,\n });\n\n const retryIfIdle = () => {\n // After a 204 (no-stream), a focus signal is the retry trigger.\n if (noStreamRef.current) {\n noStreamRef.current = false;\n subscriptionRef.current?.reconnectNow();\n }\n };\n window.addEventListener('focus', retryIfIdle);\n\n return () => {\n window.removeEventListener('focus', retryIfIdle);\n if (invalidateTimerRef.current) {\n clearTimeout(invalidateTimerRef.current);\n invalidateTimerRef.current = null;\n }\n subscriptionRef.current?.close();\n subscriptionRef.current = null;\n setConnected(false);\n setSummary(EMPTY_SUMMARY);\n };\n // handlersRef is stable; streamUrl/auth changes remount the stream.\n }, [streamEnabled, streamUrl]);\n\n // ---- Public API ----\n const markRead = React.useCallback(\n async (ticketExternalId: string) => {\n try {\n const response = await embedAuthedFetch(readUrl, {\n method: 'POST',\n body: JSON.stringify({ ticket_id: ticketExternalId }),\n });\n if (!response.ok) return;\n // 0-latency local zero, then reconcile with the response's\n // server-computed summary (THE truth — includes closure\n // accounting and other tickets).\n zeroUnread(ticketExternalId);\n const body = (await response.json().catch(() => null)) as { summary?: TicketUnreadSummary } | null;\n if (isSummaryData(body?.summary)) {\n setSummary({\n totalUnread: body.summary.totalUnread,\n tickets: body.summary.tickets ?? {},\n latestUnreadAt: body.summary.latestUnreadAt ?? {},\n });\n }\n } catch {\n // Non-fatal — the receipt lands on the next markRead; unread\n // state reconciles via the next server summary push.\n }\n },\n [readUrl, zeroUnread],\n );\n\n const setOpenTicketId = React.useCallback((ticketExternalId: string | null) => {\n openTicketIdRef.current = ticketExternalId;\n setOpenTicketIdState(ticketExternalId);\n }, []);\n\n const notifyTicketCreated = React.useCallback(() => {\n // Fresh connect → fresh ownership set + fresh server summary\n // (covers both the no-stream 204 wait state and an already-live\n // stream whose set predates the new ticket).\n noStreamRef.current = false;\n subscriptionRef.current?.reconnectNow();\n }, []);\n\n // Derived unread map — open ticket masked to 0 so a server summary\n // landing inside the markRead debounce window can't transiently\n // re-badge it.\n const value = React.useMemo<TicketLiveContextValue>(() => {\n let unreadByTicket = summary.tickets;\n let unreadTotal = summary.totalUnread;\n if (openTicketIdState && unreadByTicket[openTicketIdState]) {\n const masked = unreadByTicket[openTicketIdState];\n unreadByTicket = { ...unreadByTicket };\n delete unreadByTicket[openTicketIdState];\n unreadTotal = Math.max(0, unreadTotal - masked);\n }\n // Ticket with the NEWEST unread reply (compared as parsed epoch ms\n // via `stampMs` — mixed timezone offsets break string ordering) —\n // header cell routes there. Falls back to any unread key if a\n // timestamp is missing.\n let nextUnreadTicketId: string | null = null;\n let nextStampMs = 0;\n for (const id of Object.keys(unreadByTicket)) {\n const ms = stampMs(summary.latestUnreadAt[id]);\n if (nextUnreadTicketId === null || ms > nextStampMs) {\n nextUnreadTicketId = id;\n nextStampMs = ms;\n }\n }\n return {\n authed,\n connected,\n unreadTotal,\n unreadByTicket,\n nextUnreadTicketId,\n markRead,\n setOpenTicketId,\n notifyTicketCreated,\n };\n }, [summary, authed, connected, openTicketIdState, markRead, setOpenTicketId, notifyTicketCreated]);\n\n return <TicketLiveContext.Provider value={enabled ? value : null}>{children}</TicketLiveContext.Provider>;\n}\n","/**\n * Wire shape of a row returned by `POST /api/chat/agent/find-ticket`.\n * Mirrors the executor's projection at `lib/data/hubspot-tools.ts`\n * (`FIND_TICKET_SELECT` / `FindTicketResult`).\n *\n * Cross-repo duplication is INTENTIONAL: this lib ships independently\n * of the hub, so we can't import `FindTicketResult` from\n * `hubspot-tools.ts` directly. If the server adds a column to\n * `FIND_TICKET_SELECT`, also add it here. The smoke test in §F of the\n * plan covers the happy path; a wire-contract test belongs in the hub.\n *\n * `find-ticket` returns `customer_emails: string[]` (jsonb array), NOT\n * a single `customer_email`. The list is server-self-scoped to the\n * caller's session email; the array is exposed for admin/staff\n * surfaces, which the ticket center doesn't render.\n */\nexport interface TicketData {\n id: string;\n /** HubSpot ticket id (display number, e.g. \"1234\"). */\n external_id: string;\n subject: string | null;\n /** Short (≤400 char) HTML-stripped preview of the ticket body —\n * used for the list-card subtitle when needed. */\n preview: string | null;\n /** Longer (≤4k char) sanitized body. INCLUDES every appended\n * `content_addendum` comment because the `update_ticket` executor\n * reads + re-writes the `content` property server-side with a\n * `---` separator. Render this in the drawer's description block\n * and the user sees both the original message + every comment they\n * (or staff) added. */\n body: string | null;\n /** Canonical OPEN | CLOSED (HubSpot pipeline derived). */\n status: string | null;\n /** Human label like \"New\" / \"Working on it\" / \"Waiting on contact\" /\n * \"Closed\". Drives the badge text; canonical status drives color. */\n pipeline_stage_label: string | null;\n clickup_task_id: string | null;\n /** Snapshot of the linked ClickUp delivery task — populated server-side\n * via the `clickup_tasks` mirror when `clickup_task_id` is set. Drives\n * the \"Linked delivery\" card surface on the ticket drawer (status\n * badge + ClickUp deep link). `null` when no link OR the ClickUp row\n * was deleted / not yet synced. */\n clickup: TicketClickupSummary | null;\n priority: string | null;\n customer_emails: string[];\n customer_company: string | null;\n /** HubSpot contact's display name. Drives the customer attribution\n * on the drawer when the viewer is NOT the customer themselves\n * (admin browsing / multi-contact second viewer). Conversations\n * API messages don't carry per-message sender info on Custom\n * Channels, so this is the only reliable source for \"what's the\n * customer's name.\" */\n customer_name: string | null;\n /** HubSpot owner id of the agent assigned to this ticket. Carried as\n * raw id for debugging; rendering goes through `assignedOwner`. Null\n * when unassigned. */\n assigned_to: string | null;\n /** Resolved assigned-owner profile — name + email + avatar. Populated\n * server-side via `attachOwnerProfiles` which joins through the\n * `hubspot_owners` mirror to `profiles` by email. Drives the\n * \"Assigned to\" attribution in the drawer header. Null when\n * unassigned OR the owner couldn't be resolved (rare — only when\n * the agent was deleted from HubSpot between the ticket update and\n * the next owners reconcile). */\n assignedOwner: TicketAssignedOwner | null;\n hubspot_updated_at: string;\n}\n\n/** Resolved profile of a ticket's assigned agent — surfaced in the\n * drawer header. Subset of the server's `MirroredOwnerProfile`\n * trimmed to just the rendering fields. */\nexport interface TicketAssignedOwner {\n name: string | null;\n email: string | null;\n avatarUrl: string | null;\n}\n\n/** Compact projection of a linked ClickUp task — matches the server's\n * `ClickupSummary` and aligns with `DeliveryItem` so the linked-card\n * on a ticket can render through the same `DeliveryRow` primitive used\n * on `/bug-fixes-and-enhancements`. */\nexport interface TicketClickupSummary {\n /** ClickUp task external_id (e.g. \"86ad4e022\"). Used as the\n * `?focus=<id>` URL param to scroll the public delivery page to\n * this row. */\n external_id: string;\n title: string | null;\n description: string | null;\n /** ClickUp status name — e.g. \"complete\" / \"working\" / \"design approved\"\n * / \"waiting for release\". Used as the badge label. */\n status: string | null;\n /** ClickUp's per-status hex color (e.g. \"#008844\"). Forwarded to the\n * badge so colors match the ClickUp board exactly. */\n status_color: string | null;\n /** Bucket — `'backlog' | 'working' | 'complete' | 'unknown'`. Used as\n * a fallback when status_color is missing. */\n status_category: string | null;\n /** ClickUp custom item label (`'Bug'` / `'Request'`) — drives the\n * type badge (\"BUG-FIX\" / \"ENHANCEMENT\"). */\n task_type: string | null;\n custom_item_id: number | null;\n /** Every ClickUp list the task is associated with. UI joins with \", \". */\n list_names: string[];\n /** Unix-ms timestamps so the row's \"ACTIVE X ago\" subtitle uses the\n * shared `getRelativeTime()` helper. */\n date_opened: number | null;\n date_updated: number | null;\n date_closed: number | null;\n /** Direct https://app.clickup.com/t/<id> deep link. Kept on the wire\n * for admin surfaces; the customer-facing linked card navigates\n * internally instead. */\n clickup_url: string | null;\n /** Composed server-side via the SAME `buildDevSectionUrl` helper the\n * chat-inline delivery card uses. Carries `?search=<id>` so the\n * delivery list filters to that single task on landing. */\n delivery_href: string;\n /** Target platform name for the host's `useNavLink` to decide\n * same-tab vs new-tab on cross-platform links. */\n delivery_target_platform: string;\n /** Release version label set by the delivery team, e.g. \"0.9\" / \"1.0\".\n * Shown beside the status when present. */\n target_version: string | null;\n}\n\n/**\n * Optimistic placeholder a `submitTicket` call prepends to the list\n * BEFORE the server roundtrip resolves. Drawer is hidden until the\n * real id arrives. The wrapper destructures `_optimistic` before\n * forwarding to `<ChatTicketItem>` so the DOM doesn't see an unknown\n * prop.\n */\nexport interface OptimisticTicket extends TicketData {\n _optimistic: true;\n}\n\nexport type AnyTicket = TicketData | OptimisticTicket;\n\nexport function isOptimistic(t: AnyTicket): t is OptimisticTicket {\n return (t as OptimisticTicket)._optimistic === true;\n}\n\n/**\n * Shape of a single `['tickets', …]` TanStack-Query cache slot.\n * Mirrors `FindTicketResponse` in `hooks/use-tickets-list.ts` — kept\n * here because the cache-mutation call sites in `useTicketActions` and\n * `<HelpCenterList>` would otherwise have to redeclare the shape inline.\n *\n * A 2026-05-29 prod regression (`t.map is not a function` on\n * close/reopen) was caused by assuming the cache held a bare\n * `TicketData[]` instead of this wrapper — every helper that calls\n * `queryClient.setQueriesData` / `getQueriesData` on `['tickets']`\n * MUST type the value through this shape and project / reassemble\n * `tickets` explicitly.\n */\nexport interface TicketsCacheSlot {\n tickets?: TicketData[];\n count?: number;\n totalCount?: number;\n page?: number;\n pageSize?: number;\n totalPages?: number;\n scope?: 'self' | 'all';\n}\n\n/**\n * Stable server-side error codes the ticket-action helpers route\n * through `mapTicketActionError`. Anything else is treated as a generic\n * server error.\n *\n * Reply-specific codes (`HUBSPOT_5XX` / `HUBSPOT_400_VALIDATION` /\n * `HUBSPOT_404_THREAD` / `HUBSPOT_REPLY_UNKNOWN`) drive the drawer\n * banner that appears above the composer when a customer reply fails.\n * Distinct from `HUBSPOT_DISCONNECTED` (whole-system) and\n * `TICKET_NOT_FOUND` (terminal-row) — the reply codes are per-attempt\n * + retryable except for `HUBSPOT_404_THREAD`.\n */\nexport type TicketActionErrorCode =\n | 'PROPOSAL_NOT_CLAIMABLE'\n | 'TICKET_NOT_FOUND'\n | 'TICKET_OWNERSHIP_DENIED'\n | 'HUBSPOT_DISCONNECTED'\n | 'RATE_LIMITED'\n | 'INVALID_TOOL_ARGS'\n | 'HUBSPOT_5XX'\n | 'HUBSPOT_400_VALIDATION'\n | 'HUBSPOT_404_THREAD'\n | 'HUBSPOT_REPLY_UNKNOWN'\n | 'UNKNOWN';\n\nexport interface MappedTicketActionError {\n code: TicketActionErrorCode;\n /** Human-readable copy safe to show in a toast. */\n message: string;\n /** When true, the form should disable submit + show the\n * support-down banner. Set only for HUBSPOT_DISCONNECTED. */\n supportSystemDown: boolean;\n /** When true, the helper should remove the affected row optimistically\n * (TICKET_NOT_FOUND). */\n removeRowFromCache: boolean;\n /** Retry hint surfaced from a 429 response. Caller decides whether\n * to mention it in the toast. */\n retryAfterSeconds?: number;\n}\n\n/**\n * Defensive client-side cap on ticket text (initial content + comment\n * addendums). HubSpot Note engagements accept more, but a 100KB paste\n * should fail fast at the UI rather than burning a server round-trip.\n * Both the open-ticket form and the per-row comment textarea import\n * this so a future server-side hardening only touches one place.\n */\nexport const TICKET_TEXT_MAX_CHARS = 5000;\n\n/**\n * Wire contract of the ticket live stream (`GET /api/chat/agent/\n * ticket-stream`, SSE). Producer (the hub route's `mapEvent`) imports\n * THIS type — same producer/consumer SSOT pattern as\n * `ConversationEngagementWire = TicketEngagement`. A schema drift here\n * would be a silent serialization bug; keep one named contract.\n *\n * Frames carry METADATA ONLY — never message bodies. Content is always\n * refetched through the ACL'd `list-engagements` path (one read path).\n *\n * Event names (`eventType`):\n * - `ticket-message` — a message row landed in the mirror for one of\n * the viewer's tickets. `data` carries the metadata.\n * - `ticket-status` — a MEANINGFUL ticket-row change (status /\n * pipeline stage / closure) landed in the mirror. Server-side\n * old-vs-new diffing drops no-op writes (sync stamps). Clients\n * invalidate + refetch the summary (closures count as unread\n * server-side via `closed_at` vs the read receipt).\n * - `ticket-summary` — the server-computed `TicketUnreadSummary`.\n * THE stream is the summary webservice: pushed on connect (server-\n * side resync-on-reconnect) and re-pushed (debounced) after every\n * delivered event. Clients hold NO summary fetch path.\n * - `ticket-resync` — degraded frame: something happened that the\n * server couldn't fully describe (truncated Realtime payload, or\n * the connection's ownership set just gained tickets). A fresh\n * `ticket-summary` follows it; clients invalidate queries.\n *\n * The server also emits `status` frames (`subscribed` / `retrying` /\n * `reconnect_failed`) from the shared SSE utility — clients derive\n * `connected` from those, NOT from the HTTP stream being open.\n */\nexport type TicketStreamEventType = 'ticket-message' | 'ticket-status' | 'ticket-summary' | 'ticket-resync';\n\n/** Metadata payload of a `ticket-message` frame. */\nexport type TicketMessageStreamData = {\n ticket_external_id: string;\n /** Mirror row's HubSpot message id. */\n message_id: string;\n /** Server-stamped via the same direction predicate the wire mapper\n * uses. Clients never re-derive author classification. */\n authorRole: 'customer' | 'support';\n /** Server-stamped via the visibility+direction unread predicate\n * (`countsAsUnread` in the hub's conversations DAL). ONLY frames\n * with `true` may bump client-side unread state. */\n countsAsUnread: boolean;\n hubspot_created_at: string | null;\n};\n\n/** Metadata payload of a `ticket-status` frame. */\nexport type TicketStatusStreamData = {\n ticket_external_id: string;\n /** Canonical OPEN | CLOSED after the change. */\n status: string | null;\n pipeline_stage_label: string | null;\n closed_at: string | null;\n};\n\nexport interface TicketStreamEvent {\n eventType: TicketStreamEventType;\n /** Human-readable label (SSE envelope compat) — clients ignore it. */\n message: string;\n /** `ticket-message` → TicketMessageStreamData; `ticket-status` →\n * TicketStatusStreamData; `ticket-summary` → TicketUnreadSummary;\n * absent on `ticket-resync`. */\n data?: TicketMessageStreamData | TicketStatusStreamData | TicketUnreadSummary;\n}\n\n/**\n * The SINGLE unread source, delivered EXCLUSIVELY over the stream\n * (`ticket-summary` frames on connect + after events) and in\n * `ticket-read` responses. There is no summary fetch endpoint. Header\n * badge total AND per-row dots both read this via the\n * `TicketLiveProvider` map; missing keys mean 0.\n */\nexport type TicketUnreadSummary = {\n totalUnread: number;\n tickets: Record<string, number>;\n /** ISO timestamp of the NEWEST unread message per ticket (same keys as\n * `tickets`). Drives \"route to the most recent update\" on the header\n * cell: the ticket with the max value here is `nextUnreadTicketId`. */\n latestUnreadAt: Record<string, string>;\n};\n\n/**\n * Trailing debounce for `markRead` while the drawer is open and new\n * messages stream in — flushed on drawer close so a fast open/close\n * still persists the receipt. Named beside its sibling cadences so\n * every timing knob lives in one file.\n */\nexport const TICKET_MARK_READ_DEBOUNCE_MS = 2000;\n\n/**\n * Ticket deep-link SSOT — DEFINED in the server-safe param-keys module\n * (`utils/dev-sections/dev-section-param-keys.ts`, beside its sibling\n * `devSectionAnchorId`) because producers span both worlds: the hub's\n * SERVER-side chat-ref builder and the client header cell. Re-exported\n * here so ticket-surface consumers keep one import home.\n */\nexport { TICKET_OPEN_PARAM, buildTicketOpenHref } from '../../utils/dev-sections/dev-section-param-keys';\n\n/**\n * Centralized toast copy. Keep all wording here so QA / localization\n * can find every user-visible string in one file.\n */\nexport const TOAST_COPY = {\n open_success: { title: 'Ticket opened', description: 'We received your message and will follow up shortly.' },\n open_mirror_pending: { title: 'Ticket opened', description: 'Syncing — your ticket will appear momentarily.' },\n close_success: { title: 'Ticket closed' },\n reopen_success: { title: 'Ticket reopened' },\n comment_success: { title: 'Comment added' },\n attach_success: { title: 'Files attached' },\n // Failure variants are constructed dynamically from MappedTicketActionError.\n} as const;\n"]}
|
|
@@ -282,9 +282,7 @@ var toolIconMap = {
|
|
|
282
282
|
[ToolTypeValues.AUTHENTIK]: (size, className) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkYNL2NHXHcjs.AuthentikLogoGreyIcon, { size, className }),
|
|
283
283
|
[ToolTypeValues.OSQUERY]: (size, className) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkYNL2NHXHcjs.OsqueryLogoGreyIcon, { size, className }),
|
|
284
284
|
[ToolTypeValues.SYSTEM]: () => null,
|
|
285
|
-
|
|
286
|
-
// own brand is what the logs and the directory pickers name.
|
|
287
|
-
[ToolTypeValues.MICROSOFT_365]: (size, className) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkYNL2NHXHcjs.Office365LogoGreyIcon, { size, className }),
|
|
285
|
+
[ToolTypeValues.MICROSOFT_365]: (size, className) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkYNL2NHXHcjs.MicrosoftLogoGreyIcon, { size, className }),
|
|
288
286
|
[ToolTypeValues.GOOGLE_WORKSPACE]: (size, className) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkYNL2NHXHcjs.GoogleIcon, { size, className })
|
|
289
287
|
};
|
|
290
288
|
var ToolIcon = ({ toolType, size = 16, className }) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children: _nullishCoalesce(_optionalChain([toolIconMap, 'access', _7 => _7[toolType], 'optionalCall', _8 => _8(size, className)]), () => ( null)) });
|
|
@@ -786,4 +784,4 @@ function navigateSamePageHash(target, options = {}) {
|
|
|
786
784
|
|
|
787
785
|
|
|
788
786
|
exports.useIsTruncated = useIsTruncated; exports.useDebounce = useDebounce; exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect; exports.useMediaQuery = useMediaQuery; exports.breakpoints = breakpoints; exports.useSmUp = useSmUp; exports.useMdUp = useMdUp; exports.useLgUp = useLgUp; exports.useHeaderHeight = useHeaderHeight; exports.useMarqueeEngine = useMarqueeEngine; exports.useResetOnPageHidden = useResetOnPageHidden; exports.useSuppressCloneFocus = useSuppressCloneFocus; exports.ToolTypeValues = ToolTypeValues; exports.toolLabels = toolLabels; exports.ToolIcon = ToolIcon; exports.cn = cn; exports.errorMessage = errorMessage; exports.apiErrorMessage = apiErrorMessage; exports.delay = delay; exports.generateRandomString = generateRandomString; exports.truncateString = truncateString; exports.serializeJsonLd = serializeJsonLd; exports.deepClone = deepClone; exports.getSlackCommunityJoinUrl = getSlackCommunityJoinUrl; exports.clamp = clamp; exports.pick = pick; exports.NO_CLIENT_CACHE = NO_CLIENT_CACHE; exports.NEAR_VIEWPORT_ROOT_MARGIN = NEAR_VIEWPORT_ROOT_MARGIN; exports.useNearViewport = useNearViewport; exports.isBlankLine = isBlankLine; exports.createFenceTracker = createFenceTracker; exports.HEADING_EMOJI_RE = HEADING_EMOJI_RE; exports.stripHeadingEmojis = stripHeadingEmojis; exports.slugifyHeadingBase = slugifyHeadingBase; exports.slugifyHeadingText = slugifyHeadingText; exports.scanHeadings = scanHeadings; exports.createHeadingIdDeduper = createHeadingIdDeduper; exports.normalizeAnchorId = normalizeAnchorId; exports.findAnchorElementByNormalizedId = findAnchorElementByNormalizedId; exports.getScrollableAncestor = getScrollableAncestor; exports.scrollElementIntoView = scrollElementIntoView; exports.STICKY_HEADER_OFFSET_PX = STICKY_HEADER_OFFSET_PX; exports.HUB_HEADER_OFFSET_PX = HUB_HEADER_OFFSET_PX; exports.normalizeHashFragment = normalizeHashFragment; exports.getHashTargetElement = getHashTargetElement; exports.navigateSamePageHash = navigateSamePageHash;
|
|
789
|
-
//# sourceMappingURL=chunk-
|
|
787
|
+
//# sourceMappingURL=chunk-IJUQQTMV.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-IJUQQTMV.cjs","../src/hooks/ui/use-is-truncated.ts","../src/hooks/ui/use-debounce.ts","../src/hooks/ui/use-isomorphic-layout-effect.ts","../src/hooks/ui/use-media-query.ts","../src/hooks/ui/use-header-height.ts","../src/hooks/ui/use-marquee-engine.ts","../src/hooks/ui/use-reset-on-page-hidden.ts","../src/hooks/ui/use-suppress-clone-focus.ts","../src/types/tool.types.ts","../src/components/tool-icon.tsx","../src/utils/common.ts","../src/hooks/use-near-viewport.ts","../src/utils/markdown-fences.ts","../src/utils/markdown-heading-id.ts","../src/utils/anchor-id.ts","../src/utils/scroll-into-view.ts","../src/utils/same-page-hash-nav.ts"],"names":["delay","useState","useEffect","header","bar","useCallback","useRef"],"mappings":"AAAA,6rBAAY;AACZ;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACTA,8BAAiD;AA+B1C,SAAS,cAAA,CAAsC,KAAA,EAAgB,OAAA,EAAiC;AACrG,EAAA,MAAM,UAAA,mCAAY,OAAA,2BAAS,WAAA,UAAa,OAAA;AACxC,EAAA,MAAM,CAAC,OAAA,EAAS,UAAU,EAAA,EAAI,6BAAA,IAAuB,CAAA;AACrD,EAAA,MAAM,CAAC,WAAA,EAAa,cAAc,EAAA,EAAI,6BAAA,KAAc,CAAA;AAKpD,EAAA,MAAM,IAAA,EAAM,gCAAA,CAAa,IAAA,EAAA,GAAmB,UAAA,CAAW,IAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAEhE,EAAA,8BAAA,CAAU,EAAA,GAAM;AACd,IAAA,GAAA,CAAI,CAAC,OAAA,EAAS,OAAO,KAAA,CAAA;AAIrB,IAAA,MAAM,MAAA,EAAQ,CAAA,EAAA,GAAM;AAClB,MAAA,cAAA;AAAA,QACE,UAA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AA;AAEE,MAAA;AACA,MAAA;AACI,MAAA;AACF,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACA,EAAA;AACF;AhBwdU;AACA;AiBppBG;AAIA;AAUG;AACT,EAAA;AACC,EAAA;AACC,EAAA;AACT;AAqBgB;AACL,EAAA;AACH,EAAA;AACF,EAAA;AAEA,EAAA;AACA,EAAA;AACF,IAAA;AACI,IAAA;AACF,MAAA;AACI,MAAA;AACN,IAAA;AACM,EAAA;AAEN,IAAA;AACF,EAAA;AAEO,EAAA;AACT;AAsBgB;AACV,EAAA;AACI,EAAA;AACF,EAAA;AAKF,EAAA;AACA,EAAA;AACI,IAAA;AACA,EAAA;AACN,IAAA;AACF,EAAA;AAEM,EAAA;AAIJ,IAAA;AACF,EAAA;AACM,EAAA;AAGA,EAAA;AACF,EAAA;AACF,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AACM,EAAA;AACA,EAAA;AAED,EAAA;AACD,EAAA;AACI,IAAA;AACF,IAAA;AACF,MAAA;AACF,IAAA;AACE,MAAA;AACF,IAAA;AAGA,IAAA;AACM,MAAA;AACF,QAAA;AACA,QAAA;AACD,MAAA;AACH,IAAA;AACF,EAAA;AACM,EAAA;AACF,EAAA;AACF,IAAA;AACF,EAAA;AAGA,EAAA;AACE,IAAA;AACA,IAAA;AACD,EAAA;AACM,EAAA;AACT;AjB+kBU;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-IJUQQTMV.cjs","sourcesContent":[null,"'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\n\nexport interface UseIsTruncatedOptions {\n /** Measure vertical clipping (`line-clamp-N`) instead of the single-line ellipsis. */\n multiline?: boolean;\n}\n\n/**\n * Tracks whether an element's text is ACTUALLY clipped — the condition for\n * offering a \"full value\" tooltip. Text that fits needs no tooltip, and showing\n * one anyway just repeats what the user is already reading.\n *\n * Three things can change the answer, and all three are watched: the box\n * resizing (`ResizeObserver`), the text itself changing, and the measured\n * ELEMENT changing. None of them implies the others — new text inside a\n * width-constrained box leaves the box exactly as it was, so the observer never\n * fires; and a caller that swaps between render branches (adornment vs plain)\n * mounts a different node under the same text, which a `useRef` would leave\n * measured against the old, detached node. Pass the rendered value as `value`.\n *\n * `ref` is a CALLBACK ref, not a `RefObject` — that is what makes the element\n * itself a dependency. Attach it exactly like a normal ref; there is no\n * `.current` to read.\n *\n * ```tsx\n * const { ref, isTruncated } = useIsTruncated<HTMLHeadingElement>(title)\n * <FloatingTooltip content={title} disabled={!isTruncated}>\n * <h1 ref={ref} className=\"truncate\">{title}</h1>\n * </FloatingTooltip>\n * ```\n */\nexport function useIsTruncated<T extends HTMLElement>(value: unknown, options?: UseIsTruncatedOptions) {\n const multiline = options?.multiline ?? false;\n const [element, setElement] = useState<T | null>(null);\n const [isTruncated, setIsTruncated] = useState(false);\n\n // Wrapped so the identity stays stable across renders: passing the raw\n // `useState` setter as a ref would be stable too, but this keeps the public\n // shape a plain `RefCallback<T>` instead of a state dispatcher.\n const ref = useCallback((node: T | null) => setElement(node), []);\n\n useEffect(() => {\n if (!element) return undefined;\n // The 1px tolerance absorbs sub-pixel layout rounding, which otherwise\n // reports a permanent fractional \"overflow\" at some zoom levels / DPRs and\n // leaves a tooltip armed on text that is fully visible.\n const check = () => {\n setIsTruncated(\n multiline ? element.scrollHeight > element.clientHeight + 1 : element.scrollWidth > element.clientWidth + 1,\n );\n };\n check();\n const observer = new ResizeObserver(check);\n observer.observe(element);\n return () => observer.disconnect();\n }, [element, value, multiline]);\n\n // Masked rather than reset from the effect: with no element there is nothing\n // to clip, and deriving that during render avoids a second render pass every\n // time the measured node unmounts.\n return { ref, isTruncated: element ? isTruncated : false };\n}\n","'use client';\n\nimport { useState, useEffect } from 'react';\n\n/**\n * Hook to debounce a value\n * @param value - Value to debounce\n * @param delay - Delay in milliseconds\n * @returns Debounced value\n */\nexport function useDebounce<T>(value: T, delay = 500): T {\n const [debouncedValue, setDebouncedValue] = useState<T>(value);\n\n useEffect(() => {\n // Set up timeout to update debounced value\n const timer = setTimeout(() => {\n setDebouncedValue(value);\n }, delay);\n\n // Clean up timeout on value change or unmount\n return () => {\n clearTimeout(timer);\n };\n }, [value, delay]);\n\n return debouncedValue;\n}\n","'use client';\n\nimport { useEffect, useLayoutEffect } from 'react';\n\n/**\n * `useLayoutEffect` in the browser, `useEffect` on the server.\n *\n * `useLayoutEffect` never runs during server rendering — React cannot measure or\n * mutate a layout that has not been laid out — so calling it in a component that\n * SSRs logs a warning on every render pass. Client components still render on the\n * server in Next.js, so `'use client'` alone does not avoid it.\n *\n * Use this wherever the effect writes something the FIRST paint depends on (a CSS\n * custom property, a scroll position, a measured size). A plain `useEffect` there\n * runs after paint, which shows one frame of the pre-effect value; a plain\n * `useLayoutEffect` gets the timing right and pays for it with the warning. This\n * gets both: paint-blocking where there is a paint, a no-op where there is not.\n */\nexport const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n","'use client';\n\nimport { useState } from 'react';\nimport { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';\n\n/**\n * Hook to check if a media query matches\n * @param query - Media query to check\n * @returns Whether the media query matches, or undefined during SSR/initial render\n */\nexport function useMediaQuery(query: string): boolean | undefined {\n const [matches, setMatches] = useState<boolean | undefined>(undefined);\n\n useIsomorphicLayoutEffect(() => {\n const matchMedia = window.matchMedia(query);\n\n const handleChange = () => {\n setMatches(matchMedia.matches);\n };\n\n // Set initial value\n handleChange();\n\n matchMedia.addEventListener('change', handleChange);\n\n return () => {\n matchMedia.removeEventListener('change', handleChange);\n };\n }, [query]);\n\n return matches;\n}\n\n/**\n * Predefined breakpoints for common screen sizes\n */\nexport const breakpoints = {\n md: '(min-width: 800px)', // Tablet: 50rem\n lg: '(min-width: 1280px)', // Desktop: 80rem\n};\n\n/** @deprecated Use useMdUp instead */\nexport function useSmUp(): boolean | undefined {\n return useMdUp();\n}\n\nexport function useMdUp(): boolean | undefined {\n const matches = useMediaQuery(breakpoints.md);\n return matches === undefined ? undefined : matches;\n}\n\nexport function useLgUp(): boolean | undefined {\n const matches = useMediaQuery(breakpoints.lg);\n return matches === undefined ? undefined : matches;\n}\n","'use client';\n\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns the combined height (px) of the sticky page header and announcement\n * bar (if present), updated live via ResizeObserver / MutationObserver.\n * Useful for offsetting fixed/absolute-positioned panels so they don't\n * overlap the header.\n */\nexport function useHeaderHeight(\n // First-paint fallback = the unified top-navigation `big` bar (72px), the\n // size every hub/marketing site renders; replaced by the live measurement.\n defaultHeight = 72,\n options: {\n /**\n * When false, no observers are attached and the default height is\n * returned — for consumers that stay mounted on every page but only need\n * the measurement while an overlay is open (avoids an always-on\n * document-wide MutationObserver + forced reflow).\n * @default true\n */\n enabled?: boolean;\n } = {},\n): number {\n const { enabled = true } = options;\n const [height, setHeight] = useState(defaultHeight);\n\n useEffect(() => {\n if (!enabled) return undefined;\n\n const measure = () => {\n let total = 0;\n const header = document.querySelector('header');\n if (header) total += header.offsetHeight;\n const bar = document.querySelector('[data-announcement-bar]');\n if (bar instanceof HTMLElement) total += bar.offsetHeight;\n setHeight(total > 0 ? total : defaultHeight);\n };\n\n measure();\n\n const resizeObserver = new ResizeObserver(measure);\n const header = document.querySelector('header');\n if (header) resizeObserver.observe(header);\n const bar = document.querySelector('[data-announcement-bar]');\n if (bar) resizeObserver.observe(bar);\n\n const mutationObserver = new MutationObserver(mutations => {\n for (const mutation of mutations) {\n if (mutation.type === 'childList' || mutation.type === 'attributes') {\n measure();\n const newBar = document.querySelector('[data-announcement-bar]');\n if (newBar) resizeObserver.observe(newBar);\n }\n }\n });\n mutationObserver.observe(document.body, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['data-announcement-bar'],\n });\n\n return () => {\n resizeObserver.disconnect();\n mutationObserver.disconnect();\n };\n }, [defaultHeight, enabled]);\n\n return height;\n}\n","'use client';\n\nimport { useCallback, useEffect, useRef, type MutableRefObject } from 'react';\n\n/**\n * THE marquee animation core (single source of truth) — extracted verbatim\n * from <CardsStrip> so every endless-scroll surface (card strips, logo strips,\n * quick-action walls, chip marquees) shares ONE rAF position engine (\"unify\n * means delete variations\").\n *\n * The engine is axis- and driver-agnostic: it owns a FLOAT position ref, a\n * velocity envelope, seam wrapping, and an optional chevron-style glide; the\n * caller decides what a position \"means\" via `apply` — writing\n * `scroller.scrollLeft` (CardsStrip: a real scroller the user can also drag)\n * or a `translate` transform (MarqueeWall: decorative tracks, incl. vertical —\n * mandatory inside surfaces that forbid inner scrollers, e.g. the deck's\n * mobile single-fold panels).\n *\n * Engine semantics (do not \"simplify\"):\n * - Position lives in a FLOAT ref, never read-modify-write from the DOM:\n * scrollLeft reads back rounded values, so sub-pixel increments\n * (speed/fps < 1px) get eaten by rounding — stutter + measurably slower\n * than the configured speed.\n * - Velocity envelope (~250ms time constant) eases between 0 and `speed`\n * instead of binary stop/start — pause decelerates, resume accelerates from\n * the current position (GSAP-marquee behavior; hard cuts read as jank).\n * - Glide consumes a signed remaining-distance, wrapping modulo the copy size\n * each frame, so seam warps are invisible to it (browser smooth-scroll\n * animates toward an ABSOLUTE target and lunges after a warp).\n * - `isPaused` is evaluated every frame — the caller owns the pause-reason\n * set (hover, viewport, tab visibility, suppress windows); the engine only\n * turns it into a smooth velocity target.\n */\nexport interface MarqueeEngineOptions {\n /** Master switch — the rAF runs only while true. On (re)activation the\n * position resyncs from `readBack` when provided. */\n active: boolean;\n /** Cruise speed in px/s. */\n speed: number;\n /** Per-frame pause verdict (caller-owned reason set). `now` is the rAF\n * timestamp, for suppress-until comparisons. */\n isPaused: (now: number) => boolean;\n /** Single-copy size in px (the wrap modulus). Return <= 0 to disable\n * wrapping (position advances unwrapped — callers should size tracks so\n * this never happens while active). */\n getWrapSize: () => number;\n /** Lower bound of the wrap range: positions stay in\n * [wrapMin, wrapMin + wrapSize). Default 0. Scroller drivers with USER\n * scrolling pass their seam-warp buffer here so engine-written positions\n * never enter the re-center zones — an exact-edge warp check is racy\n * against the rAF (the engine nudges the scroller off the edge before the\n * scroll handler samples it → \"stuck at the left edge\"). */\n getWrapMin?: () => number;\n /** Write the position to the DOM (scrollLeft assignment or transform). */\n apply: (pos: number) => void;\n /** Read the externally-mutated position back (real scrollers: user drag /\n * native smooth scroll move scrollLeft under the engine). Omit for\n * transform drivers — nothing external can move them. */\n readBack?: () => number;\n /** Called at the end of every frame (e.g. hover re-resolution after the\n * track moved under a stationary pointer). */\n onAfterFrame?: () => void;\n}\n\nexport interface MarqueeEngineHandle {\n /** The engine's float position (px along the axis, 0 ≤ pos < wrap while\n * wrapping). Callers may write it together with their own DOM write (seam\n * warp on manual scroll). */\n posRef: MutableRefObject<number>;\n /** Accumulate a signed glide distance (chevron navigation). Runs through\n * the engine's own tween — never native smooth scroll while wrapping. */\n glideBy: (px: number) => void;\n /** Wrap an arbitrary position into [0, wrapSize). */\n wrap: (pos: number) => number;\n}\n\n// Resync threshold (px): external movement beyond this adopts the DOM value.\nconst RESYNC_EPSILON = 1.5;\n\nexport function useMarqueeEngine(options: MarqueeEngineOptions): MarqueeEngineHandle {\n const posRef = useRef(0);\n const glideRemainingRef = useRef(0);\n const speedEnvRef = useRef(0);\n\n // Latest-options ref: the rAF loop always reads current values without the\n // effect restarting on every render. Refreshed in an unconditional effect,\n // declared before every effect that starts the loop, rather than in the\n // render body — a render attempt React discards must not be able to hand the\n // loop options that were never committed.\n const optsRef = useRef(options);\n useEffect(() => {\n optsRef.current = options;\n });\n\n const wrap = useCallback((pos: number) => {\n const half = optsRef.current.getWrapSize();\n if (half <= 0) return pos;\n const min = optsRef.current.getWrapMin?.() ?? 0;\n let wrapped = pos;\n while (wrapped >= min + half) wrapped -= half;\n while (wrapped < min) wrapped += half;\n return wrapped;\n }, []);\n\n const glideBy = useCallback((px: number) => {\n glideRemainingRef.current += px;\n }, []);\n\n const active = options.active;\n useEffect(() => {\n if (!active) return undefined;\n let raf = 0;\n let last = performance.now();\n const readBack = optsRef.current.readBack;\n if (readBack) posRef.current = readBack();\n\n const tick = (now: number) => {\n const opts = optsRef.current;\n const dt = Math.min(now - last, 100) / 1000; // clamp tab-wake jumps\n last = now;\n\n const paused = opts.isPaused(now);\n // Ease the velocity toward its target (0 when paused) — smooth decel on\n // pause, smooth accel on resume, always from the CURRENT position.\n const targetSpeed = paused ? 0 : opts.speed;\n speedEnvRef.current += (targetSpeed - speedEnvRef.current) * Math.min(1, dt / 0.25);\n if (targetSpeed === 0 && speedEnvRef.current < 0.5) speedEnvRef.current = 0;\n\n const external = opts.readBack ? opts.readBack() : null;\n const resync = () => {\n if (external !== null && Math.abs(external - posRef.current) > RESYNC_EPSILON) {\n posRef.current = external;\n }\n };\n\n const glide = glideRemainingRef.current;\n if (glide !== 0) {\n // Ease-out toward the glide target; runs even while \"paused\" (the\n // interaction that queued it sets its own suppress window).\n resync();\n const speed = Math.max(Math.abs(glide) * 6, 240); // px/s, proportional\n const step = Math.sign(glide) * Math.min(Math.abs(glide), speed * dt);\n glideRemainingRef.current = Math.abs(glide - step) < 0.5 ? 0 : glide - step;\n posRef.current = wrap(posRef.current + step);\n opts.apply(posRef.current);\n } else if (speedEnvRef.current > 0) {\n // Resync after external movement (user scroll, seam warp).\n resync();\n posRef.current = wrap(posRef.current + speedEnvRef.current * dt);\n opts.apply(posRef.current);\n } else if (external !== null) {\n // Idle: follow external movement so resumes start from where the\n // user left the scroller.\n posRef.current = external;\n }\n opts.onAfterFrame?.();\n raf = requestAnimationFrame(tick);\n };\n raf = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(raf);\n }, [active, wrap]);\n\n return { posRef, glideBy, wrap };\n}\n","import { useEffect } from 'react';\n\n/**\n * Runs `reset` whenever the tab is hidden or the window loses focus — exactly the\n * moments a `pointerleave` / `pointercancel` can be SWALLOWED (tab blur, an\n * overlay mounting under the cursor, an interrupted pointer), which otherwise\n * leaves a hover/\"inside\" flag stuck `true` and freezes a marquee FOREVER. The\n * next real pointer/hover re-arms the flag.\n *\n * SSOT self-heal for every marquee surface (MarqueeWall, CardsStrip) so the\n * blur + `visibilitychange` wiring lives in one place. `reset` almost always\n * only UN-sticks state. The one edge: on `blur` WITHOUT the tab hiding (a second\n * window focused beside this one), clearing the hover-pause can let the marquee\n * resume under a still-stationary cursor in the now-unfocused window — it\n * re-pauses on the next `pointermove`/`pointerenter`. We keep the `blur` reset\n * anyway because it's the only signal that catches a tab-blur that swallows the\n * `pointerleave` without a `visibilitychange`. Pass a STABLE `reset` (memoize\n * with `useCallback`) — the listeners re-attach whenever its identity changes.\n */\nexport function useResetOnPageHidden(reset: () => void): void {\n useEffect(() => {\n const onVisibility = () => {\n if (document.visibilityState === 'hidden') reset();\n };\n window.addEventListener('blur', reset);\n document.addEventListener('visibilitychange', onVisibility);\n return () => {\n window.removeEventListener('blur', reset);\n document.removeEventListener('visibilitychange', onVisibility);\n };\n }, [reset]);\n}\n","'use client';\n\nimport { useEffect, useRef } from 'react';\n\n// Every focusable a clone might contain — matched so it can be pulled out of the\n// keyboard tab order (see useSuppressCloneFocus). `[contenteditable]:not(\n// [contenteditable=\"false\"])` catches the empty/`\"true\"`/`\"plaintext-only\"`\n// editable forms; `summary` is focusable inside a <details>.\nconst CLONE_FOCUSABLE_SELECTOR =\n 'a[href],button,input,select,textarea,iframe,summary,audio[controls],video[controls],[tabindex],[contenteditable]:not([contenteditable=\"false\"])';\n\n/**\n * Keep a marquee clone's content pointer-CLICKABLE while taking it out of the\n * accessibility tree and the keyboard tab order. Shared by every endless-loop\n * surface that renders a second track copy (<CardsStrip> managed cells,\n * <MarqueeWall> clone copies).\n *\n * `inert` (the previous approach) does all three at once: a11y-hidden,\n * un-focusable AND un-clickable. That third effect was the \"news marquee stops\n * being clickable after you scroll it for a while\" bug — the 2-copy endless\n * loop ALWAYS paints clone cards inside the viewport near the copy seam, so a\n * user who manually scrolls and parks there is looking at real-looking cards\n * that silently swallow every click. Clones must therefore stay clickable (a\n * click on ANY visible card must open its link — mouse, ⌘-click, middle-click\n * and context-menu all handled natively by the clone's own anchor).\n *\n * The a11y contract is still met without `inert`: the caller keeps\n * `aria-hidden` on the clone wrapper (out of the a11y tree) and this hook\n * forces every focusable descendant to `tabindex=\"-1\"` (out of the tab order →\n * no duplicate tab stops, no aria-hidden-focus violation). Re-applied on\n * subtree mutation. This is the standard loop-clone treatment used by\n * Swiper/Splide.\n */\nexport function useSuppressCloneFocus(active: boolean) {\n const ref = useRef<HTMLDivElement | null>(null);\n useEffect(() => {\n const root = ref.current;\n if (!root || !active) return undefined;\n const suppress = () => {\n root.querySelectorAll<HTMLElement>(CLONE_FOCUSABLE_SELECTOR).forEach(el => {\n // Only stamp the ones not already stamped — avoids touching the DOM (and\n // clobbering an intentional tabindex) on every mutation.\n if (el.getAttribute('tabindex') !== '-1') el.setAttribute('tabindex', '-1');\n });\n };\n suppress();\n // Watch structure AND the attributes that can turn a descendant tabbable\n // (an anchor gaining `href`, React restoring `tabindex=\"0\"`, an element\n // becoming editable, media gaining `controls`). The `!== '-1'` guard above\n // makes our own tabindex writes a no-op, so the observer never loops.\n const mo = new MutationObserver(suppress);\n mo.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['href', 'tabindex', 'contenteditable', 'controls'],\n });\n return () => mo.disconnect();\n }, [active]);\n return ref;\n}\n","/**\n * Centralized Tool Types\n *\n * Single source of truth for all tool-related types across the entire platform.\n * Used by ToolBadge, ToolIcon, and any component that needs tool type information.\n */\n\nexport const ToolTypeValues = {\n FLEET_MDM: 'FLEET_MDM',\n MESHCENTRAL: 'MESHCENTRAL',\n AUTHENTIK: 'AUTHENTIK',\n OPENFRAME: 'OPENFRAME',\n OPENFRAME_CHAT: 'OPENFRAME_CHAT',\n OPENFRAME_CLIENT: 'OPENFRAME_CLIENT',\n OPENFRAME_RMM: 'OPENFRAME_RMM',\n OSQUERY: 'OSQUERY',\n SYSTEM: 'SYSTEM',\n // Directory tenants (Tenant Management): the same identifiers the gateway's\n // DirectoryProvider enum uses, so a directory sync's log rows resolve here.\n MICROSOFT_365: 'MICROSOFT_365',\n GOOGLE_WORKSPACE: 'GOOGLE_WORKSPACE',\n} as const;\n\nexport type ToolType = (typeof ToolTypeValues)[keyof typeof ToolTypeValues];\n\n/**\n * Maps tool types to display labels\n */\nexport const toolLabels: Record<ToolType, string> = {\n FLEET_MDM: 'Fleet',\n MESHCENTRAL: 'MeshCentral',\n AUTHENTIK: 'Authentik',\n OPENFRAME: 'OpenFrame',\n OPENFRAME_CHAT: 'OpenFrame Chat',\n OPENFRAME_CLIENT: 'OpenFrame Client',\n OPENFRAME_RMM: 'RMM',\n OSQUERY: 'Osquery',\n SYSTEM: 'System',\n MICROSOFT_365: 'Microsoft 365',\n GOOGLE_WORKSPACE: 'Google Workspace',\n};\n","import type { FC, ReactNode } from 'react';\nimport { type ToolType, ToolTypeValues } from '../types/tool.types';\nimport {\n OsqueryLogoGreyIcon,\n MeshcentralLogoGreyIcon,\n FleetMdmLogoGreyIcon,\n AuthentikLogoGreyIcon,\n MicrosoftLogoGreyIcon,\n GoogleIcon,\n OpenframeLogoGreyIcon,\n} from './icons-v2-generated';\n\ntype ToolIconRenderer = (size: number, className?: string) => ReactNode;\n\n// Every mark is the grey (`currentColor`) cut of the brand logo, the OpenFrame one included, so a\n// row of tool icons reads as one set and takes the text colour of wherever it sits.\nconst renderOpenFrameLogo: ToolIconRenderer = (size, className) => (\n <OpenframeLogoGreyIcon size={size} className={className} />\n);\n\nconst toolIconMap: Record<ToolType, ToolIconRenderer> = {\n [ToolTypeValues.FLEET_MDM]: (size, className) => <FleetMdmLogoGreyIcon size={size} className={className} />,\n [ToolTypeValues.MESHCENTRAL]: (size, className) => <MeshcentralLogoGreyIcon size={size} className={className} />,\n [ToolTypeValues.OPENFRAME]: renderOpenFrameLogo,\n [ToolTypeValues.OPENFRAME_CHAT]: renderOpenFrameLogo,\n [ToolTypeValues.OPENFRAME_CLIENT]: renderOpenFrameLogo,\n [ToolTypeValues.OPENFRAME_RMM]: renderOpenFrameLogo,\n [ToolTypeValues.AUTHENTIK]: (size, className) => <AuthentikLogoGreyIcon size={size} className={className} />,\n [ToolTypeValues.OSQUERY]: (size, className) => <OsqueryLogoGreyIcon size={size} className={className} />,\n [ToolTypeValues.SYSTEM]: () => null,\n [ToolTypeValues.MICROSOFT_365]: (size, className) => <MicrosoftLogoGreyIcon size={size} className={className} />,\n [ToolTypeValues.GOOGLE_WORKSPACE]: (size, className) => <GoogleIcon size={size} className={className} />,\n};\n\nexport interface ToolIconProps {\n toolType: ToolType;\n size?: number;\n className?: string;\n}\n\nexport const ToolIcon: FC<ToolIconProps> = ({ toolType, size = 16, className }) => (\n <>{toolIconMap[toolType]?.(size, className) ?? null}</>\n);\n\nToolIcon.displayName = 'ToolIcon';\n","import { clsx, type ClassValue } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\n/**\n * Utility functions for common operations\n */\n\n/**\n * Merge class names with Tailwind CSS\n * @param inputs - Class names to merge\n * @returns Merged class names\n */\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\n/**\n * Human-readable message for a caught value.\n *\n * `catch (e)` binds `unknown` under this tsconfig, and a thrown value is not\n * guaranteed to be an `Error`. Use this instead of `catch (e: any)` +\n * `e.message`, which crashes on a thrown string/object with no `message`.\n *\n * @param error - The caught value\n * @param fallback - Returned when the value carries no usable message\n */\nexport function errorMessage(error: unknown, fallback = 'Something went wrong'): string {\n if (error instanceof Error && error.message) return error.message;\n if (typeof error === 'string' && error) return error;\n if (typeof error === 'object' && error !== null) {\n const message = (error as { message?: unknown }).message;\n if (typeof message === 'string' && message) return message;\n }\n return fallback;\n}\n\n/**\n * Human-readable message for a FAILED API response body.\n *\n * `Response.json()` is typed `any`, so `body.error` used to be read off an\n * `any` at every call site. The platform's route helpers answer errors with\n * `{ error, code, details }` (see `errorResponse` in the hub's\n * `lib/api/route-base.ts`); a few endpoints answer `{ message }` instead, so\n * both are accepted before giving up.\n *\n * @param payload - The parsed response body (or whatever came back)\n * @param fallback - Returned when the body carries no usable message\n */\nexport function apiErrorMessage(payload: unknown, fallback: string): string {\n if (typeof payload === 'object' && payload !== null && 'error' in payload) {\n const { error } = payload;\n if (typeof error === 'string' && error) return error;\n }\n return errorMessage(payload, fallback);\n}\n\n/**\n * Delay execution for a specified time\n * @param ms - Milliseconds to delay\n * @returns Promise that resolves after the delay\n */\nexport function delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Generate a random string of specified length\n * @param length - Length of the string\n * @returns Random string\n */\nexport function generateRandomString(length = 8): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let result = '';\n for (let i = 0; i < length; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n return result;\n}\n\n/**\n * Truncate a string to a specified length\n * @param str - String to truncate\n * @param maxLength - Maximum length\n * @param suffix - Suffix to add to truncated string\n * @returns Truncated string\n */\nexport function truncateString(str: string, maxLength: number, suffix = '...'): string {\n if (str.length <= maxLength) return str;\n return str.substring(0, maxLength - suffix.length) + suffix;\n}\n\n/**\n * Serialize a JSON-LD schema for a `<script type=\"application/ld+json\">`\n * block — THE one home of the escape rule (the hub re-exports this from\n * lib/utils/breadcrumbs). JSON.stringify does NOT HTML-escape: a stored\n * \"</script>\" inside any admin/user-entered field would terminate the tag\n * early (stored XSS). Every \"<\" becomes the JSON escape sequence\n * backslash-u003c — still valid JSON, inert in HTML.\n */\nexport function serializeJsonLd(schema: unknown): string {\n return JSON.stringify(schema).replace(/</g, '\\\\u003c');\n}\n\n/**\n * Deep clone an object through a JSON round-trip.\n *\n * Lossy by construction, and deliberately so — this is the JSON projection of\n * `T`: `undefined` members and functions are dropped, `Date` becomes an ISO\n * string, `Map`/`Set` become `{}`, and a cyclic graph throws. Reach for\n * `structuredClone` when any of that matters.\n *\n * `JSON.parse` is typed `any`; the assertion states the contract above, which\n * is the closest a JSON clone can get to \"still a `T`\".\n *\n * @param obj - Object to clone (must be JSON-serializable)\n * @returns Cloned object\n */\nexport function deepClone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj)) as T;\n}\n\n/**\n * Get the Slack community join URL from environment variables\n * @returns Slack community join URL or fallback URL\n */\nexport function getSlackCommunityJoinUrl(): string {\n const url = process.env.NEXT_PUBLIC_SLACK_COMMUNITY_JOIN_URL;\n if (!url) {\n console.warn('NEXT_PUBLIC_SLACK_COMMUNITY_JOIN_URL is not defined in environment variables');\n return 'https://join.slack.com/t/openmsp/shared_invite/zt-36bl7mx0h-3~U2nFH6nqHqoTPXMaHEHA';\n }\n return url;\n}\n\n/**\n * Clamp a number into an inclusive range. THE one clamp for the lib and the hub\n * (step/page/contrast math all bottom out here).\n */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\n/**\n * Typed key-subset of an object. Keys whose value is `undefined` on the source\n * are still copied when present, so `pick(params, dropped)` writes explicit\n * `null`s (the URL-state writer's \"remove this key\" signal).\n */\nexport function pick<T extends object, K extends keyof T>(source: T, keys: readonly K[]): Pick<T, K> {\n const out = {} as Pick<T, K>;\n for (const key of keys) {\n if (key in source) out[key] = source[key];\n }\n return out;\n}\n\n/**\n * React Query options for data that MUST NOT be served from the client cache.\n *\n * The rule (hub memory `feedback_no_client_query_cache_for_mutable_entities`):\n * anything a user can mutate, or a cron can rewrite under them, is refetched on\n * mount. Spread this instead of retyping `staleTime: 0` — it is also the hub\n * QueryClient's default, so a hook that spreads it is explicit rather than\n * silently inheriting.\n */\nexport const NO_CLIENT_CACHE = { staleTime: 0 } as const;\n","/**\n * useNearViewport — module-level shared IntersectionObserver in hook form.\n *\n * Single IO instance per `rootMargin` value, shared across every component\n * that mounts the hook. Reduces overhead vs. one IO per component on\n * grid/list pages where many subscribers observe the viewport with the same\n * margin. Promoted from the inline singleton at\n * `multi-platform-hub/components/shared/video-bites-display.tsx:21-43`,\n * which is the only IO pattern in either repo today.\n *\n * Usage:\n * ```tsx\n * function MyCard() {\n * const { ref, isNear } = useNearViewport('500px');\n * return <div ref={ref}>{isNear ? <HeavyChild /> : <Placeholder />}</div>;\n * }\n * ```\n *\n * StrictMode safety: cleanup uses an identity check on the registered\n * callback so React's dev double-mount (mount → cleanup → re-mount) does\n * not drop the second mount's freshly-set subscription. The IO callback\n * also checks `subscribers.get(target)` before invoking so a fire that\n * races with unmount cannot crash on a torn-down component.\n *\n * The hook fires once — on first intersection it sets `isNear=true` and\n * unobserves the element. Callers that need re-observation should\n * unmount and remount (or fork the hook for two-way behavior).\n */\n\nimport { useEffect, useRef, useState, useCallback } from 'react';\n\n// Per-(rootMargin, threshold) IO map. Multiple call sites with different\n// margins/thresholds each get their own singleton observer.\nconst observers = new Map<string, IntersectionObserver>();\nconst subscribers = new WeakMap<Element, () => void>();\n\n// Slack for the explicit ratio check: an element sized to exactly meet the\n// threshold can report a ratio a hair under it (sub-pixel / float rounding), so\n// accept `ratio >= threshold - EPSILON`. With `threshold: 0` this is a no-op\n// (ratio is always ≥ 0 > -EPSILON) — the `isIntersecting` check alone gates.\nconst THRESHOLD_EPSILON = 0.01;\n\n/** Stable map key for an observer config. */\nfunction observerKey(rootMargin: string, threshold: number): string {\n return `${rootMargin}|${threshold}`;\n}\n\nfunction getObserverFor(rootMargin: string, threshold: number): IntersectionObserver {\n const key = observerKey(rootMargin, threshold);\n const existing = observers.get(key);\n if (existing) return existing;\n\n const io = new IntersectionObserver(\n entries => {\n entries.forEach(entry => {\n // Enforce the threshold EXPLICITLY. `isIntersecting` is spec-defined as\n // `intersectionRatio > 0` (any overlap), so the initial `observe()`\n // firing can report `true` at, say, 20% visible even with\n // `threshold: 0.5` — which would prematurely pass the gate. Require both\n // an intersection AND the ratio to actually meet the threshold (minus a\n // small epsilon for the float rounding where the ratio lands a hair\n // under the exact value).\n if (!entry.isIntersecting) return;\n if (entry.intersectionRatio < threshold - THRESHOLD_EPSILON) return;\n // Race-safe: re-read the callback at fire time. A late IO firing\n // after cleanup must not invoke a stale callback.\n const cb = subscribers.get(entry.target);\n if (cb) {\n cb();\n io.unobserve(entry.target);\n subscribers.delete(entry.target);\n }\n });\n },\n { rootMargin, threshold },\n );\n observers.set(key, io);\n return io;\n}\n\n/**\n * Default near-viewport lookahead — the SSOT for \"mount media on approach\".\n * Shared by this hook's default AND the raw two-way IntersectionObservers in\n * `cards-strip.tsx` / `video-bites-strip.tsx` (which need mount+unmount, not\n * this hook's fire-once semantics, but must agree on the distance).\n */\nexport const NEAR_VIEWPORT_ROOT_MARGIN = '500px';\n\nexport interface UseNearViewportResult<T extends Element = HTMLElement> {\n /** Ref to attach to the element you want to gate on visibility. */\n ref: (node: T | null) => void;\n /** Flips to `true` once the element enters within `rootMargin` of the viewport. Never flips back. */\n isNear: boolean;\n}\n\n/**\n * @param rootMargin Margin around the viewport (CSS-style string).\n * '500px' = element starts mounting 500px before scroll-in.\n * '1000px' = a full viewport's worth of lookahead.\n * '0px' = strict on-screen detection.\n * @param threshold Fraction of the element that must be visible before firing\n * (0 = any pixel — the default; 0.5 = at least half on-screen).\n */\nexport function useNearViewport<T extends Element = HTMLElement>(\n rootMargin: string = NEAR_VIEWPORT_ROOT_MARGIN,\n threshold: number = 0,\n): UseNearViewportResult<T> {\n const [isNear, setIsNear] = useState(false);\n const elRef = useRef<T | null>(null);\n const key = observerKey(rootMargin, threshold);\n\n // Subscribe/unsubscribe on element change.\n const ref = useCallback(\n (node: T | null) => {\n const prev = elRef.current;\n\n // Unsubscribe previous, if any. Identity-check the callback so a\n // StrictMode re-mount that has already re-registered keeps its sub.\n if (prev) {\n const stillOurs = subscribers.get(prev);\n if (stillOurs) {\n subscribers.delete(prev);\n observers.get(key)?.unobserve(prev);\n }\n }\n\n elRef.current = node;\n if (!node) return;\n\n const cb = () => setIsNear(true);\n subscribers.set(node, cb);\n getObserverFor(rootMargin, threshold).observe(node);\n },\n [key, rootMargin, threshold],\n );\n\n // Unsubscribe on unmount. Identity check guards the StrictMode race.\n useEffect(() => {\n return () => {\n const el = elRef.current;\n if (!el) return;\n if (subscribers.get(el)) {\n subscribers.delete(el);\n observers.get(key)?.unobserve(el);\n }\n };\n }, [key]);\n\n return { ref, isNear };\n}\n","/**\n * Fenced-code tracker — THE definition of \"am I inside a code fence\".\n * Server-safe: no React, no DOM.\n *\n * Lives in its own module because it is a GENERAL CommonMark fence machine\n * with two unrelated consumers: the heading scanner\n * (`utils/markdown-heading-id`) and the streaming block splitter\n * (`components/ui/markdown/streaming`). It used to live inside\n * `markdown-heading-id`, which meant a streaming renderer imported its fence\n * state machine from a module named after heading slugs. `markdown-heading-id`\n * re-exports these names so the public `utils` surface is unchanged.\n */\n\n/**\n * CommonMark fenced-code opener/closer. Fence indent is capped at 3 spaces\n * (4+ is an indented code block, whose backticks are literal content), and the\n * run length is captured so a closer can be required to be at least as long as\n * its opener. Matched on the RAW line — `trimStart()` would let a fence inside\n * 4-space-indented code toggle the state.\n *\n * `\\r`-TOLERANT BY CONSTRUCTION. The previous spelling ended `(.*)$`, and `.`\n * excludes `\\r` while `$` (no `m` flag) anchors at end of input — so on a CRLF\n * document, split on `\\n`, NO line ever matched and the tracker was completely\n * fence-blind: `['```js\\r','const a = 1\\r','```\\r','after\\r']` classified as\n * four `text` lines where the LF spelling gives `open/inside/close/text`. The\n * sanitizer's closer haystack then never blanked the fenced region, so a\n * `</textarea>` written as a CRLF code sample satisfied `hasLaterCloser` and a\n * prose `<textarea>` above it stayed LIVE (reproduced in the DOM; the LF twin\n * of the same fixture escapes correctly). The `\\r` is absorbed by `\\r?$` rather\n * than normalized out of the text, because the sanitizer's mask is\n * LENGTH-PRESERVING and every offset in it is an index into the original\n * string — stripping `\\r` would shift them all.\n *\n * THE ONLY COPY. This constant plus its open/close state machine used to be\n * duplicated verbatim in `components/ui/markdown/streaming.ts`, kept in sync\n * by a code comment — which is exactly how the `~~~`-blind extractor drifted\n * in the first place. Both consumers now instantiate `createFenceTracker()`.\n */\nconst FENCE_RE = /^ {0,3}(`{3,}|~{3,})([^\\n]*?)\\r?$/;\n\n/**\n * CommonMark's BLANK LINE — spaces and tabs only. The single definition, shared\n * by every consumer of this module (the sanitizer's mask passes, the heading\n * scanner, the HTML-block range walk).\n *\n * NOT `String.prototype.trim()`. JS `trim()` strips the full Unicode\n * White_Space set — U+00A0 NBSP, U+000B VT, U+000C FF, U+2028/9, U+FEFF BOM —\n * none of which CommonMark (or remark) treats as blank. Every place that meant\n * \"is this a CommonMark blank line?\" and asked `trim() === ''` therefore\n * TERMINATED a construct one line early while remark kept it open. Verified\n * end-to-end: `<div>\\n\\u00A0\\n\\`<textarea>\\`\\n\\nrest\\n` left a LIVE `<textarea>`\n * in the DOM (`escapeUnknownHtmlTags` returned the input byte-identical),\n * because the tracked HTML-block range ended at the NBSP filler line and the\n * inline-code shelter below it stopped being inside a tracked block. Same for\n * VT / FF / BOM, for `<pre>` / `<details>` wrappers, and for a live third-party\n * `<iframe>`.\n *\n * `\\r` IS accepted: a CRLF document split on `\\n` spells its blank lines\n * `\"\\r\"`, and the mask is length-preserving so stripping `\\r` from the source\n * is not an option (see `FENCE_RE`'s `\\r?$`).\n */\nconst BLANK_LINE_RE = /^[ \\t\\r]*$/;\n\n/** True when `line` is a CommonMark blank line (spaces/tabs only, `\\r`-tolerant). */\nexport function isBlankLine(line: string): boolean {\n return BLANK_LINE_RE.test(line);\n}\n\n/**\n * What one source line is, relative to fenced code:\n * - `open` — this line opened a fence\n * - `close` — this line closed the open fence\n * - `inside`— this line is fence content (including a would-be delimiter that\n * does NOT close the open fence: wrong marker char, too short, or\n * carrying an info string)\n * - `text` — this line is ordinary markdown outside any fence\n *\n * NOTE: no consumer discriminates the three non-`text` roles today — both the\n * heading scanner and the streaming splitter only test `!== 'text'`, and the\n * closer-haystack mask below only tests `=== 'open'` / `=== 'close'`. The\n * four-value union is kept because the state machine already computes the\n * distinction for free and a future consumer (e.g. fence-aware syntax\n * post-processing) would otherwise have to re-derive it.\n */\nexport type FenceLineRole = 'open' | 'close' | 'inside' | 'text';\n\nexport interface FenceTracker {\n /** Advance across one raw source line (mutates) and classify it. */\n push(line: string): FenceLineRole;\n /** Marker CHARACTER of the currently open fence (`` ` `` / `~`), or null. */\n openChar(): string | null;\n /** Run length of the currently open fence (a closer must be ≥ this). */\n openLength(): number;\n}\n\n/** A fresh fenced-code state machine. Server-safe: no React, no DOM. */\nexport function createFenceTracker(): FenceTracker {\n let fenceChar: string | null = null;\n let fenceLength = 0;\n return {\n push(line: string): FenceLineRole {\n const fence = FENCE_RE.exec(line);\n if (fence) {\n const run = fence[1];\n if (fenceChar === null) {\n fenceChar = run[0];\n fenceLength = run.length;\n return 'open';\n }\n // A closer must use the SAME marker char, be at least as long as the\n // opener, and (per CommonMark) carry no info string. \"No info string\"\n // means spaces/tabs only — `trim()` would accept an NBSP tail and close\n // a fence CommonMark keeps open, i.e. blank LESS of the haystack\n // (fail-OPEN). Hence `isBlankLine`, not `trim()`.\n if (run[0] === fenceChar && run.length >= fenceLength && isBlankLine(fence[2])) {\n fenceChar = null;\n fenceLength = 0;\n return 'close';\n }\n return 'inside';\n }\n return fenceChar === null ? 'text' : 'inside';\n },\n openChar: () => fenceChar,\n openLength: () => fenceLength,\n };\n}\n","/**\n * Markdown heading-id slug SSOT (server-safe: no React, no DOM).\n *\n * This algorithm previously existed in THREE byte-identical copies:\n * - `components/ui/simple-markdown-renderer.tsx` (generateHeadingId)\n * - `components/ui/rich-markdown-renderer.tsx` (generateHeadingId)\n * - `utils/markdown-section-extractor.ts` (extractSections)\n *\n * The extractor is the PRODUCER of `sectionIds` and the renderers are the\n * CONSUMERS — if the two ever drift, deep-link anchors and scroll-spy\n * targets silently diverge. All three now call these helpers; the parity\n * test `components/ui/__tests__/markdown-parity.test.tsx` asserts\n * extractor-vs-renderer ID agreement over the fixture corpus.\n */\n\n/** Emoji ranges stripped from heading text before slugification. */\nexport const HEADING_EMOJI_RE = /[\\u{1F300}-\\u{1F9FF}]|[\\u{2600}-\\u{26FF}]|[\\u{2700}-\\u{27BF}]/gu;\n\n/** Remove emoji characters and trim. */\nexport function stripHeadingEmojis(text: string): string {\n return text.replace(HEADING_EMOJI_RE, '').trim();\n}\n\n/**\n * Core slug chain WITHOUT the emoji strip (the extractor exposes emoji\n * stripping as an option, so the two steps are kept separable):\n * lowercase → drop non-word/space/hyphen chars → spaces to hyphens →\n * trim leading/trailing hyphens. May return `''` for symbol-only input —\n * callers apply their own fallback (`section-N`).\n */\nexport function slugifyHeadingBase(text: string): string {\n return text\n .trim()\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/\\s+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\n/** The full default chain used by the renderers: emoji strip + slugify. */\nexport function slugifyHeadingText(text: string): string {\n return slugifyHeadingBase(stripHeadingEmojis(text));\n}\n\n// ---------------------------------------------------------------------------\n// Heading SCANNER + DEDUPER (the other half of the producer/consumer contract)\n// ---------------------------------------------------------------------------\n/**\n * Sharing the slug chain alone was not enough. The PRODUCER\n * (`utils/markdown-section-extractor`) and the CONSUMER\n * (`components/ui/markdown/heading-ids`) each carried their own copy of\n * \"which lines are headings\" and \"how do duplicates get suffixed\", and the\n * copies drifted:\n * - the extractor toggled its code-block state on a bare\n * `line.startsWith('```')`, so a `~~~`-fenced (or wider-backtick, or\n * indented) block containing `## Setup` produced a SECTION from the\n * extractor and NO id from the renderer — `sectionIdMap` then missed\n * silently and the deep-link anchor pointed nowhere;\n * - the extractor anchored ATX at column 0 while the renderer allowed the\n * CommonMark 0..3-space indent;\n * - the dedupe counter was hand-copied in both files, each with a comment\n * saying \"the two must agree\".\n * Both now call `scanHeadings` + `createHeadingIdDeduper`. Server-safe: no\n * React, no DOM.\n */\n\n// The CommonMark fence machine used to live in THIS file, which meant a\n// streaming renderer imported its fence state from a module named after\n// heading slugs. It now lives in `./markdown-fences`; re-exported here so the\n// public `utils` surface (and every existing import) is unchanged.\nexport { createFenceTracker, isBlankLine, type FenceTracker, type FenceLineRole } from './markdown-fences';\nimport { createFenceTracker, isBlankLine } from './markdown-fences';\n\n/** A heading the renderer will emit, located in the source. */\nexport interface ScannedHeading {\n /** 1-based line of the heading's FIRST line (setext: the title line). */\n line: number;\n level: number;\n /** Raw title text, before `stripInlineMarkdown` / slugification. */\n text: string;\n}\n\nexport interface ScanHeadingsOptions {\n /**\n * Skip a leading YAML frontmatter block (`---` on line 1 through the next\n * `---`). Only a DOCUMENT-LEADING block counts: a bare `---` mid-document\n * is a thematic break or a setext underline, and treating it as a\n * frontmatter toggle (what the extractor used to do) silently swallowed\n * every heading until the next one.\n */\n skipFrontmatter?: boolean;\n /** Include raw-HTML headings (`<h2>Title</h2>`). Default true. */\n includeRawHtml?: boolean;\n /**\n * Skip fenced-code blocks. Default true — a `##` inside a code fence is\n * code, not a heading, and the renderer emits no id for it.\n */\n skipFences?: boolean;\n}\n\n/**\n * EVERY line-anchored regex in this module ends `\\r?$`, not `$`.\n *\n * Lines here come from `content.split('\\n')`, so on a CRLF document each one\n * carries a trailing `\\r`. `$` (no `m` flag) anchors at end of string and `\\r`\n * is not in `[ \\t]`, so a `$`-anchored pattern matches NOTHING on such a\n * document. That was a live REGRESSION: `main`'s looser `^(#{1,6})\\s+(.+)`\n * had no end anchor at all and tolerated the `\\r` (the title was `.trim()`ed\n * afterwards), so `'# Real\\r\\n\\r\\nbody\\r\\n\\r\\n## Second\\r\\n'` yielded\n * `[\"Real\",\"Second\"]` on `main` and `[]` here — every CRLF-stored doc / blog /\n * release body silently lost its TOC, its in-page anchors and its doc-SEO\n * heading links.\n *\n * The `\\r` is ABSORBED, not normalized away: `scanHeadings` reports 1-based\n * LINE numbers that the renderer's id map is keyed by, and the sanitizer's mask\n * (which shares `markdown-fences`) is length-preserving — neither may be fed a\n * rewritten source.\n */\n/** CommonMark ATX heading (closing `#` run is not part of the title). */\nconst ATX_HEADING_RE = /^ {0,3}(#{1,6})[ \\t]+(.*?)(?:[ \\t]+#+)?[ \\t]*\\r?$/;\n/** ATX with no title at all (`###`, `## ###`) — still a heading, empty text. */\nconst ATX_EMPTY_RE = /^ {0,3}(#{1,6})[ \\t]*#*[ \\t]*\\r?$/;\n/**\n * Raw-HTML heading (`<h2 id=\"x\">Title</h2>`) — rehype-raw renders these too.\n * GLOBAL: two `<h3>`s on one line are two headings, and a non-global scan\n * silently dropped the second (it then fell through to the renderer's\n * suffix-free fallback and emitted a DUPLICATE DOM id).\n */\nconst RAW_HEADING_RE = /<h([1-6])\\b[^>]*>([\\s\\S]*?)(?:<\\/h\\1>|$)/gi;\n/**\n * Blockquote markers and list-item markers preceding an ATX heading\n * (`> ## Setup`, `- ## Setup`, `1. ## Setup`). mdast emits a REAL `<h2>` for\n * these; scanning only column-0..3 missed them entirely, so two identical\n * `> ## Setup` headings both hit the suffix-free fallback and emitted the\n * duplicate DOM ids this whole module exists to prevent.\n */\nconst CONTAINER_PREFIX_RE = /^ {0,3}(?:(?:>[ \\t]?)+|(?:[-+*]|\\d{1,9}[.)])[ \\t]+)+/;\n/** Setext underline (`===` → h1, `---` → h2), AFTER container-prefix strip. */\nconst SETEXT_UNDERLINE_RE = /^ {0,3}(=+|-+)[ \\t]*\\r?$/;\n/** Thematic break — ends a paragraph run, never underlines it. */\nconst THEMATIC_BREAK_RE = /^ {0,3}(\\*|_){3,}[ \\t]*\\r?$/;\n/**\n * CommonMark HTML-block type 6 tag names — these open a raw HTML block no\n * matter what follows them on the line.\n */\nconst HTML_BLOCK_TAGS =\n 'address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul';\n\n/**\n * A line that OPENS a raw HTML block. mdast hands the whole block to the HTML\n * parser, so a `---` inside it is not a setext underline and the lines above\n * it are not a paragraph: `<div>\\nText\\n---\\n</div>` emits NO heading. The\n * scanner used to publish a phantom `Text` h2 there.\n *\n * The naive `^ {0,3}<` this replaced disqualified any run whose first line\n * merely STARTED with a tag, so `<span>x</span> more text` + `---` (a plain\n * paragraph in mdast, yielding an h2) was missed. The alternatives are spelled\n * out per CommonMark:\n * - types 1-5: `<script|pre|style|textarea`, `<!--`, `<?`, `<!X`, `<![CDATA[`\n * - type 6: a `HTML_BLOCK_TAGS` name, whatever follows it\n * - type 7: ANY complete open/closing tag ALONE on the line (trailing\n * whitespace only) — this is the clause the old regex got wrong\n * Attribute soup inside a type-7 tag is approximated with `[^>]*` rather than\n * a full attribute grammar; the error bias is unchanged (a missed run costs a\n * TOC entry, never a wrong id — the same direction as the documented\n * list-item-indent gap in `SetextRun.prefix`).\n */\nconst HTML_BLOCK_OPENER_RE = new RegExp(\n '^ {0,3}(?:' +\n // types 1-5\n '<(?:script|pre|style|textarea)(?:[\\\\s>]|$)|<!--|<\\\\?|<![a-zA-Z]|<!\\\\[CDATA\\\\[' +\n // type 6\n `|</?(?:${HTML_BLOCK_TAGS})(?:[\\\\s/>]|$)` +\n // type 7 — a complete tag standing alone on the line\n '|<[a-zA-Z][a-zA-Z0-9-]*(?:\\\\s[^>]*)?/?>[ \\\\t]*\\\\r?$' +\n '|</[a-zA-Z][a-zA-Z0-9-]*[ \\\\t]*>[ \\\\t]*\\\\r?$' +\n ')',\n 'i',\n);\n\n/**\n * The paragraph RUN that a setext underline would convert into a heading.\n *\n * mdast positions a setext heading at the FIRST line of the paragraph and its\n * text is the WHOLE run (`Foo\\nbar\\n===` → `{line:1, text:\"Foo\\nbar\"}`). The\n * scanner used to remember only the LAST line, so the renderer's line-keyed\n * lookup missed the heading entirely (falling back to a slug of the rendered\n * children, `foo-bar`) while the extractor published `bar` — a dead deep\n * link, plus a phantom TOC entry at the wrong line.\n */\ninterface SetextRun {\n /** 1-based line of the run's FIRST line — where mdast puts the heading. */\n line: number;\n /**\n * Container prefix (`> `, `- `, …) every line of the run shares. The\n * underline must carry the IDENTICAL prefix, which is why `> Quote` +\n * `> ---` scans as an h2 while `> Quote` + a bare `---` does not.\n *\n * KNOWN, DELIBERATE GAP: a setext underline indented to a LIST ITEM's\n * content column (`- item` / ` ---`) is a heading in mdast but has no\n * container prefix at all, so this equality test misses it. Closing that\n * would mean re-deriving list-item content columns here — the scanner\n * simply emits nothing (the pre-existing behavior), which costs a TOC entry\n * and never produces a WRONG id.\n */\n prefix: string;\n /** Run lines with the container prefix stripped, in order. */\n lines: string[];\n /** Run opened with a raw-HTML block line — mdast emits no heading for it. */\n disqualified: boolean;\n}\n\n/**\n * Collect every heading the markdown renderer will emit, in document order.\n * THE single definition of \"which lines are headings\" for both the extractor\n * and the renderer's id map.\n */\nexport function scanHeadings(content: string, options: ScanHeadingsOptions = {}): ScannedHeading[] {\n const { skipFrontmatter = true, includeRawHtml = true, skipFences = true } = options;\n const out: ScannedHeading[] = [];\n const lines = content.split('\\n');\n // ONE fenced-code state machine (utils/markdown-fences), shared with\n // markdown/streaming.ts.\n const fences = skipFences ? createFenceTracker() : null;\n\n let start = 0;\n if (skipFrontmatter && lines[0]?.trim() === '---') {\n for (let i = 1; i < lines.length; i++) {\n if (lines[i].trim() === '---' || lines[i].trim() === '...') {\n start = i + 1;\n break;\n }\n }\n }\n\n // The paragraph run a setext underline would convert (see SetextRun).\n let setextRun: SetextRun | null = null;\n\n for (let i = start; i < lines.length; i++) {\n const line = lines[i];\n if (fences) {\n const role = fences.push(line);\n if (role !== 'text') {\n setextRun = null;\n continue;\n }\n }\n\n // Container prefix (`> `, `- `, `1. `) is stripped from EVERY construct\n // below, so a blockquote/list-nested heading is scanned in both its ATX\n // (`> ## Setup`) and setext (`> Quote title` / `> ---`) spellings.\n const prefix = CONTAINER_PREFIX_RE.exec(line)?.[0] ?? '';\n const body = prefix ? line.slice(prefix.length) : line;\n\n // --- setext (`Title` / `===`): a REAL h1/h2 in mdast, positioned at the\n // run's FIRST line — which is the line the heading-id map is keyed by.\n // The underline must carry the SAME container prefix as the run it\n // closes; `> Quote` followed by a bare `---` is a quote and a thematic\n // break, not a heading.\n const setext = SETEXT_UNDERLINE_RE.exec(body);\n if (setext) {\n if (setextRun && !setextRun.disqualified && setextRun.prefix === prefix) {\n out.push({\n line: setextRun.line,\n level: setext[1][0] === '=' ? 1 : 2,\n text: setextRun.lines.join('\\n'),\n });\n }\n setextRun = null;\n continue;\n }\n\n // --- ATX, including inside a blockquote / list item.\n const atx = ATX_HEADING_RE.exec(body) ?? ATX_EMPTY_RE.exec(body);\n if (atx) {\n out.push({ line: i + 1, level: atx[1].length, text: (atx[2] ?? '').trim() });\n setextRun = null;\n continue;\n }\n\n if (includeRawHtml && line.indexOf('<') !== -1) {\n RAW_HEADING_RE.lastIndex = 0;\n let raw: RegExpExecArray | null;\n let matched = false;\n while ((raw = RAW_HEADING_RE.exec(line)) !== null) {\n matched = true;\n out.push({\n line: i + 1,\n level: Number(raw[1]),\n text: raw[2].replace(/<[^>]*>/g, '').trim(),\n });\n }\n if (matched) {\n setextRun = null;\n continue;\n }\n }\n\n // Paragraph accumulation. A blank line or a thematic break ends the run;\n // a change of container prefix starts a new block (a list or blockquote\n // interrupts a paragraph in CommonMark).\n // CommonMark's blank line (spaces/tabs), NOT `trim()` — an NBSP-only line\n // is paragraph CONTENT to remark, so ending the run there would move a\n // setext heading's reported line off the run's first line.\n if (isBlankLine(body) || THEMATIC_BREAK_RE.test(body)) {\n setextRun = null;\n continue;\n }\n if (setextRun && setextRun.prefix === prefix) {\n setextRun.lines.push(body.trim());\n } else {\n setextRun = {\n line: i + 1,\n prefix,\n lines: [body.trim()],\n disqualified: HTML_BLOCK_OPENER_RE.test(body),\n };\n }\n }\n\n return out;\n}\n\n/**\n * The duplicate-id suffix counter, as ONE closure both sides instantiate.\n * First occurrence keeps the bare slug; the Nth gets `-N`. Extractor and\n * renderer MUST use the same counter or `#anchor` deep links diverge.\n */\nexport function createHeadingIdDeduper(): (cleanId: string) => string {\n const counts: Record<string, number> = {};\n return (cleanId: string): string => {\n if (counts[cleanId]) {\n counts[cleanId]++;\n return `${cleanId}-${counts[cleanId]}`;\n }\n counts[cleanId] = 1;\n return cleanId;\n };\n}\n","/**\n * GitHub-compatible anchor resolution for in-page `#hash` links.\n *\n * ## The mismatch this exists to bridge\n *\n * Doc authors write their table of contents against GitHub's slugger, which\n * keeps the separator left behind by a stripped emoji:\n *\n * `## 📚 Table of Contents` → GitHub anchor `#-table-of-contents`\n *\n * Our heading ids come from the shared slug SSOT (`markdown-heading-id`),\n * whose `slugifyHeadingBase` trims leading and trailing hyphens — so the same\n * heading renders as `id=\"table-of-contents\"`. The \"On this page\" rail\n * navigates by those ids and works; the in-body TOC link points at an id that\n * does not exist and the browser silently does nothing.\n *\n * Rather than change the id shape (it is already baked into shared URLs and\n * the rail), resolution is made tolerant: compare a *normalized* form of both\n * sides. This module owns ONLY that tolerance — the slug chain itself is\n * imported, never re-implemented, so a change to the id shape lands in one\n * place and both sides move together.\n *\n * Callers do not reach for this directly: `getHashTargetElement`\n * (`utils/same-page-hash-nav`) is the ONE resolver every hash consumer goes\n * through, and it applies this as its last pass.\n */\nimport { slugifyHeadingText } from './markdown-heading-id';\n\n/**\n * Reduce an anchor id (ours or GitHub's) to a comparable form.\n *\n * Everything but the final hyphen-run collapse is the shared heading-slug\n * chain: emoji strip → lowercase → drop non-word chars → spaces to hyphens →\n * trim edge hyphens. The collapse is this module's own addition, covering\n * GitHub's *interior* divergence — `## 💬 Community & Support` slugs to\n * `#-community--support` (a double hyphen around the dropped `&`) against our\n * `community-support`.\n *\n * `'-getting-started'` → `'getting-started'`\n * `'-community--support'` → `'community-support'`\n * `'Getting Started'` → `'getting-started'`\n */\nexport function normalizeAnchorId(raw: string): string {\n return slugifyHeadingText(raw)\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\n/** Heading elements carrying an id — the candidate set for the fuzzy pass. */\nconst HEADING_SELECTOR = 'h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]';\n\n/** A `base-N` id, split into its base and ordinal. */\nconst DUPLICATE_SUFFIX_RE = /^(.+)-(\\d+)$/;\n\n/**\n * The two sides also disagree on where duplicate-heading numbering STARTS.\n * For a document with two `## Setup` headings GitHub emits `setup` and\n * `setup-1`, while `createHeadingIdDeduper` emits `setup` and `setup-2` (its\n * suffix is the occurrence COUNT, not the offset). So a GitHub `#setup-1`\n * needs our `setup-2` — every duplicate is off by exactly one.\n *\n * Runs LAST, after the exact lookup and the heading scan have both missed: a\n * heading that genuinely slugs to `step-2` is resolved long before this, and\n * the shift is the one pass that can match an id it was not asked for.\n */\nfunction findDuplicateShifted(normalized: string, doc: Document): HTMLElement | null {\n const parts = DUPLICATE_SUFFIX_RE.exec(normalized);\n if (!parts) return null;\n const ordinal = Number(parts[2]);\n if (!Number.isSafeInteger(ordinal)) return null;\n return doc.getElementById(`${parts[1]}-${ordinal + 1}`);\n}\n\n/**\n * Resolve a `#hash` id that no exact lookup matched, by comparing normalized\n * forms. Returns `null` when nothing in the document matches, so the caller\n * can leave the browser's default behavior alone rather than hijacking a\n * click that was never ours to handle.\n *\n * Three passes, in order of how much they assume:\n * 1. a single `getElementById` on the normalized id — catches the whole\n * emoji-hyphen family without walking the DOM;\n * 2. a heading scan — catches ids whose own raw form normalizes differently\n * (e.g. `a---b`, from a title containing a literal ` - `);\n * 3. the duplicate-heading shift (see `findDuplicateShifted`) — last,\n * because it is the only pass that resolves to an id the fragment did\n * not name.\n */\nexport function findAnchorElementByNormalizedId(rawId: string, doc: Document): HTMLElement | null {\n const normalized = normalizeAnchorId(rawId);\n if (!normalized) return null;\n\n if (normalized !== rawId) {\n const direct = doc.getElementById(normalized);\n if (direct) return direct;\n }\n\n for (const heading of Array.from(doc.querySelectorAll<HTMLElement>(HEADING_SELECTOR))) {\n if (normalizeAnchorId(heading.id) === normalized) return heading;\n }\n\n // Last: the shift would happily match an unrelated `x-3` for a `x-2` that\n // has no heading at all, so it runs only once the scan has come up empty.\n return findDuplicateShifted(normalized, doc);\n}\n","/**\n * `scrollElementIntoView` — canonical \"scroll an element to the top of the\n * viewport, account for sticky chrome, survive layout shifts\" helper.\n *\n * One shared implementation so every caller (the ticket drawer expand, the\n * hub's `useUnifiedNav` / `use-nav-link` hash scroll, doc-tree, delivery\n * `?focus=`, sticky-section-nav, …) inherits the SAME cancellation-proof\n * motion.\n *\n * WHY A SELF-DRIVEN rAF TWEEN INSTEAD OF `window.scrollTo({behavior:'smooth'})`:\n * the native smooth scroll is CANCELLABLE, and in real pages it gets cancelled\n * constantly:\n *\n * - Browser SCROLL ANCHORING: when content is inserted/removed above or\n * around the target (a collapsible drawer expanding, an async image\n * loading, a list re-rendering) the browser issues a synchronous scrollTop\n * correction to keep the anchored element stable. Per CSSOM-View \"perform a\n * scroll\" step 1 (\"abort any ongoing smooth scroll\"), that correction\n * ABORTS an in-flight native smooth scroll — so it lands as an instant jump.\n * Anchoring is suppressed when the scroll offset is 0, which is exactly why\n * a native smooth scroll appears to work the FIRST time (page at top) and\n * jumps on every repeat (page already scrolled). This was a multi-day\n * \"smooth only works once\" bug on the /tickets drawer.\n * - A second programmatic scroll on the same frame, or a `focus()` without\n * `{preventScroll:true}`, cancels it the same way.\n *\n * A tween that re-asserts the position with INSTANT writes every frame is\n * immune: there is no \"ongoing native smooth scroll\" for anchoring/focus to\n * abort, and any correction that lands between our frames is overwritten on the\n * next frame. We also RECOMPUTE the target each frame, so an element whose\n * final position is still settling (drawer still expanding, images loading)\n * is tracked to its resting place instead of animating to a stale pixel.\n *\n * Honors `prefers-reduced-motion` (jumps instantly) and cancels on genuine user\n * scroll intent (wheel / touch) so we never fight the user.\n *\n * WINDOW *OR* A SCROLLABLE ANCESTOR: the helper is not hard-wired to the window\n * scroller. It walks up from the target to the nearest ancestor that is an\n * actual scroll container (`overflow-y: auto | scroll | overlay` AND\n * `scrollHeight > clientHeight`) and drives THAT element; only when none exists\n * does it fall back to `window`. This is what makes it work inside app shells\n * that put page content in a fixed-height `<main class=\"overflow-y-auto\">`\n * (e.g. OpenFrame's `AppLayout`) where the document/window never scrolls — the\n * old window-only version was a silent no-op there. Note `overflow: clip` /\n * `hidden` are deliberately NOT treated as scroll containers, so a list wrapper\n * that uses `overflow-clip` only to round its corners still bubbles the scroll\n * up to the real container (matches the `<HelpCenterCard>` list intent).\n */\n\nexport interface ScrollElementIntoViewOptions {\n /** Pixels to subtract from the target element's `top` so it lands BELOW\n * sticky chrome. Defaults to 0. Pass `96` for the standard hub header. */\n headerOffset?: number;\n /** `'smooth'` (default) runs the self-driven tween; `'instant'` / `'auto'`\n * jump in one synchronous write (deep-link land, programmatic focus moves). */\n behavior?: ScrollBehavior;\n /** Optional adjustment applied to the computed pixel target each frame. The\n * callback receives the \"raw\" Y (`element.top + scrollY - headerOffset`) and\n * returns the FINAL target. Use when the caller knows about a layout shift\n * (e.g. a sibling drawer collapsing) the geometry can't yet reflect. */\n adjustTargetY?: (rawTargetY: number) => number;\n /** Tween duration in ms (smooth only). Default 320. */\n durationMs?: number;\n}\n\n/** Module-level handle to the in-flight tween so a new call (or a user\n * gesture) cancels the previous one — only ever one page-scroll animation at\n * a time. */\nlet activeRaf = 0;\nlet teardownActive: (() => void) | null = null;\n\nfunction cancelActiveScroll(): void {\n if (activeRaf) {\n cancelAnimationFrame(activeRaf);\n activeRaf = 0;\n }\n if (teardownActive) {\n teardownActive();\n teardownActive = null;\n }\n}\n\nconst easeOutCubic = (t: number): number => 1 - Math.pow(1 - t, 3);\n\n/** Nearest ancestor that is a *real* scroll container, or `null` when the\n * window/document is the scroller. Only `auto | scroll | overlay` count —\n * `clip` / `hidden` are intentionally excluded (a wrapper using `overflow-clip`\n * purely to round corners must let the scroll bubble to the page).\n *\n * THE one rule for \"what scrolls this element\": `useScrollSpy` resolves the\n * scroller it listens to with it, so the section a spy highlights is the\n * section this helper scrolls to — inside a `<main overflow-y-auto>` shell as\n * much as on a window-scrolled page. */\nexport function getScrollableAncestor(el: HTMLElement): HTMLElement | null {\n for (let node = el.parentElement; node; node = node.parentElement) {\n const overflowY = getComputedStyle(node).overflowY;\n if (\n (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') &&\n node.scrollHeight > node.clientHeight\n ) {\n return node;\n }\n }\n return null;\n}\n\n/**\n * Scroll the page so `target` lands at the top of the viewport (below sticky\n * chrome via `headerOffset`). SSR-safe; `null`/`undefined` target is a no-op so\n * callers can pass refs without defensive branching.\n */\nexport function scrollElementIntoView(\n target: HTMLElement | null | undefined,\n options: ScrollElementIntoViewOptions = {},\n): void {\n if (typeof window === 'undefined' || !target) return;\n const { headerOffset = 0, behavior = 'smooth', adjustTargetY, durationMs = 320 } = options;\n\n // Pick the scroller ONCE: a fixed-height `<main overflow-y-auto>` shell scrolls\n // the element, a plain document scrolls the window. The choice can't change\n // mid-tween, so resolve it up front and route every read/write through it.\n const container = getScrollableAncestor(target);\n const readCurrent = (): number => (container ? container.scrollTop : window.scrollY);\n const writeTo = (y: number): void => {\n if (container) container.scrollTop = y;\n else window.scrollTo(0, y);\n };\n\n // Target is recomputed every frame: the row's absolute position can move as\n // the page reflows (a sibling drawer collapsing) and the reachable max grows\n // as the just-opened drawer expands. Clamp to the LIVE max each frame.\n const computeTarget = (): number => {\n const raw = container\n ? container.scrollTop +\n (target.getBoundingClientRect().top - container.getBoundingClientRect().top) -\n headerOffset\n : target.getBoundingClientRect().top + window.scrollY - headerOffset;\n const adjusted = adjustTargetY ? adjustTargetY(raw) : raw;\n const maxScroll = container\n ? Math.max(0, container.scrollHeight - container.clientHeight)\n : Math.max(0, document.documentElement.scrollHeight - window.innerHeight);\n return Math.min(Math.max(0, adjusted), maxScroll);\n };\n\n // Any prior animation loses — one page scroll at a time.\n cancelActiveScroll();\n\n const prefersReduced =\n typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n // Instant paths: a single synchronous write. No tween, no anchoring race.\n if (behavior === 'instant' || behavior === 'auto' || prefersReduced) {\n writeTo(computeTarget());\n return;\n }\n\n // Smooth: self-driven tween with instant per-frame writes (anchoring-proof).\n let startY: number | null = null;\n let startTime = 0;\n\n // Bail the moment the user takes over with a real scroll gesture — we must\n // never fight them. (Not keydown: the ticket composer auto-focuses on open,\n // and typing there should not abort the scroll.)\n const onUserGesture = () => cancelActiveScroll();\n window.addEventListener('wheel', onUserGesture, { passive: true });\n window.addEventListener('touchmove', onUserGesture, { passive: true });\n teardownActive = () => {\n window.removeEventListener('wheel', onUserGesture);\n window.removeEventListener('touchmove', onUserGesture);\n };\n\n const step = (now: number) => {\n if (startY === null) {\n startY = readCurrent();\n startTime = now;\n }\n const targetY = computeTarget();\n const t = Math.min(1, (now - startTime) / durationMs);\n const y = startY + (targetY - startY) * easeOutCubic(t);\n writeTo(y);\n if (t < 1) {\n activeRaf = requestAnimationFrame(step);\n } else {\n // Final exact write in case easing left a sub-pixel gap, then teardown.\n writeTo(computeTarget());\n activeRaf = 0;\n if (teardownActive) {\n teardownActive();\n teardownActive = null;\n }\n }\n };\n activeRaf = requestAnimationFrame(step);\n}\n","import { findAnchorElementByNormalizedId } from './anchor-id';\nimport { scrollElementIntoView } from './scroll-into-view';\n\n/** Pages with a section-nav STRIP on top of the global hub header\n * (dev-center roadmap/delivery/tickets, FAQ category-pill nav).\n * Anchor lands BELOW both layers. */\nexport const STICKY_HEADER_OFFSET_PX = 96;\n\n/** Pages with only the global hub header (docs, blog, vendor detail).\n * Anchor lands BELOW the header bar. */\nexport const HUB_HEADER_OFFSET_PX = 80;\n\n/**\n * Take only the FIRST hash segment from a fragment that may contain extra\n * `#` characters. `'' → ''`, `'#a' → '#a'`, `'#a#b' → '#a'`.\n *\n * No real DOM id contains `#`, so a multi-fragment hash is always a bug at\n * the composer site; `navigateSamePageHash` + `useScrollToHash` both call\n * this so URL bar and `getElementById` stay in sync.\n */\nexport function normalizeHashFragment(hash: string): string {\n if (!hash) return '';\n const second = hash.indexOf('#', 1);\n return second < 0 ? hash : hash.slice(0, second);\n}\n\n/**\n * Resolve the DOM element a hash fragment id points at — THE hash resolver;\n * `navigateSamePageHash`, `useScrollToHash` and the markdown link renderer\n * all go through this one, so a fragment that resolves for a deep link\n * resolves for an in-body click too.\n *\n * Three passes, cheapest first:\n * 1. the raw id (ordinary anchors — the overwhelming common case);\n * 2. the percent-decoded form — href composers like `buildTicketOpenHref`\n * encode the id into the fragment while rows render the raw id, so\n * `#ticket-a%2Fb` must still find `id=\"ticket-a/b\"`. A malformed escape\n * sequence just falls through;\n * 3. a NORMALIZED match against the document's headings — doc bodies are\n * authored on GitHub, whose slugger keeps the hyphen left behind by a\n * stripped emoji (`## 📚 Table of Contents` → `#-table-of-contents`)\n * while our ids trim it. Without this every in-body TOC link in every\n * GitHub-authored doc resolves to nothing and clicking one does nothing.\n * See `utils/anchor-id`.\n */\nexport function getHashTargetElement(id: string): HTMLElement | null {\n if (!id) return null;\n const direct = document.getElementById(id);\n if (direct) return direct;\n\n let decoded = id;\n try {\n decoded = decodeURIComponent(id);\n if (decoded !== id) {\n const decodedEl = document.getElementById(decoded);\n if (decodedEl) return decodedEl;\n }\n } catch {\n // malformed escape — the raw lookup above already covered it\n decoded = id;\n }\n\n return findAnchorElementByNormalizedId(decoded, document);\n}\n\nexport interface NavigateSamePageHashOptions {\n /** Pixels to subtract for sticky chrome. */\n headerOffset?: number;\n /** `'push'` (default) — new history entry; `'replace'` — overwrite\n * current entry (use for TOC-style in-page navigators). */\n history?: 'push' | 'replace';\n}\n\n/**\n * Same-page hash navigation primitive: pushState + synthetic `hashchange`\n * + anchoring-proof smooth scroll. Replaces `router.push` for hash CTAs\n * (Next.js suppresses smooth-scroll during navigation; `router.push` on\n * an exact-URL match is a no-op). Returns `true` when the helper claimed\n * the nav (same pathname + search); `false` for cross-page targets so\n * callers fall through to `router.push`.\n *\n * `target` accepts an origin-stripped path (`/x#anchor`) or a bare hash\n * (`#anchor`); bare-hash callers don't need to reconstruct `pathname +\n * search` themselves.\n */\nexport function navigateSamePageHash(target: string, options: NavigateSamePageHashOptions = {}): boolean {\n if (typeof window === 'undefined') return false;\n const { headerOffset = 0, history: historyMode = 'push' } = options;\n const normalizedTarget = target.startsWith('#') ? window.location.pathname + window.location.search + target : target;\n // `new URL(absoluteUrl, base)` ignores `base` per RFC 3986; an absolute\n // cross-origin target sharing pathname/search would otherwise pass the\n // check below and trip pushState's same-origin enforcement. Parse with\n // an explicit base so malformed inputs cleanly fall through.\n let url: URL;\n try {\n url = new URL(normalizedTarget, window.location.href);\n } catch {\n return false;\n }\n if (\n url.origin !== window.location.origin ||\n url.pathname !== window.location.pathname ||\n url.search !== window.location.search\n ) {\n return false;\n }\n const current = window.location.pathname + window.location.search + window.location.hash;\n // Heal a malformed multi-fragment hash so the URL bar is clean and\n // `getElementById` resolves. Dev-warn fingers the upstream composer.\n const normalizedHash = normalizeHashFragment(url.hash);\n if (process.env.NODE_ENV === 'development' && normalizedHash !== url.hash) {\n console.warn(\n `[navigateSamePageHash] malformed fragment \"${url.hash}\" → normalizing to \"${normalizedHash}\". Fix the upstream composer.`,\n );\n }\n const next = url.pathname + url.search + normalizedHash;\n const id = normalizedHash && normalizedHash !== '#' ? normalizedHash.slice(1) : '';\n // Hash-less targets are only ours on an EXACT URL re-click.\n if (!id && next !== current) return false;\n if (next !== current) {\n const oldURL = window.location.href;\n if (historyMode === 'replace') {\n window.history.replaceState(null, '', next);\n } else {\n window.history.pushState(null, '', next);\n }\n // Synthetic `hashchange` — `pushState` doesn't fire it (HTML spec),\n // so URL-hash-bound listeners (FAQ auto-expand, etc.) wouldn't react.\n window.dispatchEvent(\n new HashChangeEvent('hashchange', {\n oldURL,\n newURL: window.location.href,\n }),\n );\n }\n const el = id ? getHashTargetElement(id) : null;\n if (id && !el && process.env.NODE_ENV === 'development') {\n console.warn(`[navigateSamePageHash] anchor \"#${id}\" not found — scrolling to top.`);\n }\n // Missing anchor → tween to page top. `documentElement` is at 0 by\n // definition, so one tween covers both branches.\n scrollElementIntoView(el ?? document.documentElement, {\n behavior: 'smooth',\n headerOffset,\n });\n return true;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import {
|
|
3
3
|
SearchInput
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-MHTB67ZH.js";
|
|
5
5
|
import {
|
|
6
6
|
contentFetch
|
|
7
7
|
} from "./chunk-UAKWSR3U.js";
|
|
@@ -12,10 +12,10 @@ import {
|
|
|
12
12
|
resolveExternalNavigation,
|
|
13
13
|
resolveSourceIcon,
|
|
14
14
|
stripSameOriginToPath
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-YPXXXX6R.js";
|
|
16
16
|
import {
|
|
17
17
|
useDebounce
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-JNUL3ZWK.js";
|
|
19
19
|
import {
|
|
20
20
|
useRouter
|
|
21
21
|
} from "./chunk-XXMHLZ3Y.js";
|
|
@@ -370,4 +370,4 @@ export {
|
|
|
370
370
|
resolveSearchResultAction,
|
|
371
371
|
useDocSearch
|
|
372
372
|
};
|
|
373
|
-
//# sourceMappingURL=chunk-
|
|
373
|
+
//# sourceMappingURL=chunk-JBJZL5PI.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
FleetMdmLogoGreyIcon,
|
|
5
5
|
GoogleIcon,
|
|
6
6
|
MeshcentralLogoGreyIcon,
|
|
7
|
-
|
|
7
|
+
MicrosoftLogoGreyIcon,
|
|
8
8
|
OpenframeLogoGreyIcon,
|
|
9
9
|
OsqueryLogoGreyIcon
|
|
10
10
|
} from "./chunk-UZEW5Z7R.js";
|
|
@@ -282,9 +282,7 @@ var toolIconMap = {
|
|
|
282
282
|
[ToolTypeValues.AUTHENTIK]: (size, className) => /* @__PURE__ */ jsx(AuthentikLogoGreyIcon, { size, className }),
|
|
283
283
|
[ToolTypeValues.OSQUERY]: (size, className) => /* @__PURE__ */ jsx(OsqueryLogoGreyIcon, { size, className }),
|
|
284
284
|
[ToolTypeValues.SYSTEM]: () => null,
|
|
285
|
-
|
|
286
|
-
// own brand is what the logs and the directory pickers name.
|
|
287
|
-
[ToolTypeValues.MICROSOFT_365]: (size, className) => /* @__PURE__ */ jsx(Office365LogoGreyIcon, { size, className }),
|
|
285
|
+
[ToolTypeValues.MICROSOFT_365]: (size, className) => /* @__PURE__ */ jsx(MicrosoftLogoGreyIcon, { size, className }),
|
|
288
286
|
[ToolTypeValues.GOOGLE_WORKSPACE]: (size, className) => /* @__PURE__ */ jsx(GoogleIcon, { size, className })
|
|
289
287
|
};
|
|
290
288
|
var ToolIcon = ({ toolType, size = 16, className }) => /* @__PURE__ */ jsx(Fragment, { children: toolIconMap[toolType]?.(size, className) ?? null });
|
|
@@ -786,4 +784,4 @@ export {
|
|
|
786
784
|
getHashTargetElement,
|
|
787
785
|
navigateSamePageHash
|
|
788
786
|
};
|
|
789
|
-
//# sourceMappingURL=chunk-
|
|
787
|
+
//# sourceMappingURL=chunk-JNUL3ZWK.js.map
|