@flamingo-stack/openframe-frontend-core 0.0.628 → 0.0.629-2171.6182.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-QS2QCXBH.js → chunk-2J7EFH4V.js} +380 -30
- package/dist/chunk-2J7EFH4V.js.map +1 -0
- package/dist/{chunk-X3LC6R37.js → chunk-32P6KUZP.js} +2 -2
- package/dist/{chunk-EHAYNUOL.cjs → chunk-4E7XCEV3.cjs} +77 -2
- package/dist/chunk-4E7XCEV3.cjs.map +1 -0
- package/dist/{chunk-JONR3BDJ.cjs → chunk-53ARMJHM.cjs} +37 -37
- package/dist/{chunk-JONR3BDJ.cjs.map → chunk-53ARMJHM.cjs.map} +1 -1
- package/dist/{chunk-OQHFHKUG.cjs → chunk-55X46LKR.cjs} +450 -100
- package/dist/chunk-55X46LKR.cjs.map +1 -0
- package/dist/{chunk-U4UNC3RP.js → chunk-5BUEB2WQ.js} +12 -12
- package/dist/{chunk-6AFJQOT2.js → chunk-65IVNHBS.js} +4 -4
- package/dist/{chunk-U7TTQV4N.cjs → chunk-6I3KNDBF.cjs} +3 -3
- package/dist/{chunk-U7TTQV4N.cjs.map → chunk-6I3KNDBF.cjs.map} +1 -1
- package/dist/{chunk-S6WBBSII.js → chunk-76HB456V.js} +5 -5
- package/dist/{chunk-HLZKMYST.js → chunk-7ZDPJ6SW.js} +4 -4
- package/dist/{chunk-L6GJV7E7.cjs → chunk-BQ6QZUZ6.cjs} +83 -83
- package/dist/{chunk-L6GJV7E7.cjs.map → chunk-BQ6QZUZ6.cjs.map} +1 -1
- package/dist/{chunk-MB4IEWLH.js → chunk-BS6ASI3D.js} +3 -3
- package/dist/{chunk-Q544C4Z7.cjs → chunk-CHRPZ5PV.cjs} +25 -25
- package/dist/{chunk-Q544C4Z7.cjs.map → chunk-CHRPZ5PV.cjs.map} +1 -1
- package/dist/{chunk-LLSX5T7X.js → chunk-CIRD5P4U.js} +7 -7
- package/dist/{chunk-YQCA4ZEJ.js → chunk-CMUNJZWN.js} +2 -2
- package/dist/{chunk-UBX3ATG5.cjs → chunk-CP3R4GRA.cjs} +451 -436
- package/dist/chunk-CP3R4GRA.cjs.map +1 -0
- package/dist/{chunk-2E543KJD.js → chunk-D7VNHPJB.js} +10 -8
- package/dist/{chunk-2E543KJD.js.map → chunk-D7VNHPJB.js.map} +1 -1
- package/dist/{chunk-TDKOW2C5.cjs → chunk-DDUG42FK.cjs} +28 -26
- package/dist/chunk-DDUG42FK.cjs.map +1 -0
- package/dist/{chunk-SWJ6QLD7.cjs → chunk-ELKTBTGR.cjs} +105 -105
- package/dist/{chunk-SWJ6QLD7.cjs.map → chunk-ELKTBTGR.cjs.map} +1 -1
- package/dist/{chunk-6QLOSGE7.cjs → chunk-F4JGAGI3.cjs} +49 -47
- package/dist/chunk-F4JGAGI3.cjs.map +1 -0
- package/dist/{chunk-TUUSLED7.js → chunk-FENZRLVO.js} +10 -8
- package/dist/{chunk-TUUSLED7.js.map → chunk-FENZRLVO.js.map} +1 -1
- package/dist/{chunk-VCY2KHOE.cjs → chunk-FTWVYXNP.cjs} +34 -34
- package/dist/{chunk-VCY2KHOE.cjs.map → chunk-FTWVYXNP.cjs.map} +1 -1
- package/dist/{chunk-C3DDNRJG.cjs → chunk-FYC3W72E.cjs} +6 -6
- package/dist/{chunk-C3DDNRJG.cjs.map → chunk-FYC3W72E.cjs.map} +1 -1
- package/dist/{chunk-GH4WLDPS.cjs → chunk-G5FL4QTN.cjs} +18 -18
- package/dist/{chunk-GH4WLDPS.cjs.map → chunk-G5FL4QTN.cjs.map} +1 -1
- package/dist/{chunk-BND25SXU.cjs → chunk-GUCKPOPQ.cjs} +42 -42
- package/dist/{chunk-BND25SXU.cjs.map → chunk-GUCKPOPQ.cjs.map} +1 -1
- package/dist/{chunk-HNNR5CGX.js → chunk-HRRKZWFF.js} +10 -8
- package/dist/{chunk-HNNR5CGX.js.map → chunk-HRRKZWFF.js.map} +1 -1
- package/dist/{chunk-WBZ4HP7D.js → chunk-J6ATJUEE.js} +4 -4
- package/dist/{chunk-Y5QXDVPP.cjs → chunk-JQSN7D7X.cjs} +7 -7
- package/dist/{chunk-Y5QXDVPP.cjs.map → chunk-JQSN7D7X.cjs.map} +1 -1
- package/dist/{chunk-5LIDR7HL.js → chunk-JRYS4VMV.js} +4 -79
- package/dist/{chunk-5LIDR7HL.js.map → chunk-JRYS4VMV.js.map} +1 -1
- package/dist/{chunk-KTBZJP5J.cjs → chunk-KAG3SX3R.cjs} +22 -20
- package/dist/chunk-KAG3SX3R.cjs.map +1 -0
- package/dist/{chunk-ON7663OW.js → chunk-L5FEAOGJ.js} +8 -354
- package/dist/chunk-L5FEAOGJ.js.map +1 -0
- package/dist/{chunk-LCMXGM2P.js → chunk-LUBIWC3N.js} +8 -8
- package/dist/{chunk-ZRCWXJDW.js → chunk-LZB2UZJY.js} +4 -4
- package/dist/{chunk-JWXEEZKD.js → chunk-MIOE7FYN.js} +3 -3
- package/dist/{chunk-K43T7N7O.js → chunk-NBM7ZB6T.js} +12 -12
- package/dist/{chunk-YZJL6WGP.js → chunk-NDIPDU36.js} +49 -34
- package/dist/chunk-NDIPDU36.js.map +1 -0
- package/dist/{chunk-3IXDZI3R.cjs → chunk-P7UT2YSC.cjs} +3 -3
- package/dist/{chunk-3IXDZI3R.cjs.map → chunk-P7UT2YSC.cjs.map} +1 -1
- package/dist/{chunk-JJUV7Z4L.cjs → chunk-QIVX7F3N.cjs} +27 -27
- package/dist/{chunk-JJUV7Z4L.cjs.map → chunk-QIVX7F3N.cjs.map} +1 -1
- package/dist/{chunk-WIP5JO2O.cjs → chunk-R46TW4LX.cjs} +9 -9
- package/dist/{chunk-WIP5JO2O.cjs.map → chunk-R46TW4LX.cjs.map} +1 -1
- package/dist/{chunk-2MMEPNSX.cjs → chunk-RAPPN6MN.cjs} +3 -3
- package/dist/{chunk-2MMEPNSX.cjs.map → chunk-RAPPN6MN.cjs.map} +1 -1
- package/dist/{chunk-XQ4II4BK.js → chunk-SOUGXQJE.js} +4 -4
- package/dist/{chunk-E523WX5V.cjs → chunk-TV6NXNKO.cjs} +5 -5
- package/dist/{chunk-E523WX5V.cjs.map → chunk-TV6NXNKO.cjs.map} +1 -1
- package/dist/{chunk-FKBM6U43.js → chunk-USIRWQJ3.js} +76 -1
- package/dist/{chunk-FKBM6U43.js.map → chunk-USIRWQJ3.js.map} +1 -1
- package/dist/{chunk-CCWI3622.cjs → chunk-VOZZQ6HQ.cjs} +4 -4
- package/dist/{chunk-CCWI3622.cjs.map → chunk-VOZZQ6HQ.cjs.map} +1 -1
- package/dist/{chunk-JVLLA3Z7.js → chunk-WYELOUP4.js} +6 -6
- package/dist/{chunk-F2KBCLUG.js → chunk-X5NN4NJM.js} +2 -2
- package/dist/{chunk-KT47FRJC.cjs → chunk-Y2ZRUCYH.cjs} +15 -15
- package/dist/{chunk-KT47FRJC.cjs.map → chunk-Y2ZRUCYH.cjs.map} +1 -1
- package/dist/{chunk-YXWGSDK4.cjs → chunk-ZI27ALYX.cjs} +5 -80
- package/dist/chunk-ZI27ALYX.cjs.map +1 -0
- package/dist/{chunk-BVQEU5JB.js → chunk-ZOMGXH7C.js} +2 -2
- package/dist/{chunk-UNI3POHU.cjs → chunk-ZYDNPUSH.cjs} +279 -625
- package/dist/chunk-ZYDNPUSH.cjs.map +1 -0
- package/dist/components/case-studies/index.cjs +14 -14
- package/dist/components/case-studies/index.js +8 -8
- package/dist/components/chat/index.cjs +5 -5
- package/dist/components/chat/index.js +4 -4
- package/dist/components/contact/index.cjs +9 -9
- package/dist/components/contact/index.js +8 -8
- package/dist/components/docs/index.cjs +12 -12
- package/dist/components/docs/index.js +11 -11
- package/dist/components/embeds/index.cjs +9 -9
- package/dist/components/embeds/index.js +8 -8
- package/dist/components/faq/index.cjs +10 -10
- package/dist/components/faq/index.js +9 -9
- package/dist/components/features/changelog-manager.d.ts +17 -1
- package/dist/components/features/changelog-manager.d.ts.map +1 -1
- package/dist/components/features/index.cjs +8 -8
- package/dist/components/features/index.js +7 -7
- package/dist/components/help-center-pages/index.cjs +31 -31
- package/dist/components/help-center-pages/index.js +22 -22
- package/dist/components/index.cjs +71 -69
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.js +26 -24
- package/dist/components/index.js.map +1 -1
- package/dist/components/meeting-scheduler/index.cjs +49 -49
- package/dist/components/meeting-scheduler/index.js +9 -9
- package/dist/components/navigation/index.cjs +11 -11
- package/dist/components/navigation/index.js +10 -10
- package/dist/components/onboarding-guides/index.cjs +12 -12
- package/dist/components/onboarding-guides/index.js +11 -11
- package/dist/components/related-content/index.cjs +6 -6
- package/dist/components/related-content/index.js +5 -5
- package/dist/components/tickets/index.cjs +13 -13
- package/dist/components/tickets/index.js +12 -12
- package/dist/components/ui/color-preset-select.d.ts +4 -5
- package/dist/components/ui/color-preset-select.d.ts.map +1 -1
- package/dist/components/ui/department-badge.d.ts +3 -3
- package/dist/components/ui/index.cjs +10 -8
- package/dist/components/ui/index.cjs.map +1 -1
- package/dist/components/ui/index.js +9 -7
- package/dist/components/ui/palette-badge.d.ts +8 -6
- package/dist/components/ui/palette-badge.d.ts.map +1 -1
- package/dist/components/ui/status-badge.d.ts +1 -1
- package/dist/components/ui/status-badge.d.ts.map +1 -1
- package/dist/hooks/index.cjs +5 -5
- package/dist/hooks/index.js +4 -4
- package/dist/index.cjs +18 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +46 -46
- package/dist/types/department.d.ts +1 -1
- package/dist/types/department.d.ts.map +1 -1
- package/dist/types/index.cjs.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/product-release.d.ts +5 -0
- package/dist/types/product-release.d.ts.map +1 -1
- package/dist/utils/color-presets.d.ts +24 -0
- package/dist/utils/color-presets.d.ts.map +1 -0
- package/dist/utils/index.cjs +24 -21
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +22 -19
- package/dist/utils/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/features/__tests__/changelog-manager-tags.test.tsx +57 -0
- package/src/components/features/changelog-manager.tsx +69 -5
- package/src/components/ui/.department-badge.md +2 -2
- package/src/components/ui/.palette-badge.md +2 -2
- package/src/components/ui/.status-badge.md +2 -2
- package/src/components/ui/__tests__/department-badge.test.tsx +21 -23
- package/src/components/ui/color-preset-select.tsx +5 -21
- package/src/components/ui/department-badge.tsx +3 -3
- package/src/components/ui/palette-badge.tsx +13 -8
- package/src/components/ui/status-badge.tsx +0 -5
- package/src/types/department.ts +1 -1
- package/src/types/product-release.ts +5 -0
- package/src/utils/.color-presets.md +2 -0
- package/src/utils/color-presets.ts +48 -0
- package/src/utils/index.ts +1 -2
- package/dist/chunk-6QLOSGE7.cjs.map +0 -1
- package/dist/chunk-EHAYNUOL.cjs.map +0 -1
- package/dist/chunk-KTBZJP5J.cjs.map +0 -1
- package/dist/chunk-ON7663OW.js.map +0 -1
- package/dist/chunk-OQHFHKUG.cjs.map +0 -1
- package/dist/chunk-QS2QCXBH.js.map +0 -1
- package/dist/chunk-TDKOW2C5.cjs.map +0 -1
- package/dist/chunk-UBX3ATG5.cjs.map +0 -1
- package/dist/chunk-UNI3POHU.cjs.map +0 -1
- package/dist/chunk-YXWGSDK4.cjs.map +0 -1
- package/dist/chunk-YZJL6WGP.js.map +0 -1
- package/dist/utils/badge-palette.d.ts +0 -18
- package/dist/utils/badge-palette.d.ts.map +0 -1
- package/src/utils/.badge-palette.md +0 -2
- package/src/utils/badge-palette.ts +0 -38
- /package/dist/{chunk-X3LC6R37.js.map → chunk-32P6KUZP.js.map} +0 -0
- /package/dist/{chunk-U4UNC3RP.js.map → chunk-5BUEB2WQ.js.map} +0 -0
- /package/dist/{chunk-6AFJQOT2.js.map → chunk-65IVNHBS.js.map} +0 -0
- /package/dist/{chunk-S6WBBSII.js.map → chunk-76HB456V.js.map} +0 -0
- /package/dist/{chunk-HLZKMYST.js.map → chunk-7ZDPJ6SW.js.map} +0 -0
- /package/dist/{chunk-MB4IEWLH.js.map → chunk-BS6ASI3D.js.map} +0 -0
- /package/dist/{chunk-LLSX5T7X.js.map → chunk-CIRD5P4U.js.map} +0 -0
- /package/dist/{chunk-YQCA4ZEJ.js.map → chunk-CMUNJZWN.js.map} +0 -0
- /package/dist/{chunk-WBZ4HP7D.js.map → chunk-J6ATJUEE.js.map} +0 -0
- /package/dist/{chunk-LCMXGM2P.js.map → chunk-LUBIWC3N.js.map} +0 -0
- /package/dist/{chunk-ZRCWXJDW.js.map → chunk-LZB2UZJY.js.map} +0 -0
- /package/dist/{chunk-JWXEEZKD.js.map → chunk-MIOE7FYN.js.map} +0 -0
- /package/dist/{chunk-K43T7N7O.js.map → chunk-NBM7ZB6T.js.map} +0 -0
- /package/dist/{chunk-XQ4II4BK.js.map → chunk-SOUGXQJE.js.map} +0 -0
- /package/dist/{chunk-JVLLA3Z7.js.map → chunk-WYELOUP4.js.map} +0 -0
- /package/dist/{chunk-F2KBCLUG.js.map → chunk-X5NN4NJM.js.map} +0 -0
- /package/dist/{chunk-BVQEU5JB.js.map → chunk-ZOMGXH7C.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-6QLOSGE7.cjs","../src/components/docs/doc-viewer.tsx","../src/components/persistent-filter-controls.tsx","../src/components/docs/doc-navigation-context.tsx","../src/components/docs/use-docs-resolve-link.ts","../src/components/docs/use-document-tree.ts","../src/components/docs/use-scroll-spy.ts","../src/components/docs/skeletons.tsx","../src/components/docs/docs-hub-page.tsx"],"names":["jsx","useCallback","readString","useRef","pathParts","currentPath","useState","useMemo","jsxs"],"mappings":"AAAA,6xBAAY;AACZ;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;A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A;AACR,EAAA;AACmB,EAAA;AACF,EAAA;AACJ,EAAA;AACD,EAAA;AACG,EAAA;AACZ,EAAA;AACgB;AAC8B,EAAA;AACrC,IAAA;AACL,IAAA;AACS,IAAA;AACP,IAAA;AACD,IAAA;AACR,EAAA;AAEwD,EAAA;AACjC,IAAA;AACJ,IAAA;AACQ,IAAA;AAC3B,EAAA;AAGEA,EAAAA;AAAC,IAAA;AAAA,IAAA;AACK,MAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AAAA,IAAA;AACF,EAAA;AAEJ;ARg4B6B;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-6QLOSGE7.cjs","sourcesContent":[null,"'use client';\n\nimport type React from 'react';\nimport { useMemo } from 'react';\nimport { useRouter } from '../../embed-shims/next-navigation';\nimport type { DocContent, DocNode, DocRenderHandlers, DocSourceId } from '../../types/doc-source';\nimport { findDocNodeByPath } from '../../utils/doc-tree-nav';\nimport { PageShell } from '../layout/article-detail-layout';\nimport { PageLayout } from '../layout/page-layout';\nimport { CategorySidebarSkeleton } from '../loading/page-layout-skeleton';\nimport { MultiLevelNavigation, MobileNavigationDropdown } from '../navigation/multi-level-navigation';\nimport { StickySectionNav } from '../navigation/sticky-section-nav';\nimport { PersistentSidebar, PersistentMobileDropdown } from '../persistent-filter-controls';\nimport { DocSearchBar, useDocSearch } from '../shared/doc-search';\nimport { useDocNavigation } from './doc-navigation-context';\nimport { useDocsResolveLink } from './use-docs-resolve-link';\nimport { useDocumentTree } from './use-document-tree';\nimport { useScrollSpy } from './use-scroll-spy';\n\n/** Color tokens for the doc-viewer chrome. Hub-side `DocViewer` callers share\n * this constant; no need to override per source — the palette is intentionally\n * uniform across knowledge-base + data-room (both use ODS dark tokens). */\nexport const DEFAULT_DOC_VIEWER_PALETTE = {\n background: 'bg-ods-bg',\n containerBackground: 'transparent',\n headerText: 'text-ods-text-primary',\n primaryText: 'text-ods-text-primary',\n secondaryText: 'text-ods-text-secondary',\n accent: 'var(--ods-accent)',\n border: 'border-ods-border',\n cardBackground: 'bg-ods-card',\n} as const;\n\nexport interface DocViewerProps {\n /**\n * Registry source id (`'openframe-docs'`, `'data-room-docs'`, …). Flowed through\n * `renderContent`'s handlers for `/api/docs/resolve-link` POSTs.\n */\n sourceId: DocSourceId;\n\n /**\n * Render the content body. The page shell owns this — it picks the markdown\n * renderer, dispatches PDF/Figma/Sheets/file branches, etc. No renderer\n * interface in between.\n */\n renderContent: (content: DocContent, handlers: DocRenderHandlers) => React.ReactNode;\n\n /**\n * Render the loading skeleton. Receives the selected node's `documentType`\n * (undefined while structure is still loading) so the caller can return a\n * markdown-shaped skeleton vs an embed-shaped skeleton.\n */\n renderSkeleton: (documentType: DocNode['documentType']) => React.ReactNode;\n\n /**\n * Chat-source identifier — passed in by the page shell from server-side\n * `currentPlatform()`. Lib has no platform context; the page shell is the\n * trusted boundary that wires this. NEVER pass user input here.\n */\n chatSource: string;\n\n /** Page title — rendered as the inline hero `<h1>` (same DOM\n * `<DevSectionView>`'s hero uses) so the doc-viewer chrome matches the\n * dev-section pages. ReactNode is intentionally not supported here —\n * every consumer renders the same typography. */\n title?: string;\n /** Optional icon rendered inline before the title text — same slot\n * `<DevSectionView>`'s hero uses (Map for Roadmap, Rocket for Releases,\n * etc.). Pass a pre-rendered React element styled with\n * `SECTION_HERO_ICON_CLASS` (`h-10 w-10 text-ods-accent`) for visual\n * parity with other lib pages. */\n titleIcon?: React.ReactNode;\n /** Subtitle (h6, secondary text) rendered beneath the title. */\n subtitle?: string;\n /** Render a yellow accent dot (`.`) after the title — same flag as\n * the hub's legacy `<AdminPageHeader accentDot>` so the docs-hub\n * surface keeps its existing accent styling after the migration. */\n accentDot?: boolean;\n /** Override the default ODS palette. Optional — most callers should omit. */\n colorPalette?: typeof DEFAULT_DOC_VIEWER_PALETTE;\n className?: string;\n /** Render the standalone `<PageShell>` (own `<main>` + bg + max-width). Default\n * true. Pass false when the host layout already provides the page container —\n * only the padding box renders, avoiding a nested `<main>`. */\n shell?: boolean;\n\n /** Initial doc path (URL `[...path]`). */\n docPath?: string;\n\n /** Sidebar header copy (`'DOCUMENTATION'`, `'DATA ROOM'`). */\n sidebarLabel?: string;\n\n /**\n * API endpoint for fetching the document tree structure. Defaults to the\n * dispatcher path `/api/docs/sources/${sourceId}/structure`. Override only\n * if hosting the viewer behind a different route.\n */\n structureEndpoint?: string;\n /** Same shape as `structureEndpoint`. Defaults to `/api/docs/sources/${sourceId}/content`. */\n contentEndpoint?: string;\n /** RAG-search endpoint that backs the in-source search bar (when `showAIChat`\n * is on). Defaults to `/api/docs/search`. Override for proxy-prefix embeds —\n * same injectability pattern as `structureEndpoint` / `contentEndpoint`. */\n searchEndpoint?: string;\n /** POST internal-link resolver. The viewer threads an async `onResolveLink`\n * into `renderContent`'s `handlers` that posts `{ link, currentPath, source }`\n * here. Defaults to `/api/docs/resolve-link`. Override for proxy-prefix embeds —\n * same injectability pattern as `structureEndpoint` / `contentEndpoint` /\n * `searchEndpoint`, with `ChatRuntime.endpoints.docsResolveLinkUrl` as a\n * runtime fallback (prop → runtime → default). */\n resolveLinkEndpoint?: string;\n /** Base route path for URL navigation. */\n baseRoute: string;\n\n /** Empty state copy when no doc is selected. */\n emptyStateText?: string;\n\n /** Whether to render the doc-search bar (bound to chat). */\n showAIChat?: boolean;\n\n /** Folder-index filename (default `'README.md'`). */\n folderIndexFile?: string;\n\n /** Back-button shown above the title. Mirrors `<DevSectionPage>` /\n * `<HelpCenterList>` / `<LegalDocumentPage>` so every embeddable surface\n * shares the same chrome. Defaults to `{ label: 'Back to home', href: '/' }`.\n * Pass `false` to hide; pass `{ href: '/docs' }` etc. when the embed's\n * home isn't `/`. */\n backButton?: { label?: string; href?: string } | false;\n}\n\nexport function DocViewer(props: DocViewerProps) {\n return <DocViewerContent {...props} />;\n}\n\nfunction DocViewerContent({\n sourceId,\n renderContent,\n renderSkeleton,\n chatSource,\n title,\n subtitle,\n colorPalette = DEFAULT_DOC_VIEWER_PALETTE,\n className = '',\n shell = true,\n docPath,\n sidebarLabel = 'DOCUMENTATION',\n structureEndpoint,\n contentEndpoint,\n searchEndpoint,\n resolveLinkEndpoint,\n baseRoute,\n emptyStateText,\n showAIChat = false,\n folderIndexFile,\n backButton,\n}: DocViewerProps) {\n // Default endpoints derived from sourceId. Hub callers omit the props in 99%\n // of cases; the override is for embed contexts where the doc-viewer sits\n // behind a non-standard route.\n const resolvedStructureEndpoint = structureEndpoint ?? `/api/docs/sources/${sourceId}/structure`;\n const resolvedContentEndpoint = contentEndpoint ?? `/api/docs/sources/${sourceId}/content`;\n // Resolve-link endpoint chain (prop → ChatRuntime.endpoints → hub default)\n // + the full fetch + JSON-parse pipeline live in `useDocsResolveLink`.\n // Keeping it factored out as a proper hook makes the contract reusable\n // by any embedder rendering doc content outside `<DocViewer>` (custom\n // markdown renderers, link-resolver previews, etc.) and keeps this\n // component focused on layout + state.\n const resolveLink = useDocsResolveLink(sourceId, resolveLinkEndpoint);\n const {\n structure,\n selectedPath,\n content,\n isLoadingStructure,\n isLoadingContent,\n error,\n expandedNodes,\n selectNode,\n toggleNode,\n navigateToDoc,\n } = useDocumentTree(\n {\n structureEndpoint: resolvedStructureEndpoint,\n contentEndpoint: resolvedContentEndpoint,\n baseRoute,\n folderIndexFile,\n },\n docPath,\n );\n\n const { activeSection, handleSectionClick } = useScrollSpy(content?.sections);\n\n const docNav = useDocNavigation();\n\n // Back-button config — mirrors `<DevSectionPage>` so the docs surface\n // matches every other embeddable page's chrome. Default target is `/`\n // (the embed's home); pass `backButton: false` to hide entirely, or\n // override the href when the embed's home isn't `/`.\n const router = useRouter();\n const backCfg =\n backButton === false\n ? null\n : {\n label: backButton?.label ?? 'Back to home',\n onClick: () => router.push(backButton?.href ?? '/'),\n };\n const docSearch = useDocSearch({\n source: chatSource,\n baseRoute,\n searchEndpoint,\n onNavigate: path => navigateToDoc(path, { fromInternalLink: true }),\n onInPageSwap: path => docNav.navigate(path),\n });\n\n const renderedContent = useMemo(() => {\n if (!content) return null;\n return renderContent(content, {\n onInternalLinkClick: navigateToDoc,\n // Relative-link base = the RENDERED document's path, NOT `selectedPath`.\n // They diverge for a no-README folder: selection stays on the folder\n // (e.g. `repo/diagrams`) while the body is its first descendant doc\n // (e.g. `repo/diagrams/architecture/README.md`, via `findFirstDocPath`).\n // Resolving `./sibling.mmd` against the folder would 404; resolving it\n // against `content.path` lands in the descendant's directory. The DAL\n // sets `content.path` to the served doc in all cases (file / README\n // folder / first-child fallback), so this is correct everywhere.\n currentPath: content.path,\n sourceId,\n onResolveLink: resolveLink,\n });\n }, [content, renderContent, navigateToDoc, sourceId, resolveLink]);\n\n // Selected node's documentType drives:\n // - which skeleton the caller renders during fetch (markdown vs embed)\n // - the article max-width + sticky-nav visibility (markdown only)\n // `undefined` documentType is treated as `'markdown'` (per the DocNode\n // discriminator's documented default).\n const selectedNodeDocType =\n selectedPath && structure.length > 0 ? findDocNodeByPath(selectedPath, structure)?.documentType : undefined;\n // During loading, the in-flight content's type isn't known yet — fall back\n // to the selected node's type (or markdown if neither is set).\n const activeDocType = content?.documentType ?? selectedNodeDocType;\n const isMarkdownContent = !activeDocType || activeDocType === 'markdown';\n const showStickyNav = isMarkdownContent;\n\n const stickyNavSections = content?.sections?.map(s => ({ id: s.id, label: s.title })) ?? [];\n\n const isColorValue =\n colorPalette.background.startsWith('#') ||\n colorPalette.background.startsWith('rgb') ||\n colorPalette.background.startsWith('var(');\n\n const bgStyle = isColorValue ? { backgroundColor: colorPalette.background } : {};\n const bgClass = !isColorValue ? colorPalette.background : '';\n const containerBgStyle =\n colorPalette.containerBackground !== 'transparent' ? { backgroundColor: colorPalette.containerBackground } : {};\n\n const defaultEmptyText =\n structure.length > 0\n ? 'Select a document from the sidebar to view'\n : 'No documents yet. Add content from the admin panel.';\n const resolvedEmptyText = emptyStateText || defaultEmptyText;\n\n // Unified header: title/subtitle route through the canonical (frozen)\n // `PageLayout` `TitleBlock` (text-h2) — same as every other help-center page —\n // so the docs hub shares one header. The `gap-10` column then holds the search\n // bar + content grid. `colorPalette` / `className` / `bgStyle` flow through the\n // shell's contentClassName + an inner style-passthrough wrapper.\n const inner = (\n <div style={{ ...bgStyle, ...containerBgStyle }}>\n <PageLayout title={title} subtitle={subtitle} titleSize=\"h1\" titleWrap backButton={backCfg ?? undefined}>\n <div className=\"flex w-full flex-col gap-10\">\n {showAIChat && (\n <DocSearchBar\n placeholder={`Search ${sidebarLabel?.toLowerCase() || 'documents'}...`}\n query={docSearch.query}\n onQueryChange={docSearch.setQuery}\n results={docSearch.results}\n isLoading={docSearch.isLoading}\n onResultSelect={docSearch.handleResultSelect}\n showDropdown={docSearch.keepDropdownOpen}\n />\n )}\n\n {error && (\n <div className=\"flex justify-center\">\n <div className=\"max-w-md rounded-lg border border-ods-border bg-ods-card p-8 text-center\">\n <h2 className=\"text-ods-text-primary text-h3\">Error Loading Documents</h2>\n <p className=\"mt-2 text-ods-text-secondary\">{error}. Please try again later.</p>\n </div>\n </div>\n )}\n\n {!error && (\n <div className=\"flex flex-1 flex-col items-start gap-6 lg:flex-row lg:gap-10\">\n <div className=\"w-full lg:w-[320px] lg:shrink-0\">\n <div className=\"lg:sticky lg:top-20\">\n {isLoadingStructure ? (\n <CategorySidebarSkeleton />\n ) : (\n <>\n <PersistentMobileDropdown isLoading={false}>\n <MobileNavigationDropdown\n nodes={structure}\n selectedPath={selectedPath}\n expandedNodes={expandedNodes}\n onNodeClick={selectNode}\n onToggleExpand={toggleNode}\n isLoading={false}\n folderIndexFile={folderIndexFile}\n />\n </PersistentMobileDropdown>\n\n <PersistentSidebar isLoading={false}>\n <div className=\"hidden lg:block\">\n <div className=\"space-y-4\">\n <h3 className=\"font-semibold text-ods-text-secondary text-h5\">{sidebarLabel}</h3>\n <MultiLevelNavigation\n nodes={structure}\n selectedPath={selectedPath}\n expandedNodes={expandedNodes}\n onNodeClick={selectNode}\n onToggleExpand={toggleNode}\n isLoading={false}\n folderIndexFile={folderIndexFile}\n />\n </div>\n </div>\n </PersistentSidebar>\n </>\n )}\n </div>\n </div>\n\n <div className=\"w-full min-w-0 flex-1\">\n <div\n className={`grid grid-cols-1 ${\n // \"On this page\" right column only makes sense for\n // MARKDOWN content (PDFs / Sheets / Figma / file have no\n // sections to navigate to). Gating the grid template on\n // `isMarkdownContent` also suppresses the section-skeleton\n // bars during embed loads — the user-reported \"skeleton\n // shouldn't be on file pages\" bug.\n isMarkdownContent &&\n ((showStickyNav && stickyNavSections.length > 0) || isLoadingContent || isLoadingStructure)\n ? 'lg:grid-cols-[1fr_280px]'\n : ''\n } gap-8`}\n >\n {/* min-w-0: grid items default to min-width:auto, which would\n let a long unbreakable token push this column past the\n track width. Pair with the inherited overflow-wrap:anywhere\n (app-globals.css) so content wraps instead of overflowing. */}\n <div className={`w-full min-w-0 ${isMarkdownContent ? 'mx-auto max-w-4xl' : ''}`}>\n <article className=\"space-y-2\">\n {isLoadingContent || isLoadingStructure ? (\n renderSkeleton(selectedNodeDocType)\n ) : !content ? (\n <div className=\"py-16 text-center\">\n <p className=\"text-ods-text-secondary text-h4\">{resolvedEmptyText}</p>\n </div>\n ) : (\n renderedContent\n )}\n </article>\n </div>\n\n {isMarkdownContent && (isLoadingContent || isLoadingStructure) && (\n <div className=\"hidden lg:block\">\n <div className=\"sticky top-24\">\n <div className=\"mb-5 h-[14px] w-28 animate-pulse rounded bg-ods-border\" />\n <div className=\"space-y-0\">\n {[130, 170, 190, 220, 110, 200, 80, 100, 120, 140, 90].map((w, i) => (\n <div\n key={i}\n className={`border-l-2 py-[13px] pl-3 ${\n i === 0 ? 'border-ods-accent' : 'border-transparent'\n }`}\n >\n <div className=\"h-[13px] animate-pulse rounded bg-ods-border\" style={{ width: w }} />\n </div>\n ))}\n </div>\n </div>\n </div>\n )}\n\n {showStickyNav && content && stickyNavSections.length > 0 && !isLoadingContent && (\n <div className=\"hidden lg:block\">\n <div className=\"sticky top-24\">\n <h3 className=\"mb-4 font-semibold text-ods-text-secondary text-h5\">ON THIS PAGE</h3>\n <StickySectionNav\n sections={stickyNavSections}\n activeSection={activeSection}\n onSectionClick={handleSectionClick}\n ribbonPosition=\"left\"\n ribbonColor=\"var(--ods-accent)\"\n />\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )}\n </div>\n </PageLayout>\n </div>\n );\n\n // `shell` true → standalone `<PageShell>`; false → padding-only box (no nested\n // <main>) for hosts whose layout already provides the container. Both carry the\n // palette/className via the same `page-shell-content` styling hook.\n return shell ? (\n <PageShell contentClassName={`${bgClass} ${className}`}>{inner}</PageShell>\n ) : (\n <div className={`page-shell-content ${bgClass} ${className}`.trim()}>{inner}</div>\n );\n}\n","'use client';\n\nimport type { ReactNode } from 'react';\nimport { cn } from '../utils/cn';\n\ninterface PersistentFilterControlsProps {\n /**\n * Whether the filters are currently in a loading state\n */\n isLoading: boolean;\n /**\n * The filter control components (search, sidebar, mobile dropdown)\n */\n children: ReactNode;\n /**\n * Additional CSS classes\n */\n className?: string;\n /**\n * Disabled opacity (0-1)\n */\n disabledOpacity?: number;\n /**\n * Transition duration in milliseconds\n */\n transitionDuration?: number;\n /**\n * Whether to prevent pointer events during loading\n */\n preventInteraction?: boolean;\n}\n\n/**\n * PersistentFilterControls\n *\n * A wrapper component that keeps filter controls visible during loading states\n * but provides visual feedback that they are temporarily disabled.\n *\n * Features:\n * - Reduces opacity and disables pointer events during loading\n * - Maintains layout and accessibility during loading states\n * - Provides smooth transitions between enabled/disabled states\n * - Preserves keyboard navigation and screen reader functionality\n * - Applies consistent disabled styling across all filter types\n *\n * Usage:\n * ```tsx\n * <PersistentFilterControls isLoading={isLoadingVendors}>\n * <SearchContainer />\n * <CategoryFilterSidebar />\n * <MobileDropdown />\n * </PersistentFilterControls>\n * ```\n */\nexport function PersistentFilterControls({\n isLoading,\n children,\n className,\n disabledOpacity = 0.6,\n transitionDuration = 300,\n preventInteraction = true,\n}: PersistentFilterControlsProps) {\n return (\n <div\n className={cn(\n 'relative transition-all ease-in-out',\n isLoading && preventInteraction && 'pointer-events-none',\n className,\n )}\n style={{\n opacity: isLoading ? disabledOpacity : 1,\n transitionDuration: `${transitionDuration}ms`,\n }}\n role=\"region\"\n aria-label=\"Filter controls\"\n aria-busy={isLoading}\n data-loading={isLoading}\n >\n {/* Loading indicator overlay for screen readers */}\n {isLoading && (\n <div className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n Filters temporarily disabled while loading content\n </div>\n )}\n\n {/* Filter controls with disabled state styling */}\n <div\n className={cn('transition-all ease-in-out', isLoading && 'cursor-not-allowed')}\n style={{\n transitionDuration: `${transitionDuration}ms`,\n }}\n >\n {children}\n </div>\n\n {/* Visual loading indicator */}\n {isLoading && (\n <div className=\"absolute right-2 top-2 z-10\" role=\"status\" aria-label=\"Loading filters\">\n <div className=\"h-4 w-4 animate-spin rounded-full border-2 border-ods-border border-t-ods-accent\" />\n </div>\n )}\n </div>\n );\n}\n\n/**\n * Enhanced SearchContainer wrapper that integrates with persistent loading\n */\ninterface PersistentSearchContainerProps {\n isLoading: boolean;\n children: ReactNode;\n className?: string;\n}\n\nexport function PersistentSearchContainer({ isLoading, children, className }: PersistentSearchContainerProps) {\n return (\n <PersistentFilterControls\n isLoading={isLoading}\n preventInteraction={false} // Keep search interactive during loading\n className={className}\n >\n {children}\n </PersistentFilterControls>\n );\n}\n\n/**\n * Enhanced sidebar wrapper for desktop filter controls\n */\ninterface PersistentSidebarProps {\n isLoading: boolean;\n children: ReactNode;\n className?: string;\n}\n\nexport function PersistentSidebar({ isLoading, children, className }: PersistentSidebarProps) {\n return (\n <PersistentFilterControls\n isLoading={isLoading}\n disabledOpacity={0.5}\n className={cn('lg:sticky lg:top-20', className)}\n >\n {children}\n </PersistentFilterControls>\n );\n}\n\n/**\n * Enhanced mobile dropdown wrapper\n */\ninterface PersistentMobileDropdownProps {\n isLoading: boolean;\n children: ReactNode;\n className?: string;\n}\n\nexport function PersistentMobileDropdown({ isLoading, children, className }: PersistentMobileDropdownProps) {\n return (\n <PersistentFilterControls isLoading={isLoading} disabledOpacity={0.7} className={cn('lg:hidden', className)}>\n {children}\n </PersistentFilterControls>\n );\n}\n","'use client';\n\nimport React, { createContext, useCallback, useContext, useRef, type ReactNode } from 'react';\nimport type { DocNode } from '../../types/doc-source';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface DocNavigator {\n /** Base route this navigator owns (e.g., '/knowledge-base', '/data-room'). */\n baseRoute: string;\n /** Look up a node in the tree by its storage path (e.g., 'openframe-cli/README.md'). */\n findNodeByPath: (path: string) => DocNode | null;\n /** Navigate to a node using the same flow as a sidebar menu click. */\n selectNode: (node: DocNode) => void;\n}\n\ninterface DocNavigationContextValue {\n /**\n * Register a navigator for a `baseRoute`. Returns a cleanup function that\n * removes the navigator from the map IF the slot still owns it (StrictMode-safe).\n * Duplicate registration for the same baseRoute logs a console.warn and replaces.\n */\n register: (nav: DocNavigator) => () => void;\n /**\n * Navigate to a path inside whichever registered navigator owns its baseRoute prefix.\n * Returns true if handled, false otherwise (caller falls back to opening in a new tab).\n */\n navigate: (path: string) => boolean;\n /** Whether ANY navigator is currently mounted. */\n isAvailable: () => boolean;\n}\n\n// =============================================================================\n// Context\n// =============================================================================\n\nconst DocNavigationContext = createContext<DocNavigationContextValue | null>(null);\n\n/**\n * Bridges `useDocumentTree` instances (deep in the page tree) to `GlobalAskAI`\n * (high up near the root) without global events or URL parsing.\n *\n * Multi-navigator design: a `Map<baseRoute, DocNavigator>` lets multiple\n * viewers coexist (nested viewers, dual-pane scenarios). Today only one\n * viewer mounts at a time, so behavior is unchanged.\n */\nexport function DocNavigationProvider({ children }: { children: ReactNode }) {\n const navMap = useRef<Map<string, DocNavigator>>(new Map());\n\n const register = useCallback((nav: DocNavigator) => {\n const existing = navMap.current.get(nav.baseRoute);\n if (existing && existing !== nav) {\n console.warn(`[DocNavigationContext] duplicate registration for ${nav.baseRoute}; replacing`);\n }\n navMap.current.set(nav.baseRoute, nav);\n return () => {\n // StrictMode-safe identity check: only delete if THIS nav still owns the slot.\n if (navMap.current.get(nav.baseRoute) === nav) {\n navMap.current.delete(nav.baseRoute);\n }\n };\n }, []);\n\n const findOwningNavigator = useCallback((path: string): DocNavigator | null => {\n // First try: a navigator whose baseRoute is a prefix of `path`. Walks the\n // longest match first so nested routes win over a parent.\n const baseRoutes = Array.from(navMap.current.keys()).sort((a, b) => b.length - a.length);\n for (const baseRoute of baseRoutes) {\n if (path === baseRoute || path.startsWith(`${baseRoute}/`)) {\n return navMap.current.get(baseRoute) ?? null;\n }\n }\n // Fallback: a single navigator handles any path (existing behavior — chat\n // chips emit storage paths, not absolute URLs, so prefix matching misses).\n if (navMap.current.size === 1) {\n return navMap.current.values().next().value ?? null;\n }\n return null;\n }, []);\n\n const navigate = useCallback(\n (path: string): boolean => {\n const nav = findOwningNavigator(path);\n if (!nav) return false;\n const node = nav.findNodeByPath(path);\n if (!node) return false;\n nav.selectNode(node);\n return true;\n },\n [findOwningNavigator],\n );\n\n const isAvailable = useCallback(() => navMap.current.size > 0, []);\n\n const value = React.useMemo(() => ({ register, navigate, isAvailable }), [register, navigate, isAvailable]);\n\n return <DocNavigationContext.Provider value={value}>{children}</DocNavigationContext.Provider>;\n}\n\n// =============================================================================\n// Hooks\n// =============================================================================\n\nexport function useDocNavigation(): DocNavigationContextValue {\n const ctx = useContext(DocNavigationContext);\n if (!ctx) {\n // Safe no-op fallback when used outside the provider.\n return {\n register: () => () => {},\n navigate: () => false,\n isAvailable: () => false,\n };\n }\n return ctx;\n}\n","import { useCallback } from 'react';\nimport { useChatRuntime } from '../../contexts/chat-runtime-context';\nimport type { ResolveLinkResult } from '../../types/doc-source';\nimport { contentFetch } from '../../utils/embed-content-fetch';\n\n/**\n * `useDocsResolveLink(sourceId, override?)` — POST `/api/docs/resolve-link`\n * (or the override / `ChatRuntime.endpoints.docsResolveLinkUrl`) for a\n * relative href inside a doc body, returning a `ResolveLinkResult`\n * envelope.\n *\n * The endpoint chain (`override ?? runtime.endpoints.docsResolveLinkUrl\n * ?? '/api/docs/resolve-link'`) mirrors `searchEndpoint` resolution in\n * `<DocViewer>` so embedders configure both the same way: per-instance\n * prop OR ambient `ChatRuntimeProvider`.\n *\n * The full fetch + JSON-parse pipeline is wrapped in try/catch so a\n * network throw (DNS / CORS / offline) or a non-JSON response surfaces\n * as `{ success: false, error }` — the markdown renderer's broken-link\n * badge handles that branch instead of swallowing an unhandled rejection\n * past the click handler.\n */\n/**\n * Narrow the endpoint's answer to a `ResolveLinkResult`.\n *\n * `Response.json()` hands back `any`, and the route answers either the bare\n * result or a `{ data: … }` envelope — so the shape is checked instead of\n * trusted: a non-object body, or a field of the wrong primitive type, degrades\n * to `{ success: false }`, which is the \"leave the link alone\" branch the\n * markdown renderer already handles.\n *\n * Mirrors `toResolveLinkResult` in `ui/markdown/rich/rich-markdown-renderer`,\n * which narrows the same wire shape for the renderer's own fetch (that copy\n * cannot be imported here — it would pull the whole rich renderer chunk into\n * this hook).\n */\nfunction toResolveLinkResult(body: unknown): ResolveLinkResult {\n if (typeof body !== 'object' || body === null) {\n return { success: false };\n }\n const envelope: Record<string, unknown> = { ...body };\n const inner = envelope.data;\n const fields: Record<string, unknown> = typeof inner === 'object' && inner !== null ? { ...inner } : envelope;\n const readString = (key: string): string | undefined => (typeof fields[key] === 'string' ? fields[key] : undefined);\n\n return {\n success: fields.success === true,\n resolvedPath: readString('resolvedPath'),\n type: readString('type'),\n action: readString('action'),\n error: readString('error'),\n message: readString('message'),\n };\n}\n\nexport function useDocsResolveLink(sourceId: string, resolveLinkEndpoint?: string | null) {\n const chatRuntime = useChatRuntime();\n const resolvedResolveLinkEndpoint =\n resolveLinkEndpoint ?? chatRuntime?.endpoints.docsResolveLinkUrl ?? '/api/docs/resolve-link';\n\n return useCallback(\n async (href: string, currentPath: string): Promise<ResolveLinkResult> => {\n try {\n const response = await contentFetch(resolvedResolveLinkEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ link: href, currentPath, source: sourceId }),\n });\n if (!response.ok) {\n return { success: false, error: `Resolve failed: ${response.status}` };\n }\n const json: unknown = await response.json();\n return toResolveLinkResult(json);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Resolve failed',\n };\n }\n },\n [resolvedResolveLinkEndpoint, sourceId],\n );\n}\n","'use client';\n\nimport { useState, useEffect, useCallback, useMemo, useRef } from 'react';\nimport type { DocNode, DocContent, DocumentType } from '../../types/doc-source';\nimport { apiErrorMessage } from '../../utils/common';\nimport {\n stripFolderIndexFromPath,\n findDocNodeByPath,\n getDocAncestorNodeIds,\n DEFAULT_FOLDER_INDEX_FILE,\n} from '../../utils/doc-tree-nav';\nimport { contentFetch } from '../../utils/embed-content-fetch';\nimport { navigateSamePageHash, HUB_HEADER_OFFSET_PX } from '../../utils/same-page-hash-nav';\nimport { scrollElementIntoView } from '../../utils/scroll-into-view';\nimport { useDocNavigation } from './doc-navigation-context';\n\nfunction scrollToContent() {\n const article = document.querySelector('article');\n if (article) {\n scrollElementIntoView(article, { headerOffset: HUB_HEADER_OFFSET_PX });\n } else {\n // Same anchoring-proof tween for the no-article fallback — native smooth\n // scrollTo is cancelled by scroll anchoring while the new doc renders in.\n scrollElementIntoView(document.documentElement);\n }\n}\n\n/**\n * First displayable document inside a folder (depth-first): a direct non-Mermaid\n * file, else the first doc found in a subfolder. Used so a folder WITHOUT a\n * README shows its first child's content (mirroring how a README folder shows\n * its README) instead of a blank panel or a redundant in-page listing — the\n * sidebar tree is the directory browser. Returns null for a folder with no docs.\n */\nfunction findFirstDocPath(folder: DocNode): string | null {\n const children = folder.children ?? [];\n for (const child of children) {\n if (child.type === 'file' && !child.path.toLowerCase().endsWith('.mmd')) {\n return child.path;\n }\n }\n for (const child of children) {\n if (child.type === 'folder') {\n const nested = findFirstDocPath(child);\n if (nested) return nested;\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Wire decoding for the two doc-source endpoints\n//\n// `Response.json()` is typed `any`, so every field of both envelopes used to be\n// read off an `any` and the whole tree walk below inherited it. Both endpoints\n// are untrusted input — an embedder's reverse proxy answers them — so the shape\n// is validated once here instead of being trusted at ~30 read sites.\n//\n// Mirrors the narrowing `toResolveLinkResult` does for the resolve-link\n// envelope in `use-docs-resolve-link.ts`; that decoder covers a different\n// endpoint and is not reusable here.\n// ---------------------------------------------------------------------------\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** `Array.isArray` narrows `unknown` to `any[]`; this keeps the elements `unknown`. */\nfunction isUnknownArray(value: unknown): value is readonly unknown[] {\n return Array.isArray(value);\n}\n\nfunction readString(source: Record<string, unknown>, key: string): string | undefined {\n const value = source[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction isDocumentType(value: unknown): value is DocumentType {\n return value === 'markdown' || value === 'pdf' || value === 'google_sheet' || value === 'figma' || value === 'file';\n}\n\n/**\n * One tree node, or null when the row cannot be rendered.\n *\n * `id`, `name`, `path` and `type` are load-bearing: the sidebar calls\n * `node.name.endsWith('.md')` and every nav helper keys off `id`/`path`, so a\n * row missing one of them throws while rendering the tree rather than merely\n * looking wrong. Dropping the row keeps the rest of the tree browsable.\n *\n * `slug` is declared on `DocNode` but read nowhere in the lib, and the shared\n * `TreeNodeBase` producer contract does not carry it — so it is derived from\n * the path (the derivation the doc-source DALs use) when the payload omits it.\n */\nfunction toDocNode(value: unknown): DocNode | null {\n if (!isRecord(value)) return null;\n\n const id = readString(value, 'id');\n const name = readString(value, 'name');\n const path = readString(value, 'path');\n const type = value.type;\n if (id === undefined || name === undefined || path === undefined) return null;\n if (type !== 'file' && type !== 'folder') return null;\n\n const sortOrder = value.sortOrder;\n const hasReadme = value.hasReadme;\n\n return {\n id,\n name,\n slug: readString(value, 'slug') ?? path.split('/').pop() ?? '',\n path,\n type,\n hasReadme: typeof hasReadme === 'boolean' ? hasReadme : undefined,\n sortOrder: typeof sortOrder === 'number' ? sortOrder : undefined,\n documentType: isDocumentType(value.documentType) ? value.documentType : undefined,\n children: toDocNodes(value.children) ?? undefined,\n };\n}\n\n/** The tree, or null when the payload is not an array at all (a failed load). */\nfunction toDocNodes(value: unknown): DocNode[] | null {\n if (!isUnknownArray(value)) return null;\n const nodes: DocNode[] = [];\n for (const entry of value) {\n const node = toDocNode(entry);\n if (node) nodes.push(node);\n }\n return nodes;\n}\n\nfunction toDocSections(value: unknown): DocContent['sections'] {\n if (!isUnknownArray(value)) return [];\n const sections: DocContent['sections'] = [];\n for (const entry of value) {\n if (!isRecord(entry)) continue;\n const id = readString(entry, 'id');\n const title = readString(entry, 'title');\n const level = entry.level;\n if (id === undefined || title === undefined || typeof level !== 'number') continue;\n sections.push({ id, title, level });\n }\n return sections;\n}\n\nfunction toStringArray(value: unknown): string[] | undefined {\n if (!isUnknownArray(value)) return undefined;\n return value.filter((entry): entry is string => typeof entry === 'string');\n}\n\n/**\n * One document body, or null when the payload is not an object.\n *\n * `content` is declared required but is empty by nature for the rich document\n * types — a `pdf` / `google_sheet` / `figma` doc renders purely from `fileUrl`\n * / `externalUrl` (see `docs-hub-page.tsx`) — so a missing `content` is\n * normalized to `''` rather than treated as a failed load.\n *\n * `sections` and `path` are also declared required, and both leak when absent:\n * `path` feeds `DocRenderHandlers.currentPath`, which is what every relative\n * link inside the body is resolved against. `requestedPath` is the path this\n * fetch asked for, which is the correct value whenever the server omits it.\n */\nfunction toDocContent(value: unknown, requestedPath: string): DocContent | null {\n if (!isRecord(value)) return null;\n\n const fileSize = value.fileSize;\n\n return {\n content: readString(value, 'content') ?? '',\n sections: toDocSections(value.sections),\n path: readString(value, 'path') ?? requestedPath,\n documentType: isDocumentType(value.documentType) ? value.documentType : undefined,\n brokenLinks: toStringArray(value.brokenLinks),\n fileUrl: readString(value, 'fileUrl'),\n externalUrl: readString(value, 'externalUrl'),\n mimeType: readString(value, 'mimeType'),\n fileName: readString(value, 'fileName'),\n fileSize: typeof fileSize === 'number' ? fileSize : undefined,\n publishedAt: readString(value, 'publishedAt'),\n updatedAt: readString(value, 'updatedAt'),\n };\n}\n\nexport interface UseDocumentTreeConfig {\n /** API endpoint for fetching the document tree structure */\n structureEndpoint: string;\n /** API endpoint for fetching document content */\n contentEndpoint: string;\n /** Base route path for URL navigation (e.g., '/knowledge-base', '/data-room') */\n baseRoute: string;\n /** Folder-index filename (defaults to 'README.md'). */\n folderIndexFile?: string;\n}\n\n/**\n * Generic hook for document tree navigation and content fetching.\n * Drives DocViewer across all doc-source consumers.\n *\n * Client-only: structure + content fetches run in parallel on first mount.\n * No SSR pre-population — the previous SSR path required a Supabase admin\n * client (service role key) and silently fell back to client fetches on\n * envs where the key wasn't set; the parallel client fetches keep behavior\n * uniform across local + prod (latency ~= max(structure, content), not sum).\n */\nexport function useDocumentTree(config: UseDocumentTreeConfig, initialPath?: string) {\n const { structureEndpoint, contentEndpoint, baseRoute } = config;\n const folderIndexFile = config.folderIndexFile ?? DEFAULT_FOLDER_INDEX_FILE;\n\n const cleanInitialPath = stripFolderIndexFromPath(initialPath?.replace(/\\/$/, '') || '', folderIndexFile);\n\n const [structure, setStructure] = useState<DocNode[]>([]);\n const [selectedPath, setSelectedPath] = useState<string>(cleanInitialPath);\n const [content, setContent] = useState<DocContent | null>(null);\n const [isLoadingStructure, setIsLoadingStructure] = useState(true);\n const [isLoadingContent, setIsLoadingContent] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());\n const lastFetchedPath = useRef<string | null>(null);\n\n const normalizedBaseRoute = baseRoute.replace(/\\/$/, '');\n\n // Refreshed after every commit rather than in the render body: the reader is\n // a popstate listener, which cannot fire before a commit, and a discarded\n // render attempt must not leave a path behind that was never navigated to.\n const selectedPathRef = useRef(selectedPath);\n useEffect(() => {\n selectedPathRef.current = selectedPath;\n });\n\n const docNavigation = useDocNavigation();\n\n useEffect(() => {\n const handlePopState = () => {\n const pathname = window.location.pathname;\n let pathFromUrl = '';\n\n if (pathname === normalizedBaseRoute || pathname === `${normalizedBaseRoute}/`) {\n pathFromUrl = '';\n } else if (pathname.startsWith(`${normalizedBaseRoute}/`)) {\n pathFromUrl = pathname.substring(`${normalizedBaseRoute}/`.length);\n }\n\n pathFromUrl = stripFolderIndexFromPath(pathFromUrl, folderIndexFile);\n\n if (pathFromUrl !== selectedPathRef.current) {\n setSelectedPath(pathFromUrl);\n if (pathFromUrl) {\n const parentPath = pathFromUrl.includes('/')\n ? pathFromUrl.substring(0, pathFromUrl.lastIndexOf('/'))\n : pathFromUrl;\n setExpandedNodes(new Set(getDocAncestorNodeIds(parentPath)));\n }\n setTimeout(() => {\n scrollToContent();\n }, 150);\n }\n };\n\n window.addEventListener('popstate', handlePopState);\n return () => window.removeEventListener('popstate', handlePopState);\n }, [normalizedBaseRoute, folderIndexFile]);\n\n // External-URL → state sync. The popstate listener above catches browser\n // back/forward, but client-side routers (react-router, Next App Router…)\n // change the URL via `history.pushState` which does NOT fire popstate.\n // The host re-renders the viewer with a new `initialPath` prop instead, so\n // we mirror the popstate logic here against the (memoized) `cleanInitialPath`.\n // Without this, a chat-card click that soft-navigates via react-router\n // updates the URL but the viewer stays on the previously-selected doc.\n //\n // Adjusted while rendering — React's documented pattern for a prop-driven\n // sync — rather than from an effect: the viewer renders `selectedPath` and\n // `expandedNodes` in THIS render, so an effect painted a full frame of the\n // previous document (and the previous expanded branch) before swapping. The\n // guard compares against the `selectedPath` STATE rather than the popstate\n // listener's ref, both because a ref must not be read during render and\n // because at this point the two hold the same value.\n const [syncedInitialPath, setSyncedInitialPath] = useState(cleanInitialPath);\n const [externalNavCount, setExternalNavCount] = useState(0);\n if (syncedInitialPath !== cleanInitialPath) {\n setSyncedInitialPath(cleanInitialPath);\n if (cleanInitialPath !== selectedPath) {\n setSelectedPath(cleanInitialPath);\n if (cleanInitialPath) {\n const parentPath = cleanInitialPath.includes('/')\n ? cleanInitialPath.substring(0, cleanInitialPath.lastIndexOf('/'))\n : cleanInitialPath;\n setExpandedNodes(new Set(getDocAncestorNodeIds(parentPath)));\n }\n // Counter rather than a flag: it makes the scroll below fire once per\n // ACTUAL external navigation, which is exactly when the old effect\n // reached its `setTimeout` — a bare `cleanInitialPath` dep would also\n // fire for the host mirroring a sidebar click back into the URL.\n setExternalNavCount(n => n + 1);\n }\n }\n\n // Match popstate's scroll-to-content delay; the targeted content fetch\n // dispatched by the selectedPath effect lands before this fires.\n useEffect(() => {\n if (externalNavCount === 0) return undefined;\n const timer = setTimeout(scrollToContent, 150);\n return () => clearTimeout(timer);\n }, [externalNavCount]);\n\n const fetchStructure = async () => {\n try {\n setIsLoadingStructure(true);\n setError(null);\n\n const response = await contentFetch(structureEndpoint);\n\n if (!response.ok) {\n throw new Error('Failed to load documentation structure');\n }\n\n const payload: unknown = await response.json();\n // A non-array `data` used to be handed straight to `setStructure`, and\n // every later `findDocNodeByPath` then tried to iterate it — a hard\n // \"nodes is not iterable\" throw instead of the error banner below.\n const nodes = isRecord(payload) && payload.success ? toDocNodes(payload.data) : null;\n\n if (nodes) {\n setStructure(nodes);\n\n if (cleanInitialPath) {\n const pathForExpansion = cleanInitialPath.includes('.')\n ? cleanInitialPath.substring(0, cleanInitialPath.lastIndexOf('/'))\n : cleanInitialPath;\n if (pathForExpansion) {\n setExpandedNodes(new Set(getDocAncestorNodeIds(pathForExpansion)));\n }\n } else if (nodes.length > 0) {\n const hasRootReadme = nodes.some(node => node.type === 'file' && node.path === folderIndexFile);\n\n if (!hasRootReadme) {\n const firstNode = nodes[0];\n if (firstNode.type === 'folder') {\n setExpandedNodes(new Set([firstNode.id]));\n if (firstNode.hasReadme) {\n setSelectedPath(firstNode.path);\n window.history.replaceState({}, '', `${normalizedBaseRoute}/${firstNode.path}`);\n }\n }\n }\n }\n } else {\n setError(apiErrorMessage(payload, 'Failed to load documentation structure'));\n }\n } catch (err) {\n console.error('Error fetching documentation structure:', err);\n setError(err instanceof Error ? err.message : 'Failed to load documentation');\n } finally {\n setIsLoadingStructure(false);\n }\n };\n\n const fetchContent = async (path: string) => {\n try {\n setIsLoadingContent(true);\n // Don't clear `error` here — if a previous fetch set an error and this\n // is a stale/speculative call that gets superseded, the guard below\n // returns early without writing to state. Clearing error here would\n // briefly flicker the user-visible error message.\n\n const response = await contentFetch(`${contentEndpoint}?path=${encodeURIComponent(path)}`);\n\n // Request-id guard: between awaits, `lastFetchedPath.current` may have\n // been bumped by a newer fetch (the structure-arrives auto-select issues\n // a more-targeted fetch while the speculative one is in flight). Bail\n // BEFORE writing to state — otherwise the late 404 of the speculative\n // fetch overwrites the targeted fetch's good content with null.\n if (path !== lastFetchedPath.current) return;\n\n if (!response.ok) {\n if (response.status === 404) {\n const errorPayload: unknown = await response.json().catch(() => null);\n if (path !== lastFetchedPath.current) return;\n // Landing-page silent fallback: when the user lands on the source's\n // root URL and there's no root `README.md` (knowledge-base case),\n // the speculative fetch 404s — surface an empty state instead of\n // an error banner. The structure-arrives auto-select will fire\n // a targeted fetch for the first-folder README on the next render.\n if (path === folderIndexFile && selectedPath === '') {\n // Superseded by the auto-select fetch the structure effect fires.\n // Null the request id so the `finally` does NOT drop the spinner —\n // otherwise there's a 1-frame gap (isLoadingContent false, content\n // null) where the empty state flashes before the real fetch starts.\n lastFetchedPath.current = null;\n setError(null);\n setContent(null);\n return;\n }\n // No-README FOLDER → stay silent: the content effect resolves it to\n // the folder's first child, so the folder-path 404 from the direct-\n // load speculative fetch is expected, not an error to flash.\n const probe = findDocNodeByPath(stripFolderIndexFromPath(path, folderIndexFile), structure);\n const probeIsNoReadmeFolder = !!probe && probe.type === 'folder' && !probe.hasReadme;\n // Before the structure has loaded to classify the path (`structure`\n // is [] in the speculative call's closure), only silence FOLDER-LIKE\n // paths (no `.md`) — a genuinely missing `*.md` leaf must still error.\n const preStructureFolderLike = structure.length === 0 && !path.endsWith('.md');\n if (probeIsNoReadmeFolder || preStructureFolderLike) {\n // Superseded by the targeted fetch (first-child / reclassified path)\n // the structure effect fires. Null the request id so the `finally`\n // keeps the spinner up instead of flashing an empty state for a\n // frame before that fetch starts.\n lastFetchedPath.current = null;\n setError(null);\n setContent(null);\n return;\n }\n setError(apiErrorMessage(errorPayload, 'Documentation file not found'));\n setContent(null);\n return;\n }\n throw new Error('Failed to load documentation content');\n }\n\n const payload: unknown = await response.json();\n if (path !== lastFetchedPath.current) return;\n setError(null);\n\n const doc = isRecord(payload) && payload.success ? toDocContent(payload.data, path) : null;\n\n if (doc) {\n // `correctPath` is only honored when it is actually a string. The old\n // `!== undefined` check also admitted `null`, which `setSelectedPath`\n // then stored as the selection: the URL became `${baseRoute}/null` and\n // the content effect's `selectedPath === null` guard bailed on every\n // subsequent run, freezing the viewer on that document.\n const correctPath = isRecord(payload) && payload.redirect ? readString(payload, 'correctPath') : undefined;\n if (correctPath !== undefined) {\n setSelectedPath(correctPath);\n window.history.replaceState({}, '', `${normalizedBaseRoute}/${correctPath}`);\n }\n setContent(doc);\n } else {\n setError(apiErrorMessage(payload, 'Failed to load content'));\n setContent(null);\n }\n } catch (err) {\n if (path !== lastFetchedPath.current) return;\n console.error('Error fetching documentation content:', err);\n setError(err instanceof Error ? err.message : 'Failed to load content');\n setContent(null);\n } finally {\n // Only clear loading state if THIS fetch is still the active one — a\n // superseded speculative shouldn't flip the spinner off while the\n // targeted fetch is still in flight.\n if (path === lastFetchedPath.current) setIsLoadingContent(false);\n }\n };\n // `fetchStructure` / `fetchContent` are plain async functions rebuilt on\n // every render, so neither effect below can take them as dependencies: the\n // init effect would re-fire its speculative fetch and the path effect would\n // refetch the same document on every parent render. Read through a ref that\n // is refreshed after every commit, so both always call the current closures.\n const latestRef = useRef({ fetchContent, fetchStructure, cleanInitialPath, folderIndexFile });\n useEffect(() => {\n latestRef.current = { fetchContent, fetchStructure, cleanInitialPath, folderIndexFile };\n });\n\n // Mount-only. The `isInitialized` state this used to latch on was read\n // NOWHERE else: it was a run-once guard that cost a setState in an effect\n // body (and a second, no-op run of this effect) to say what empty deps say\n // directly.\n useEffect(() => {\n // Kick off the speculative content fetch IN PARALLEL with the structure\n // fetch — the two endpoints are independent and most landing pages have\n // a root README (the default folder-index). If the structure ends up\n // pointing at a different path (e.g. knowledge-base falls back to the\n // first-folder README because there's no root README), the content\n // useEffect issues the correct fetch after structure arrives — the\n // speculative result silently no-ops (the content state update gets\n // overwritten by the targeted fetch).\n const latest = latestRef.current;\n const speculativeContentPath = latest.cleanInitialPath || latest.folderIndexFile;\n lastFetchedPath.current = speculativeContentPath;\n // Both settle their own failures into `error` state via try/catch/finally,\n // so neither can reject; they are deliberately NOT awaited so the two\n // independent endpoints stay in parallel.\n void latest.fetchContent(speculativeContentPath);\n void latest.fetchStructure();\n }, []);\n\n useEffect(() => {\n if (selectedPath === null || selectedPath === undefined) return;\n if (!structure || structure.length === 0) return;\n\n let pathToFetch: string | null = null;\n\n if (selectedPath === '') {\n pathToFetch = folderIndexFile;\n } else {\n const node = findDocNodeByPath(selectedPath, structure);\n\n if (node && node.type === 'folder' && !node.hasReadme) {\n // No-README folder has no body of its own — show its FIRST child doc\n // (mirrors a README folder showing its README). selectedPath stays the\n // folder, so the sidebar keeps it highlighted/expanded; the sidebar is\n // the directory browser, so we render NO separate in-page listing.\n const firstDocPath = findFirstDocPath(node);\n if (!firstDocPath) {\n // Genuinely empty folder — nothing to fetch. The empty state itself\n // is DERIVED (see `isEmptyFolder` below); clearing content/error/\n // loading from here would be a second render pass to publish\n // something `structure` + `selectedPath` already say.\n lastFetchedPath.current = null;\n return;\n }\n pathToFetch = firstDocPath;\n } else if (node && node.type === 'folder' && node.hasReadme) {\n // `getContent(folder)` already resolves a README folder to its README,\n // so the initial speculative fetch (which uses the bare folder path)\n // ALREADY loaded this content. Re-fetching the `${folder}/README.md`\n // variant is a redundant 2nd request whose in-flight `isLoadingContent`\n // flashes the skeleton — content → skeleton → content — on first load.\n // Skip it when the folder path was already the (speculatively) fetched\n // path; the result (or its in-flight request) covers the README.\n if (lastFetchedPath.current === selectedPath) {\n return;\n }\n pathToFetch = `${selectedPath}/${folderIndexFile}`;\n } else {\n pathToFetch = selectedPath;\n }\n }\n\n if (pathToFetch === lastFetchedPath.current) {\n return;\n }\n\n if (pathToFetch) {\n lastFetchedPath.current = pathToFetch;\n // Never rejects — settles its own failures into `error` state.\n void latestRef.current.fetchContent(pathToFetch);\n }\n }, [selectedPath, structure, folderIndexFile]);\n\n const toggleNode = useCallback((nodeId: string) => {\n setExpandedNodes(prev => {\n const next = new Set(prev);\n if (next.has(nodeId)) {\n next.delete(nodeId);\n } else {\n next.add(nodeId);\n }\n return next;\n });\n }, []);\n\n // Structural minimum the body uses — `id`, `path`, `type`, `hasReadme`.\n // Widening from `DocNode` lets the navigation components (which carry the\n // narrower `NavigationNode` row shape) pass their own node back without the\n // cross-type `as` cast. Both DocNode and NavigationNode satisfy this.\n const selectNode = useCallback(\n (node: Pick<DocNode, 'id' | 'path' | 'type' | 'hasReadme'>) => {\n // Expansion only: clicking a folder toggles its own subtree; clicking a file\n // reveals its ancestor chain.\n if (node.type === 'folder') {\n setExpandedNodes(prev => {\n if (prev.has(node.id)) {\n const ancestorIds = getDocAncestorNodeIds(node.path);\n ancestorIds.pop(); // collapse self, keep ancestors open\n return new Set(ancestorIds);\n }\n return new Set(getDocAncestorNodeIds(node.path));\n });\n } else {\n const lastSlash = node.path.lastIndexOf('/');\n if (lastSlash > 0) {\n setExpandedNodes(new Set(getDocAncestorNodeIds(node.path.substring(0, lastSlash))));\n }\n }\n\n // Every node is a navigable destination — a file shows its body, a README\n // folder its README, a no-README folder its first child doc (the content\n // effect resolves which). So selection + URL + scroll are identical for all\n // node types; no per-type special-casing.\n lastFetchedPath.current = null;\n setSelectedPath(node.path);\n window.history.pushState({}, '', `${normalizedBaseRoute}/${node.path}`);\n setTimeout(scrollToContent, 150);\n },\n [normalizedBaseRoute],\n );\n\n const navigateToDoc = useCallback(\n (path: string, options?: { expandFolder?: boolean; fromInternalLink?: boolean }) => {\n const hashIndex = path.indexOf('#');\n const anchor = hashIndex !== -1 ? path.substring(hashIndex) : '';\n const cleanPath = path.replace(/\\/$/, '').split('#')[0];\n\n // Same-doc-different-anchor shortcut. Content is already mounted, so we\n // don't need the 300ms \"wait-for-fetch\" bandaid — the canonical helper\n // owns pushState + synthetic `hashchange` (so any in-doc TOC / accordion\n // bound to the URL hash re-renders) + the anchoring-proof tween in one\n // sync call. `headerOffset: HUB_HEADER_OFFSET_PX` matches the cross-doc path below so\n // anchors land BELOW the docs sticky header on every same-doc internal\n // link click. Cross-doc nav (different cleanPath) falls through to the\n // existing fetch-then-scroll path below.\n //\n // We pass the BARE-hash form to the helper rather than reconstructing\n // a full `${normalizedBaseRoute}/${cleanPath}${anchor}` path: the\n // helper's pathname check compares against `window.location.pathname`,\n // which carries the FOLDER-INDEX-STRIPPED form (`/docs/foo` for\n // `foo/README.md`, `/docs` for the root index). Handing it `cleanPath`\n // — the raw resolved path — produces e.g. `/docs/foo/README.md` and\n // the compare fails → helper returns false → silent dead-click. The\n // bare-hash form sidesteps that entirely: the helper reconstructs\n // `pathname + search + hash` from `window.location`, so the compare\n // is trivially equal. Covers bare `#anchor` links (resolve to\n // `cleanPath=''`) AND folder-index links (`foo/README.md` resolving\n // to the current `/docs/foo`).\n // Bare-hash internal links (`[Click](#section)`) come in as\n // `path === '#section'`, so `cleanPath` becomes `''` and the naive\n // strip-then-compare misses the same-doc shortcut on every NON-root\n // doc (selectedPath is e.g. `'foo/bar'`, not `''`). For that case the\n // current doc IS the same-doc target by definition — short-circuit\n // pathForSelection to the current selection so the shortcut fires.\n const pathForSelection =\n anchor && options?.fromInternalLink && cleanPath === ''\n ? selectedPathRef.current\n : stripFolderIndexFromPath(cleanPath, folderIndexFile);\n if (anchor && options?.fromInternalLink && pathForSelection === selectedPathRef.current) {\n navigateSamePageHash(anchor, { headerOffset: HUB_HEADER_OFFSET_PX });\n return;\n }\n\n const scrollAfterNav = () => {\n if (anchor) {\n setTimeout(() => {\n const el = document.getElementById(anchor.substring(1));\n if (el) {\n scrollElementIntoView(el, { headerOffset: HUB_HEADER_OFFSET_PX });\n } else {\n scrollToContent();\n }\n }, 300);\n } else {\n setTimeout(() => {\n scrollToContent();\n }, 150);\n }\n };\n\n if (options?.expandFolder) {\n lastFetchedPath.current = null;\n setSelectedPath(cleanPath);\n window.history.pushState({}, '', `${normalizedBaseRoute}/${cleanPath}${anchor}`);\n\n const pathParts = cleanPath.split('/');\n const nodeIdsToExpand: string[] = [];\n let currentPath = '';\n\n for (const part of pathParts) {\n currentPath = currentPath ? `${currentPath}-${part}` : part;\n nodeIdsToExpand.push(currentPath.toLowerCase());\n }\n\n setExpandedNodes(new Set(nodeIdsToExpand));\n\n if (options?.fromInternalLink) {\n scrollAfterNav();\n }\n\n setError(null);\n return;\n }\n\n // `pathForSelection` was already computed above (inside the\n // same-doc-anchor shortcut check); reuse it here for cross-doc nav.\n const urlPath = pathForSelection;\n\n lastFetchedPath.current = null;\n setSelectedPath(pathForSelection);\n window.history.pushState({}, '', `${normalizedBaseRoute}/${urlPath}${anchor}`);\n\n if (options?.fromInternalLink) {\n scrollAfterNav();\n }\n\n const pathParts = cleanPath.split('/');\n const parentIds: string[] = [];\n let currentPath = '';\n const partsToProcess = cleanPath.includes('.') ? pathParts.slice(0, -1) : pathParts;\n\n for (const part of partsToProcess) {\n currentPath = currentPath ? `${currentPath}-${part}` : part;\n parentIds.push(currentPath.toLowerCase());\n }\n\n if (parentIds.length > 0) {\n setExpandedNodes(new Set(parentIds));\n }\n },\n [normalizedBaseRoute, folderIndexFile],\n );\n\n useEffect(() => {\n return docNavigation.register({\n baseRoute: normalizedBaseRoute,\n findNodeByPath: path => {\n const clean = stripFolderIndexFromPath(path.replace(/\\/$/, '').split('#')[0], folderIndexFile);\n return findDocNodeByPath(clean, structure) ?? null;\n },\n selectNode,\n });\n }, [docNavigation, normalizedBaseRoute, structure, selectNode, folderIndexFile]);\n\n // A folder with no README and no documents anywhere under it has no body at\n // all, and that is a pure fact about `structure` + `selectedPath` — both\n // available while rendering. Derived here rather than written into state from\n // the content effect, which reached the same conclusion one commit later and\n // meanwhile left the PREVIOUS document's body on screen.\n const isEmptyFolder = useMemo(() => {\n if (!selectedPath || structure.length === 0) return false;\n const node = findDocNodeByPath(selectedPath, structure);\n return !!node && node.type === 'folder' && !node.hasReadme && !findFirstDocPath(node);\n }, [selectedPath, structure]);\n\n return {\n structure,\n selectedPath,\n setSelectedPath,\n content: isEmptyFolder ? null : content,\n isLoadingStructure,\n isLoadingContent: isEmptyFolder ? false : isLoadingContent,\n error: isEmptyFolder ? null : error,\n expandedNodes,\n toggleNode,\n selectNode,\n navigateToDoc,\n refetch: fetchStructure,\n setExpandedNodes,\n };\n}\n\nexport type { DocNode, DocContent };\n","'use client';\n\nimport { useState, useRef, useCallback, useEffect, useMemo } from 'react';\nimport { scrollElementIntoView } from '../../utils/scroll-into-view';\n\n// Single source for the sticky-chrome height. Used for BOTH the scroll target\n// offset (where a clicked section lands) AND the active-section detection\n// threshold (where the scroll listener flips highlight). They must match —\n// previously 100 vs 150 caused a 50px window where the indicator jumped to\n// the next section even though that section's top was still below the\n// clicked one's resting offset.\nconst SCROLL_OFFSET = 100;\n\n// Separator for the section-id key. A newline cannot occur inside an HTML id,\n// so the join is unambiguous and the key can be split back apart.\nconst ID_SEPARATOR = '\\n';\n\ninterface ScrollSpySection {\n id: string;\n title?: string;\n level?: number;\n}\n\ninterface UseScrollSpyReturn {\n activeSection: string;\n handleSectionClick: (sectionId: string) => void;\n}\n\n/**\n * Shared scroll spy hook for tracking active section based on scroll position.\n * Used by DocViewer for sticky section navigation.\n */\nexport function useScrollSpy(sections: ScrollSpySection[] | undefined): UseScrollSpyReturn {\n const [activeSection, setActiveSection] = useState('');\n const isScrollingFromClick = useRef(false);\n\n // The scroll listener only ever needs the section IDS, and callers rebuild\n // the `sections` array on every render — so the value-stable joined key IS\n // the input, and the effect unpacks it again. That replaces a ref written\n // during render whose only job was to keep the array's churning identity out\n // of the dependency array.\n const sectionIdsKey = useMemo(() => sections?.map(s => s.id).join(ID_SEPARATOR) ?? '', [sections]);\n\n const handleSectionClick = useCallback((sectionId: string) => {\n const targetElement = document.getElementById(sectionId);\n if (!targetElement) return;\n\n isScrollingFromClick.current = true;\n setActiveSection(sectionId);\n\n scrollElementIntoView(targetElement, { headerOffset: SCROLL_OFFSET });\n\n setTimeout(() => {\n isScrollingFromClick.current = false;\n }, 800);\n }, []);\n\n useEffect(() => {\n const sectionIds = sectionIdsKey === '' ? [] : sectionIdsKey.split(ID_SEPARATOR);\n if (sectionIds.length === 0) return undefined;\n\n const handleScroll = () => {\n if (isScrollingFromClick.current) return;\n\n const scrollPosition = window.scrollY + SCROLL_OFFSET;\n let currentSection = sectionIds[0] ?? '';\n\n for (let i = sectionIds.length - 1; i >= 0; i--) {\n const element = document.getElementById(sectionIds[i]);\n if (element && scrollPosition >= element.offsetTop) {\n currentSection = sectionIds[i];\n break;\n }\n }\n\n setActiveSection(prev => (prev !== currentSection ? currentSection : prev));\n };\n\n let scrollTimer: ReturnType<typeof setTimeout>;\n const throttledScroll = () => {\n clearTimeout(scrollTimer);\n scrollTimer = setTimeout(handleScroll, 100);\n };\n\n window.addEventListener('scroll', throttledScroll);\n handleScroll();\n\n return () => {\n window.removeEventListener('scroll', throttledScroll);\n clearTimeout(scrollTimer);\n };\n }, [sectionIdsKey]);\n\n return { activeSection, handleSectionClick };\n}\n","/**\n * Text-style skeleton — matches a rendered markdown article layout.\n * Used by `<DocsHubPage>` as the default for `markdown` (and unknown\n * document types). Embedders can override via `renderSkeleton`.\n */\nexport function MarkdownSkeleton() {\n return (\n <div className=\"mt-6 space-y-7\">\n <div className=\"space-y-[14px]\">\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-3/4 animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"space-y-[14px]\">\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-5/6 animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"space-y-[14px]\">\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-2/3 animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"h-[88px] animate-pulse rounded-lg border border-ods-border bg-ods-card\" />\n <div className=\"h-7 w-1/3 animate-pulse rounded bg-ods-border\" />\n <div className=\"space-y-[14px]\">\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-[72%] animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"space-y-[14px]\">\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-[58%] animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"h-7 w-2/5 animate-pulse rounded bg-ods-border\" />\n <div className=\"space-y-[14px]\">\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-[90%] animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"space-y-[14px]\">\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-full animate-pulse rounded bg-ods-border\" />\n <div className=\"h-[16px] w-[70%] animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"h-[88px] animate-pulse rounded-lg border border-ods-border bg-ods-card\" />\n </div>\n );\n}\n\n/**\n * Embed-style skeleton — matches the iframe loading state for `pdf`,\n * `google_sheet`, `figma`, and `file` document types. Used by\n * `<DocsHubPage>` as the default for non-markdown documentTypes.\n *\n * The skeleton is documentType-aware so its layout matches the actual\n * viewer that will replace it:\n * - `pdf` → header with title + TWO buttons (Preview, Download)\n * - `google_sheet`/`figma` → header with title + ONE button/toggle\n * - `file` → centered FileDownloadCard-style box\n * - undefined / others → generic (1-button header)\n *\n * IMPORTANT: bars use `bg-ods-border` (NOT `bg-ods-skeleton`). The\n * `--ods-skeleton` token resolves to TRANSPARENT in this build, leaving\n * the skeleton box visually empty — the embed skeleton was the loudest\n * surface affected (a full-height iframe area showing nothing). Same fix\n * the chat-message-row skeleton already documents in its inline comment.\n */\nexport interface EmbedSkeletonProps {\n /** When provided, the header layout matches the eventual viewer's\n * button count + arrangement, so the layout doesn't shift on load. */\n documentType?: 'pdf' | 'google_sheet' | 'figma' | 'file' | string;\n}\n\nexport function EmbedSkeleton({ documentType }: EmbedSkeletonProps = {}) {\n // Centered card shape for the `file` documentType — matches\n // `<FileDownloadCard>`'s `flex flex-col items-center justify-center py-16`\n // + bordered card with icon, name, type/size row, Download button.\n if (documentType === 'file') {\n return (\n <div className=\"flex flex-col items-center justify-center py-16\">\n <div className=\"w-full max-w-md space-y-4 rounded-xl border border-ods-border bg-ods-card p-8 text-center\">\n <div className=\"mx-auto h-16 w-16 animate-pulse rounded bg-ods-border\" />\n <div className=\"space-y-2\">\n <div className=\"mx-auto h-5 w-2/3 animate-pulse rounded bg-ods-border\" />\n <div className=\"mx-auto h-4 w-1/2 animate-pulse rounded bg-ods-border\" />\n </div>\n <div className=\"h-10 w-full animate-pulse rounded bg-ods-border\" />\n </div>\n </div>\n );\n }\n\n // PDF viewer has TWO buttons (Preview + Download); Sheets / Figma\n // render ONE (Open / view-toggle). Default to one for unknown types.\n const buttonCount = documentType === 'pdf' ? 2 : 1;\n\n return (\n <div className=\"space-y-4\">\n {/* Header — matches the actual viewer's\n * `flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between`\n * (mobile-stacked, desktop-row). */}\n <div className=\"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between\">\n {/* Left: icon + title */}\n <div className=\"flex min-w-0 flex-1 items-center gap-2\">\n <div className=\"h-5 w-5 shrink-0 animate-pulse rounded bg-ods-border\" />\n <div className=\"h-6 w-2/3 animate-pulse rounded bg-ods-border\" />\n </div>\n {/* Right: 1 or 2 buttons. Mobile = full-width; desktop = auto. */}\n <div className=\"flex w-full items-center gap-2 sm:w-auto\">\n {Array.from({ length: buttonCount }).map((_, i) => (\n <div key={i} className=\"h-10 w-full flex-1 animate-pulse rounded bg-ods-border sm:w-32 sm:flex-initial\" />\n ))}\n </div>\n </div>\n {/* Body — clean iframe-sized rectangle, no fake inner placeholder\n * cruft. Matches the viewer's default `calc(100vh - 250px)` height. */}\n <div\n className=\"w-full animate-pulse rounded-lg border border-ods-border bg-ods-card\"\n style={{ height: 'calc(100vh - 250px)' }}\n />\n </div>\n );\n}\n","import type React from 'react';\nimport type { DocContent, DocRenderHandlers, DocumentType } from '../../types/doc-source';\nimport { FigmaEmbed } from '../embeds/figma-embed';\nimport { FileDownloadCard } from '../embeds/file-download-card';\nimport { GoogleSheetsViewer } from '../embeds/google-sheets-viewer';\nimport { PdfViewer } from '../embeds/pdf-viewer';\nimport { DocViewer, type DocViewerProps } from './doc-viewer';\nimport { MarkdownSkeleton, EmbedSkeleton } from './skeletons';\n\ntype DocRenderer = (content: DocContent, handlers: DocRenderHandlers) => React.ReactNode;\n\n/**\n * Per-document-type renderer map. `markdown` is required (the lib does NOT\n * ship a default markdown renderer — embedders pick their own library +\n * sanitization to avoid an XSS surface in the lib).\n *\n * `pdf` / `google_sheet` / `figma` / `file` are optional — the lib provides\n * defaults from `components/embeds`. Override only when you want different\n * props than the default (e.g. a custom PDF toolbar, embedded credentials).\n */\nexport type DocumentTypeRenderers = { markdown: DocRenderer } & Partial<Record<DocumentType, DocRenderer>>;\n\nexport interface DocsHubPageProps extends Omit<DocViewerProps, 'renderContent' | 'renderSkeleton' | 'showAIChat'> {\n /** Per-document-type renderer map. `markdown` is REQUIRED. */\n documentTypeRenderers: DocumentTypeRenderers;\n\n /** Renderer for unknown / future document types. Defaults to a lib-styled\n * \"Unsupported document type\" message. */\n fallbackRenderer?: DocRenderer;\n\n /** Loading skeleton picker. Defaults: `markdown` / `undefined` →\n * `<MarkdownSkeleton>`, everything else → `<EmbedSkeleton>`. */\n renderSkeleton?: (documentType: DocumentType | undefined) => React.ReactNode;\n\n /** Defaults to `true` (the embeddable wrapper favors the chat-enabled\n * experience). Only mounts the in-source RAG search bar\n * (`<DocSearchBar>`) — does NOT require `ChatRuntimeContext`. */\n showAIChat?: boolean;\n}\n\nconst DEFAULT_TITLE = 'Documents';\n\nconst defaultFallbackRenderer: DocRenderer = () => (\n <div className=\"py-16 text-center\">\n <p className=\"text-ods-text-secondary\">Unsupported document type</p>\n </div>\n);\n\n// When the DAL hasn't populated the URL field for a rich-content type, the\n// embed-viewer components render a broken iframe (empty src). Fall back to\n// the same lib-styled \"Unsupported document type\" panel the explicit\n// fallback uses — the surface is honest about the missing data instead of\n// pretending to load. `FileDownloadCard` handles its own missing-URL state\n// (hides the Download button), so it doesn't need this guard.\nconst defaultPdfRenderer: DocRenderer = (content, handlers) =>\n content.fileUrl ? (\n <PdfViewer src={content.fileUrl} fileName={content.fileName} />\n ) : (\n defaultFallbackRenderer(content, handlers)\n );\n\nconst defaultGoogleSheetRenderer: DocRenderer = (content, handlers) =>\n content.externalUrl ? (\n <GoogleSheetsViewer externalUrl={content.externalUrl} fileName={content.fileName} />\n ) : (\n defaultFallbackRenderer(content, handlers)\n );\n\nconst defaultFigmaRenderer: DocRenderer = (content, handlers) =>\n content.externalUrl ? (\n <FigmaEmbed url={content.externalUrl} title={content.fileName} loading=\"eager\" />\n ) : (\n defaultFallbackRenderer(content, handlers)\n );\n\nconst defaultFileRenderer: DocRenderer = content => (\n <FileDownloadCard\n fileName={content.fileName}\n mimeType={content.mimeType}\n fileSize={content.fileSize}\n fileUrl={content.fileUrl}\n />\n);\n\nconst defaultRenderSkeleton = (documentType: DocumentType | undefined) =>\n !documentType || documentType === 'markdown' ? (\n <MarkdownSkeleton />\n ) : (\n // Forward the documentType so the embed skeleton renders the right\n // shape (PDF=2 buttons, sheets/figma=1 button, file=centered card).\n <EmbedSkeleton documentType={documentType} />\n );\n\n/**\n * Embeddable docs-hub page. Bundles `<DocViewer>` with safe defaults so the\n * minimum embed is a one-line mount (consumer only has to supply\n * `documentTypeRenderers.markdown`).\n *\n * Used by the hub at `/knowledge-base` and `/data-room`, and by third-party\n * React apps that embed the docs experience behind their own proxy. See\n * `docs/EMBEDDING_DOCS_HUB.md` for the embedder setup.\n *\n * SEO note: this component is `'use client'` (via the docs barrel) — server-\n * side SEO is the host's responsibility. The hub's `<DocSeoContent>` is the\n * canonical implementation embedders can reference.\n */\nexport function DocsHubPage({\n title = DEFAULT_TITLE,\n documentTypeRenderers,\n fallbackRenderer = defaultFallbackRenderer,\n renderSkeleton = defaultRenderSkeleton,\n showAIChat = true,\n className = 'min-h-screen',\n sidebarLabel = 'DOCUMENTATION',\n ...docViewerProps\n}: DocsHubPageProps) {\n const resolvedRenderers: DocumentTypeRenderers = {\n markdown: documentTypeRenderers.markdown,\n pdf: documentTypeRenderers.pdf ?? defaultPdfRenderer,\n google_sheet: documentTypeRenderers.google_sheet ?? defaultGoogleSheetRenderer,\n figma: documentTypeRenderers.figma ?? defaultFigmaRenderer,\n file: documentTypeRenderers.file ?? defaultFileRenderer,\n };\n\n const renderContent: DocViewerProps['renderContent'] = (content, handlers) => {\n const type = content.documentType ?? 'markdown';\n const renderer = resolvedRenderers[type] ?? fallbackRenderer;\n return renderer(content, handlers);\n };\n\n return (\n <DocViewer\n {...docViewerProps}\n title={title}\n showAIChat={showAIChat}\n className={className}\n sidebarLabel={sidebarLabel}\n renderContent={renderContent}\n renderSkeleton={renderSkeleton}\n />\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-EHAYNUOL.cjs","../src/hooks/ui/use-image-edge-color.ts","../src/utils/platform-identity.ts","../src/utils/app-config.ts","../src/utils/local-storage-adapter.ts","../src/utils/embed-proxy-auth-storage.ts","../src/utils/embed-authed-fetch.ts","../src/hooks/use-authed-asset-src.ts","../src/hooks/use-authed-image-src.ts","../src/utils/og-placeholder.ts","../src/hooks/use-og-placeholder-url.ts"],"names":["r","g","b","adapter"],"mappings":"AAAA,6rBAAY;AACZ;AACE;AACF,wDAA6B;AAC7B;AACA;ACHA,8BAAoC;AAQpC,SAAS,gBAAA,CAAiB,GAAA,EAA+B;AACvD,EAAA,MAAM,OAAA,EAAS,QAAA,CAAS,aAAA,CAAc,QAAQ,CAAA;AAC9C,EAAA,MAAM,IAAA,EAAM,MAAA,CAAO,UAAA,CAAW,IAAI,CAAA;AAClC,EAAA,GAAA,CAAI,CAAC,GAAA,EAAK,OAAO,SAAA;AAEjB,EAAA,MAAM,QAAA,EAAU,GAAA;AAChB,EAAA,MAAM,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,QAAA,EAAU,GAAA,CAAI,YAAA,EAAc,QAAA,EAAU,GAAA,CAAI,aAAa,CAAA;AAC9E,EAAA,MAAM,EAAA,EAAI,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,aAAA,EAAe,KAAK,CAAA;AAC7C,EAAA,MAAM,EAAA,EAAI,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,cAAA,EAAgB,KAAK,CA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A;AACC,EAAA;AACT,EAAA;AACD,EAAA;AACM,EAAA;AACb;AAMa;AACN,EAAA;AACP;AAEa;AAET,EAAA;AACS,EAAA;AAET,EAAA;AACF,EAAA;AACM,EAAA;AACD,EAAA;AACM,EAAA;AACb;AAEa;AACF,EAAA;AACE,EAAA;AACD,EAAA;AACV,EAAA;AACM,EAAA;AACD,EAAA;AACM,EAAA;AACb;AAEa;AACF,EAAA;AACE,EAAA;AACD,EAAA;AACC,EAAA;AACX,EAAA;AACiB,EAAA;AACF,EAAA;AACA,EAAA;AACD,EAAA;AACC,EAAA;AACT,EAAA;AACD,EAAA;AACP;AAEgB;AACP,EAAA;AACT;AAGgB;AACP,EAAA;AACT;AAEgB;AACP,EAAA;AACT;AAEgB;AACP,EAAA;AACT;AAEgB;AACP,EAAA;AACT;AAYa;AACM,EAAA;AACA,EAAA;AACF,EAAA;AACN,EAAA;AACA,EAAA;AACF,EAAA;AACP,EAAA;AACF;AAOa;AAEQ,EAAA;AACT,IAAA;AACF,IAAA;AACI,IAAA;AACI,IAAA;AACd,EAAA;AACiB,EAAA;AACT,IAAA;AACF,IAAA;AACI,IAAA;AACI,IAAA;AACd,EAAA;AACe,EAAA;AACP,IAAA;AACF,IAAA;AACI,IAAA;AACI,IAAA;AACd,EAAA;AACS,EAAA;AACD,IAAA;AACF,IAAA;AACI,IAAA;AACI,IAAA;AACd,EAAA;AACS,EAAA;AACD,IAAA;AACF,IAAA;AACI,IAAA;AACI,IAAA;AACd,EAAA;AACO,EAAA;AACC,IAAA;AACF,IAAA;AACI,IAAA;AACI,IAAA;AACd,EAAA;AACA,EAAA;AACQ,IAAA;AACF,IAAA;AACI,IAAA;AACI,IAAA;AACd,EAAA;AACF;AAUW;AAGA;AACC,EAAA;AACN,EAAA;AACR;AAEa;AACA;AAeA;AACE,EAAA;AACF,EAAA;AACC,EAAA;AACZ,EAAA;AACQ,EAAA;AACS,EAAA;AACA,EAAA;AACA,EAAA;AACD,EAAA;AACC,EAAA;AACV,EA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;AACT;AAOa;AR8kBM;AACA;ASjjBb;AAIG;AACQ,EAAA;AACT,EAAA;AACU,EAAA;AAIR,IAAA;AACF,IAAA;AACN,EAAA;AACO,EAAA;AACT;AAYgB;AAKD,EAAA;AACE,EAAA;AACF,EAAA;AACE,EAAA;AAEJ,EAAA;AACO,EAAA;AAKJ,EAAA;AACC,EAAA;AAGJ,EAAA;AACA,EAAA;AAEG,EAAA;AAChB;ATshBmB;AACA;AU7nBV;AA+BO;AACd,EAAA;AACW,EAAA;AACF,EAAA;AACC,EAAA;AAC+B;AACnC,EAAA;AAES,EAAA;AACR,IAAA;AACE,IAAA;AACM,EAAA;AACjB;AVgmBmB;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-EHAYNUOL.cjs","sourcesContent":[null,"'use client';\n\nimport { useState, useEffect } from 'react';\n\n/**\n * Extract the dominant edge color from an image using color bucketing.\n * Samples pixels along left and right edges (the visible letterbox areas),\n * groups them into color buckets, and returns the most common bucket.\n * This avoids muddy averages when edges have mixed colors (e.g., sky + sand).\n */\nfunction extractEdgeColor(img: HTMLImageElement): string {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n if (!ctx) return '#000000';\n\n const maxSize = 100;\n const scale = Math.min(maxSize / img.naturalWidth, maxSize / img.naturalHeight);\n const w = Math.round(img.naturalWidth * scale);\n const h = Math.round(img.naturalHeight * scale);\n canvas.width = w;\n canvas.height = h;\n\n ctx.drawImage(img, 0, 0, w, h);\n\n const data = ctx.getImageData(0, 0, w, h).data;\n\n // Sample left edge, right edge, top edge, bottom edge (15% band)\n const edgeW = Math.max(2, Math.round(w * 0.15));\n const edgeH = Math.max(2, Math.round(h * 0.15));\n\n // Color bucketing: quantize to 32-step buckets for grouping similar colors\n const bucketSize = 32;\n const buckets = new Map<string, { r: number; g: number; b: number; count: number }>();\n\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const isEdge = x < edgeW || x >= w - edgeW || y < edgeH || y >= h - edgeH;\n\n if (!isEdge) continue;\n\n const i = (y * w + x) * 4;\n const a = data[i + 3];\n if (a < 128) continue;\n\n const r = data[i];\n const g = data[i + 1];\n const b = data[i + 2];\n\n // Quantize to bucket\n const br = Math.floor(r / bucketSize) * bucketSize;\n const bg = Math.floor(g / bucketSize) * bucketSize;\n const bb = Math.floor(b / bucketSize) * bucketSize;\n const key = `${br},${bg},${bb}`;\n\n const existing = buckets.get(key);\n if (existing) {\n existing.r += r;\n existing.g += g;\n existing.b += b;\n existing.count++;\n } else {\n buckets.set(key, { r, g, b, count: 1 });\n }\n }\n }\n\n if (buckets.size === 0) return '#000000';\n\n // Find the most common color bucket\n let bestBucket: { r: number; g: number; b: number; count: number } | null = null;\n for (const bucket of buckets.values()) {\n if (!bestBucket || bucket.count > bestBucket.count) {\n bestBucket = bucket;\n }\n }\n\n if (!bestBucket || bestBucket.count === 0) return '#000000';\n\n // Return average color within the winning bucket\n const r = Math.round(bestBucket.r / bestBucket.count);\n const g = Math.round(bestBucket.g / bestBucket.count);\n const b = Math.round(bestBucket.b / bestBucket.count);\n\n return `rgb(${r}, ${g}, ${b})`;\n}\n\n/**\n * Hook that extracts the dominant edge color from an image URL.\n * Returns a CSS color string for use as a background behind object-contain images.\n *\n * Always sets crossOrigin='anonymous' — required for canvas pixel access.\n * Most CDNs (Supabase, Cloudflare, our image proxy) return CORS headers.\n * If the server doesn't support CORS, onerror fires and we use the fallback.\n *\n * @param imageUrl - URL of the image to analyze\n * @param fallback - Fallback color if extraction fails (default: '#000000')\n * @returns CSS color string (e.g., 'rgb(34, 28, 22)')\n */\nexport function useImageEdgeColor(imageUrl: string | undefined | null, fallback = '#000000'): string {\n const [color, setColor] = useState(fallback);\n\n // Losing the url (or being given a different fallback) is a prop-driven\n // reset, so it happens while rendering — React's documented alternative to a\n // sync-from-props effect. From the effect it would commit one frame with the\n // departed image's colour still painted behind an image that is already gone.\n const [resetFor, setResetFor] = useState({ imageUrl, fallback });\n if (resetFor.imageUrl !== imageUrl || resetFor.fallback !== fallback) {\n setResetFor({ imageUrl, fallback });\n if (!imageUrl) setColor(fallback);\n }\n\n useEffect(() => {\n if (!imageUrl) return undefined;\n\n let cancelled = false;\n const img = new Image();\n img.crossOrigin = 'anonymous';\n\n img.onload = () => {\n if (cancelled) return;\n try {\n setColor(extractEdgeColor(img));\n } catch {\n setColor(fallback);\n }\n };\n\n img.onerror = () => {\n if (cancelled) return;\n setColor(fallback);\n };\n\n img.src = imageUrl;\n\n return () => {\n cancelled = true;\n };\n }, [imageUrl, fallback]);\n\n return color;\n}\n","/**\n * Platform identity + brand SSOT (single source of truth).\n *\n * ONE module owns every per-platform STRING (display/short/long name, description,\n * slogan, icon name) and every per-platform COLOUR DECISION (the accent/secondary\n * \"stem\", the theme, the surface). Everything downstream DERIVES from here:\n * `platform-config.tsx`'s icon + colour maps, `PlatformBadge`, `getPlatformConfig`,\n * the hub's `AppConfig.brandColors`, the hub's manifest generator and `theme-color`.\n *\n * JSX-FREE + zero-dependency ON PURPOSE: it carries its own tsup entry and\n * `exports` subpath (`@flamingo-stack/openframe-frontend-core/utils/platform-identity`)\n * so hub SCRIPTS and `server-only` modules can import it without dragging React,\n * the icon components, or the utils barrel into their graph.\n *\n * TWO accepted by-construction copies of the colour decision remain, both LOCKED\n * by `src/__tests__/mlg-platform-leaves.test.ts` in this package:\n * 1. `platformHexColors` below (hand-typed hex mirror of each accent token).\n * 2. The `[data-app-type='…']` blocks in `src/styles/ods-colors.css`.\n */\n\nimport type { PlatformName } from '../types/platform';\n\n// ── Strings ─────────────────────────────────────────────────────────────────\n\n/** Human-readable platform names. THE naming source for lib-side presentation. */\nexport const platformDisplayNames = {\n openmsp: 'OpenMSP',\n openframe: 'OpenFrame',\n flamingo: 'Flamingo',\n 'flamingo-teaser': 'Flamingo Teaser',\n 'marketing-hub': 'Flamingo Marketing Hub',\n 'product-hub': 'Flamingo Product Hub',\n 'revenue-hub': 'Flamingo Revenue Hub',\n 'people-hub': 'Flamingo People Hub',\n 'company-hub': 'Flamingo Company Hub',\n tmcg: 'TMCG',\n mlg: 'Major League GitHub',\n universal: 'Universal',\n};\n\n/**\n * Short-name OVERRIDES only. A platform without a row falls back to its display\n * name, so this map never lists a name that equals `platformDisplayNames`.\n */\nexport const platformShortNames: Partial<Record<PlatformName, string>> = {\n mlg: 'MLG',\n};\n\nexport const platformDescriptions = {\n openmsp:\n 'Comprehensive directory and comparison platform for managed service providers (MSPs) and technology vendors. Reduce vendor costs and discover open-source alternatives.',\n openframe: 'AI-driven open-source security operations center (SOC) and endpoint detection platform for MSPs.',\n flamingo:\n 'AI-driven open-source OS for MSPs. Swap bloated vendor tools for open ones. Automate the boring crap. Take your margin back.',\n 'flamingo-teaser': 'Preview of Flamingo - the AI-driven open-source OS for MSPs.',\n tmcg: 'The Miami Cyber Gang - A cybersecurity community focused on education and collaboration.',\n mlg: 'Scouting report for US open-source talent. Rank GitHub contributors by programming language, city, state, region, and nearest Major League Soccer club.',\n universal: 'Cross-platform universal content.',\n};\n\nexport const platformSlogans = {\n openmsp: 'Find Your Perfect MSP Partner',\n openframe: 'Open-Source Security Operations',\n flamingo: 'Open-Source OS for MSPs',\n 'flamingo-teaser': 'Coming Soon: Open-Source OS for MSPs',\n tmcg: 'Miami Cyber Community',\n mlg: 'GitHub Scouting Report: Major League Edition',\n universal: 'Universal Platform',\n};\n\nexport const platformIconNames = {\n openmsp: 'openmsp-logo',\n openframe: 'openframe-logo',\n flamingo: 'flamingo-logo',\n universal: 'globe',\n 'flamingo-teaser': 'flamingo-logo',\n 'marketing-hub': 'flamingo-logo',\n 'product-hub': 'flamingo-logo',\n 'revenue-hub': 'flamingo-logo',\n 'people-hub': 'flamingo-logo',\n 'company-hub': 'flamingo-logo',\n tmcg: 'tmcg-logo',\n mlg: 'mlg-logo',\n};\n\nexport function getPlatformDisplayName(platformName: string): string {\n return platformDisplayNames[platformName as keyof typeof platformDisplayNames] || platformName;\n}\n\n/** Compact label (nav chips, manifest `short_name`, JSON-LD `alternateName`). */\nexport function getPlatformShortName(platformName: string): string {\n return platformShortNames[platformName as PlatformName] ?? getPlatformDisplayName(platformName);\n}\n\nexport function getPlatformDescription(platformName: string): string {\n return platformDescriptions[platformName as keyof typeof platformDescriptions] || platformName;\n}\n\nexport function getPlatformSlogan(platformName: string): string {\n return platformSlogans[platformName as keyof typeof platformSlogans] || platformName;\n}\n\nexport function getDefaultIconForPlatform(platformName: string): string {\n return platformIconNames[platformName as keyof typeof platformIconNames] || platformIconNames.universal;\n}\n\n// ── Colour stems ────────────────────────────────────────────────────────────\n\n/**\n * The six brand/attention colours (plus the neutral) a platform may adopt, named\n * by STEM rather than by token so the token spelling has exactly one home below.\n */\nexport type OdsColorStem =\n 'flamingo-pink' | 'flamingo-cyan' | 'open-yellow' | 'success' | 'warning' | 'error' | 'text-secondary';\n\n/** Stem → ODS token name (without the `--ods-` prefix). THE token spelling. */\nexport const ODS_STEM_TOKENS: Record<OdsColorStem, string> = {\n 'flamingo-pink': 'flamingo-pink-base',\n 'flamingo-cyan': 'flamingo-cyan-base',\n 'open-yellow': 'open-yellow-base',\n success: 'attention-green-success',\n warning: 'attention-yellow-warning',\n error: 'attention-red-error',\n 'text-secondary': 'system-greys-grey',\n};\n\n/**\n * Stem → Tailwind class strings. STATIC LITERALS on purpose: the Tailwind\n * scanner reads source text, so a template-built class would be purged.\n * This is the ONLY place a stem-to-class literal exists.\n */\nexport const ODS_STEM_CLASSES: Record<OdsColorStem, { text: string; bg: string; bgSoft: string; borderSoft: string }> =\n {\n 'flamingo-pink': {\n text: 'text-ods-flamingo-pink',\n bg: 'bg-ods-flamingo-pink',\n bgSoft: 'bg-ods-flamingo-pink/10',\n borderSoft: 'border-ods-flamingo-pink/30',\n },\n 'flamingo-cyan': {\n text: 'text-ods-flamingo-cyan',\n bg: 'bg-ods-flamingo-cyan',\n bgSoft: 'bg-ods-flamingo-cyan/10',\n borderSoft: 'border-ods-flamingo-cyan/30',\n },\n 'open-yellow': {\n text: 'text-ods-open-yellow',\n bg: 'bg-ods-open-yellow',\n bgSoft: 'bg-ods-open-yellow/10',\n borderSoft: 'border-ods-open-yellow/30',\n },\n success: {\n text: 'text-ods-success',\n bg: 'bg-ods-success',\n bgSoft: 'bg-ods-success/10',\n borderSoft: 'border-ods-success/30',\n },\n warning: {\n text: 'text-ods-warning',\n bg: 'bg-ods-warning',\n bgSoft: 'bg-ods-warning/10',\n borderSoft: 'border-ods-warning/30',\n },\n error: {\n text: 'text-ods-error',\n bg: 'bg-ods-error',\n bgSoft: 'bg-ods-error/10',\n borderSoft: 'border-ods-error/30',\n },\n 'text-secondary': {\n text: 'text-ods-text-secondary',\n bg: 'bg-ods-text-secondary',\n bgSoft: 'bg-ods-text-secondary/10',\n borderSoft: 'border-ods-text-secondary/30',\n },\n };\n\n// ── Theme + surface ─────────────────────────────────────────────────────────\n\n/**\n * Every platform ships the dark theme today (the hub's flamingo config says so\n * explicitly, and every `[data-app-type]` block inherits the dark `:root`).\n * ONE constant instead of a per-platform field: reintroduce the field only when\n * a platform actually differs.\n */\nexport const PLATFORM_THEME = 'dark' as const;\n\n/** The dark surface's tokens, consumed by config `brandColors` and the manifest. */\nexport const PLATFORM_SURFACE = {\n background: 'system-greys-background',\n text: 'system-greys-white',\n} as const;\n\nexport const getPlatformBackgroundVarName = (): string => `--ods-${PLATFORM_SURFACE.background}`;\nexport const getPlatformTextVarName = (): string => `--ods-${PLATFORM_SURFACE.text}`;\n\n// ── Brand record ────────────────────────────────────────────────────────────\n\nexport interface PlatformBrand {\n /** Primary brand colour (`--color-accent-primary` in the platform's CSS block). */\n accentStem: OdsColorStem;\n /** Link colour (`--color-link`). Equals `accentStem` for most platforms. */\n secondaryStem: OdsColorStem;\n}\n\n/**\n * THE accent/link table. Every row is verified against that platform's\n * `[data-app-type='…']` block in `ods-colors.css` by the hub's parity test.\n */\nexport const PLATFORM_BRAND: Record<PlatformName, PlatformBrand> = {\n openframe: { accentStem: 'open-yellow', secondaryStem: 'flamingo-cyan' },\n openmsp: { accentStem: 'open-yellow', secondaryStem: 'open-yellow' },\n flamingo: { accentStem: 'flamingo-pink', secondaryStem: 'flamingo-pink' },\n 'flamingo-teaser': { accentStem: 'flamingo-pink', secondaryStem: 'flamingo-pink' },\n tmcg: { accentStem: 'flamingo-pink', secondaryStem: 'flamingo-pink' },\n 'marketing-hub': { accentStem: 'flamingo-pink', secondaryStem: 'flamingo-pink' },\n 'product-hub': { accentStem: 'success', secondaryStem: 'success' },\n 'revenue-hub': { accentStem: 'warning', secondaryStem: 'warning' },\n 'people-hub': { accentStem: 'flamingo-cyan', secondaryStem: 'flamingo-cyan' },\n 'company-hub': { accentStem: 'error', secondaryStem: 'error' },\n mlg: { accentStem: 'flamingo-pink', secondaryStem: 'flamingo-cyan' },\n universal: { accentStem: 'text-secondary', secondaryStem: 'text-secondary' },\n};\n\n/** The brand row for a platform, falling back to `universal` for anything unknown. */\nexport function getPlatformBrand(platformName: string): PlatformBrand {\n return PLATFORM_BRAND[platformName as PlatformName] ?? PLATFORM_BRAND.universal;\n}\n\nexport function platformAccentToken(platformName: string): string {\n return ODS_STEM_TOKENS[getPlatformBrand(platformName).accentStem];\n}\n\nexport function platformSecondaryToken(platformName: string): string {\n return ODS_STEM_TOKENS[getPlatformBrand(platformName).secondaryStem];\n}\n\n/** `--ods-…` CSS variable NAME for a platform's accent (input to `resolveOdsColor`). */\nexport function platformAccentVarName(platformName: string): string {\n return `--ods-${platformAccentToken(platformName)}`;\n}\n\nexport function platformSecondaryVarName(platformName: string): string {\n return `--ods-${platformSecondaryToken(platformName)}`;\n}\n\n/** `var(--ods-…)` VALUE for a platform's accent (config `brandColors` data). */\nexport function getPlatformAccentColor(platformName: string): string {\n return `var(${platformAccentVarName(platformName)})`;\n}\n\nexport function getPlatformSecondaryColor(platformName: string): string {\n return `var(${platformSecondaryVarName(platformName)})`;\n}\n\n/** Tailwind classes for a platform, DERIVED from its stems. */\nexport function getPlatformBrandClasses(platformName: string): {\n accentText: string;\n accentBg: string;\n accentBgSoft: string;\n accentBorderSoft: string;\n secondaryText: string;\n} {\n const brand = getPlatformBrand(platformName);\n const accent = ODS_STEM_CLASSES[brand.accentStem];\n const secondary = ODS_STEM_CLASSES[brand.secondaryStem];\n return {\n accentText: accent.text,\n accentBg: accent.bg,\n accentBgSoft: accent.bgSoft,\n accentBorderSoft: accent.borderSoft,\n secondaryText: secondary.text,\n };\n}\n\n/** Platform background classes, DERIVED (was a hand-typed hex map). */\nexport const platformColors: Record<PlatformName, string> = Object.fromEntries(\n (Object.keys(PLATFORM_BRAND) as PlatformName[]).map(p => [p, getPlatformBrandClasses(p).accentBg]),\n) as Record<PlatformName, string>;\n\nexport function getPlatformColor(platformName: string) {\n return platformColors[platformName as PlatformName] || platformColors.universal;\n}\n\n/**\n * Hand-typed hex mirror of each platform's accent token (the DB `default_color`\n * and other JS-value consumers). Accepted copy #1 — locked by\n * `src/__tests__/mlg-platform-leaves.test.ts` in this package, which asserts\n * every row against the `[data-app-type]` blocks in `ods-colors.css`.\n * (The hub has its OWN parity test, but it holds different copies: the asset\n * generator's map and the generated manifests.)\n */\nexport const platformHexColors: Record<PlatformName, string> = {\n openmsp: '#ffc008',\n openframe: '#ffc008',\n flamingo: '#f357bb',\n universal: '#888888',\n 'flamingo-teaser': '#f357bb',\n 'marketing-hub': '#f357bb',\n 'product-hub': '#5ea62e',\n 'revenue-hub': '#e1b32f',\n 'people-hub': '#5efaf0',\n 'company-hub': '#f36666',\n tmcg: '#f357bb',\n mlg: '#f357bb',\n};\n\nexport function getDefaultColorForPlatform(platformName: string): string {\n return platformHexColors[platformName as PlatformName] || platformHexColors.universal;\n}\n","// Stub app config\nexport const APP_CONFIG = {\n app: {\n type: 'openmsp',\n name: 'OpenMSP',\n domain: 'openmsp.ai',\n },\n features: {\n announcements: true,\n notifications: true,\n },\n} as const;\n\nexport function getAppConfig() {\n return APP_CONFIG;\n}\n\nexport function getAppType() {\n // The exact `process.env.NEXT_PUBLIC_APP_TYPE` member expression is kept so\n // Next/webpack can statically inline it. The try/catch makes the call safe\n // in non-Next React hosts (Vite/CRA embeds) where `process` does not exist\n // at runtime — those hosts get the 'openmsp' fallback, which is fine for\n // embeds: dismissal cookies are domain-scoped and an embed domain serves\n // one platform's announcements.\n try {\n return process.env.NEXT_PUBLIC_APP_TYPE || 'openmsp';\n } catch {\n return 'openmsp';\n }\n}\n","/**\n * Thin JSON-typed Web-Storage adapter (localStorage or sessionStorage).\n *\n * Centralizes the SSR-guard + try/catch + silent quota-failure pattern\n * that every per-feature storage util would otherwise re-implement.\n *\n * Optional `namespace` prefix supports platform / user partitioning —\n * the resolver runs lazily at call time so the namespace can vary across\n * the lifetime of the page (e.g. proxy-auth switches user, which switches\n * the key suffix).\n *\n * Backend selection (`backend: 'local' | 'session'`):\n * - `'local'` (default): persists across browser sessions. Use for\n * UI state, chat history metadata, feature-flag opt-ins.\n * - `'session'`: cleared when the tab closes. Use for ANY auth-adjacent\n * value (bearer tokens, act-as identity, proxy credentials). Reduces\n * the XSS-exfiltration attack window from \"indefinite\" to \"until tab\n * close\" without losing per-session ergonomics.\n */\n\nexport type WebStorageBackend = 'local' | 'session';\n\nexport interface LocalStorageAdapter<T> {\n load(): T | null;\n save(value: T): void;\n clear(): void;\n /** Resolved storage key for the current call. Useful for tests. */\n resolveKey(): string;\n}\n\nexport interface LocalStorageAdapterOptions<T> {\n /** Base storage key. Combined with `namespace()` when provided. */\n key: string;\n /** Optional dynamic namespace prefix appended via `.` separator.\n * Called on EVERY read/write so the key can vary across the page\n * lifetime (e.g. when the platform or user identity changes). */\n namespace?: () => string | null | undefined;\n /** Runtime shape check. Falsey return → `load()` yields null. */\n validate?: (parsed: unknown) => parsed is T;\n /** Diagnostic prefix written to `console.warn` on parse / write\n * failures. Defaults to `'[local-storage]'`. */\n logTag?: string;\n /** Which Web-Storage backend to use. Defaults to `'local'`. Pass\n * `'session'` for anything auth-adjacent so the value evaporates\n * when the tab closes. */\n backend?: WebStorageBackend;\n}\n\nfunction getStorage(backend: WebStorageBackend): Storage | null {\n if (typeof window === 'undefined') return null;\n try {\n return backend === 'session' ? window.sessionStorage : window.localStorage;\n } catch {\n // Some sandboxed contexts (Safari private mode older versions,\n // strict CSP) throw on storage access — treat as unavailable.\n return null;\n }\n}\n\nexport function createLocalStorageAdapter<T>(options: LocalStorageAdapterOptions<T>): LocalStorageAdapter<T> {\n const tag = options.logTag ?? '[local-storage]';\n const backend: WebStorageBackend = options.backend ?? 'local';\n const resolveKey = (): string => {\n const ns = options.namespace?.();\n return ns ? `${ns}.${options.key}` : options.key;\n };\n\n return {\n resolveKey,\n load() {\n const storage = getStorage(backend);\n if (!storage) return null;\n try {\n const raw = storage.getItem(resolveKey());\n if (!raw) return null;\n const parsed = JSON.parse(raw) as unknown;\n if (options.validate && !options.validate(parsed)) return null;\n return parsed as T;\n } catch (err) {\n console.warn(`${tag} parse failed for key ${resolveKey()}:`, err);\n return null;\n }\n },\n save(value: T) {\n const storage = getStorage(backend);\n if (!storage) return;\n try {\n storage.setItem(resolveKey(), JSON.stringify(value));\n } catch (err) {\n console.warn(`${tag} write failed for key ${resolveKey()}:`, err);\n }\n },\n clear() {\n const storage = getStorage(backend);\n if (!storage) return;\n try {\n storage.removeItem(resolveKey());\n } catch (err) {\n console.warn(`${tag} clear failed for key ${resolveKey()}:`, err);\n }\n },\n };\n}\n","'use client';\n\n/**\n * Client-side persistence for embed-surface proxy credentials (a\n * PLATFORM API KEY + impersonation email). Used by every embedded\n * surface — the chat widget AND the ticket center AND any future\n * embedded React component that needs to identify itself as the\n * impersonated customer.\n *\n * When set, the surface attaches the creds as\n * `Authorization: Bearer <platform API key>` + `X-Chat-Act-As: <email>`\n * on every call to `/api/docs/chat`, `/api/chat/*`, and any other route\n * gated by `requireChatAuth` — proving to the server that this session\n * is acting on behalf of <email>. The key is minted in the hub's\n * `/admin/api-keys` and is platform-bound (`fpk_<platform>_…`): a\n * SERVICE key may act as any email; a PERSONAL key only as its owner.\n *\n * **Naming history:** the stored field is still named `secret` and the\n * wire-side header names are `X-Chat-*`. Those are client/server\n * contracts predating the per-platform key migration (the old shared\n * `CHAT_PROXY_SECRET` env is removed hub-side); renaming them would\n * break persisted state + the wire shape for zero behavior change. The\n * CLIENT-side helpers were renamed `Embed*` so non-chat surfaces (e.g.\n * ticket center) don't have to import a chat-prefixed symbol just to\n * send the same headers.\n *\n * Persists to **`localStorage`** so the bearer token + act-as identity\n * survive tab close, new-tab opens, and browser restarts — the\n * `/debug` paste-creds UI is an admin tool and re-pasting every tab\n * cycle was rejected as a dev-experience tradeoff that wasn't worth\n * the security gain. An XSS sink on this origin can read the value\n * indefinitely (vs only-this-tab with sessionStorage), but `/debug`\n * is admin-gated behind the platform's `askAI.enabled` flag, the key\n * is server-verified (hash-at-rest, platform-bound, revocable in\n * `/admin/api-keys`), and the act-as reach is bounded by the key's\n * tier. Explicit \"Clear\" button on the creds bar is the supported\n * logout path; closing the tab is no longer.\n *\n * Namespaced under `<platform>.chat.proxy-auth.v1` (the storage key is\n * unchanged from the old chat-prefixed helper — that's a storage\n * contract; renaming it would log everyone out).\n */\n\nimport { getAppType } from './app-config';\nimport { createLocalStorageAdapter } from './local-storage-adapter';\n\nexport interface EmbedProxyAuth {\n secret: string;\n email: string;\n /** Optional identity passthrough — empty/omitted = not sent. Server\n * parses these as `X-Chat-{First,Last}-Name` / `X-Chat-Avatar-Url` and\n * threads them through `resolveChatProxyIdentity`'s returned user. */\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}\n\nfunction isValidPersistedAuth(value: unknown): value is EmbedProxyAuth {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n if (\n typeof v.secret !== 'string' ||\n v.secret.trim().length === 0 ||\n typeof v.email !== 'string' ||\n v.email.trim().length === 0\n )\n return false;\n // Optional fields: when present must be strings. Empty string is treated\n // as absent later (in `getEmbedProxyAuth`).\n if (v.firstName != null && typeof v.firstName !== 'string') return false;\n if (v.lastName != null && typeof v.lastName !== 'string') return false;\n if (v.avatarUrl != null && typeof v.avatarUrl !== 'string') return false;\n return true;\n}\n\nconst adapter = createLocalStorageAdapter<EmbedProxyAuth>({\n // Storage key unchanged from the legacy chat-prefixed helper. Renaming\n // it would silently log every existing admin out — the key is a\n // storage contract, not a code identifier.\n key: 'chat.proxy-auth.v1',\n namespace: () => getAppType(),\n validate: isValidPersistedAuth,\n logTag: '[embed-proxy-auth-storage]',\n // localStorage — survives tab close, new tabs, and browser restarts.\n // Admin re-pasting creds every tab cycle was the dev-experience\n // tradeoff prior `sessionStorage` setup demanded — rejected. See\n // file-level doc comment for the security tradeoff rationale.\n backend: 'local',\n});\n\n/** Trim + null-coerce an optional identity field so consumers can do\n * `auth.firstName ?? ''` without worrying about whitespace-only strings. */\nfunction normalizeOptional(value: string | undefined): string | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Returns full credentials (secret + email + optional identity passthrough)\n * when secret + email are available. Returns `null` when nothing is saved —\n * callers treat that as \"fall back to cookie auth\".\n */\nexport function getEmbedProxyAuth(): EmbedProxyAuth | null {\n const persisted = adapter.load();\n if (!persisted) return null;\n return {\n secret: persisted.secret,\n email: persisted.email.trim().toLowerCase(),\n firstName: normalizeOptional(persisted.firstName),\n lastName: normalizeOptional(persisted.lastName),\n avatarUrl: normalizeOptional(persisted.avatarUrl),\n };\n}\n\n/**\n * Returns the LAST email the admin saved. The proxy creds bar reads\n * this to pre-fill the email field on mount.\n */\nexport function getPersistedProxyEmail(): string | null {\n const persisted = adapter.load();\n return persisted?.email.trim().toLowerCase() ?? null;\n}\n\n/** Save the proxy creds. Secret + email are required; identity-passthrough\n * fields are persisted only when non-empty. */\nexport function setEmbedProxyAuth(value: EmbedProxyAuth): void {\n adapter.save({\n secret: value.secret,\n email: value.email.trim().toLowerCase(),\n firstName: normalizeOptional(value.firstName),\n lastName: normalizeOptional(value.lastName),\n avatarUrl: normalizeOptional(value.avatarUrl),\n });\n}\n\n/** Drop the persisted creds. */\nexport function clearEmbedProxyAuth(): void {\n adapter.clear();\n}\n\n/**\n * Apply the embed-proxy auth (Bearer + X-Chat-Act-As) to a fetch call's\n * URL + headers. Used by every embedded-surface route that needs to\n * identify itself as the proxied customer (chat stream, agent-* routes,\n * ticket-center actions). When proxy auth is absent (regular\n * cookie-session users), returns the inputs unchanged so the cookie-auth\n * path still works.\n *\n * `X-Chat-Act-As` header (vs a URL query param) keeps PII out of access\n * logs, Sentry breadcrumbs, browser history, and CDN analytics.\n */\nexport function applyProxyAuth(\n url: string,\n baseHeaders: Record<string, string> = { 'Content-Type': 'application/json' },\n): { url: string; headers: Record<string, string> } {\n const auth = getEmbedProxyAuth();\n const headers = { ...baseHeaders };\n if (auth?.secret) {\n headers.Authorization = `Bearer ${auth.secret}`;\n }\n if (auth?.email) {\n headers['X-Chat-Act-As'] = auth.email;\n }\n // Optional identity passthrough — only attached when present so the\n // server's \"required vs optional\" header shape stays exact.\n if (auth?.firstName) headers['X-Chat-First-Name'] = auth.firstName;\n if (auth?.lastName) headers['X-Chat-Last-Name'] = auth.lastName;\n if (auth?.avatarUrl) headers['X-Chat-Avatar-Url'] = auth.avatarUrl;\n return { url, headers };\n}\n","'use client';\n\n/**\n * Shared `fetch` wrapper for any embedded surface (chat, ticket center,\n * future widgets) that needs to carry the bearer-act-as identity\n * (proxy `Authorization` + `X-Chat-Act-As` headers from\n * `embed-proxy-auth-storage.ts`).\n *\n * Wire header names are `X-Chat-*` for historical reasons — that's a\n * server contract, not a UI namespace. The wrapper itself is generic.\n *\n * Drop-in replacement for `fetch()` — `Authorization` / `X-Chat-Act-As`\n * are merged into `init.headers` when proxy creds are stashed in\n * sessionStorage, otherwise the call falls through to the cookie-auth\n * path unchanged.\n *\n * Use this for any client-side fetch hitting `/api/chat/*`, `/api/docs/chat/*`,\n * or `/api/storage/generate-upload-url` (chat-attachment surface — shared\n * with the ticket center). Routes that do NOT need bearer-act-as\n * (e.g. `/api/profile/me`) keep using vanilla `fetch`.\n */\n\nimport { applyProxyAuth } from './embed-proxy-auth-storage';\n\n// =============================================================================\n// Host-supplied auth adapter (opt-in)\n// =============================================================================\n\n/**\n * Hosts that have their own auth model (cookie sessions, app-specific\n * JWT in localStorage, OAuth access tokens, …) can register an adapter\n * to override the lib's default `embedProxyAuth` flow. When set, the\n * adapter's `getHeaders()` result is merged onto every `embedAuthedFetch`\n * call AFTER the default proxy-auth header step (so adapter headers\n * win over both caller and proxy values), and `credentials` overrides\n * the default `'same-origin'` behaviour.\n *\n * Default (no adapter): MPH-style proxy-impersonation — bearer + act-as\n * read from localStorage, `credentials: 'same-origin'`. No consumer\n * needs to touch this unless they want a different auth model.\n *\n * Use cases:\n * - openframe-frontend has its own JWT in `localStorage.of_access_token`\n * and cookie-based session; register an adapter to attach the JWT\n * and request `credentials: 'include'` so cookies travel cross-origin\n * to the openframe gateway.\n * - Future embed hosts with OAuth access tokens, signed URLs, etc.\n *\n * Lifetime: setter is module-level (intentionally — `embedAuthedFetch`\n * is a plain utility, not a hook, so it can't read React context). Host\n * runtime providers should call `setEmbedAuthAdapter(...)` on mount and\n * `setEmbedAuthAdapter(null)` on unmount. Multiple hosts registering at\n * once is a programming error (one chat panel per app).\n */\nexport interface EmbedAuthAdapter {\n /** Headers merged onto every embedded-fetch call. Return `{}` to add\n * nothing. Called per-request so reactive token refresh sees the latest\n * value from your auth store / storage. Values typed as\n * `string | undefined` so the common narrowed shape\n * `{ Authorization: token ? 'Bearer …' : undefined }` (or a conditional\n * `token ? { Authorization: … } : {}`) assigns cleanly — `undefined`\n * values are filtered before being merged into the request headers. */\n getHeaders?: () => Record<string, string | undefined>;\n /** `RequestInit.credentials` mode. Default when no adapter: callers'\n * `init.credentials` or `'same-origin'`. Use `'include'` for cookie\n * auth against a different origin (CORS + `SameSite=None` required). */\n credentials?: RequestCredentials;\n /**\n * Optional 401 self-heal. When a request comes back `401`,\n * `embedAuthedFetch` calls this once, and — if it resolves `true` —\n * retries the SAME request exactly once with freshly-recomputed\n * headers (so a rotated bearer from `getHeaders()` is picked up).\n * Resolve `false` to surface the 401 to the caller unchanged.\n *\n * This is the capability the openframe `apiClient` has had all along\n * (refresh-the-access-token-then-retry); registering it here gives the\n * embedded chat/ticket surfaces the same self-healing auth instead of\n * dying on an expired token. Concurrent 401s are de-duplicated by the\n * wrapper, so this fires at most once per refresh cycle even when a\n * stampede of chat requests all expire together — your implementation\n * does NOT need its own in-flight guard (though a token-refresh manager\n * that already dedups is harmless).\n *\n * Keep it idempotent and side-effect-light: on failure the wrapper just\n * returns the original 401 — logout/redirect decisions belong to the\n * host's own auth layer, not to this fetch wrapper.\n */\n refresh?: () => Promise<boolean>;\n /**\n * Exact extra origins (`scheme://host[:port]`, as produced by `URL.origin`)\n * the same-origin guard additionally accepts. The guard normally rejects\n * every cross-origin URL in production — but native-shell hosts serve the\n * page from a local pseudo-origin (`capacitor://localhost`,\n * `tauri://localhost`) with NO server behind it, so the gateway their\n * bearer already belongs to is unavoidably cross-origin. Listing it here\n * is the host's explicit sanction to send the adapter's credentials there.\n * Compared AFTER the http(s)-protocol check, so non-http(s) schemes can\n * never be allowlisted. Omit (or leave empty) everywhere else — same-origin\n * remains the rule, this is the narrow exception.\n */\n allowedOrigins?: string[];\n}\n\n/**\n * The registered adapter is parked on `globalThis`, NOT in a module-private\n * `let`. Reason: this lib ships multiple entry points (`/utils`,\n * `/components/chat`, …) and a consumer's bundler can inline this file into\n * more than one chunk — giving each chunk its OWN module scope. If the host\n * calls `setEmbedAuthAdapter` from the `/utils` copy while the chat's\n * `embedAuthedFetch` runs from the `/components/chat` copy, a module-local\n * `let` would be set on one copy and read as `null` on the other (the exact\n * \"credentials: same-origin, no Bearer, no refresh\" symptom). A single\n * `globalThis` slot is shared across every copy, so registration always\n * reaches the fetch path.\n */\nconst ADAPTER_GLOBAL_KEY = '__embedAuthedFetchAdapter__';\n\nfunction getRegisteredAuthAdapter(): EmbedAuthAdapter | null {\n if (typeof globalThis === 'undefined') return null;\n return ((globalThis as Record<string, unknown>)[ADAPTER_GLOBAL_KEY] as EmbedAuthAdapter | null) ?? null;\n}\n\nfunction storeRegisteredAuthAdapter(adapter: EmbedAuthAdapter | null): void {\n if (typeof globalThis === 'undefined') return;\n (globalThis as Record<string, unknown>)[ADAPTER_GLOBAL_KEY] = adapter;\n}\n\n/**\n * Register a host-owned auth adapter for `embedAuthedFetch`. Pass `null`\n * to clear (typically on provider unmount).\n *\n * Module-level state — there is one chat panel per app, so a single\n * registration is sufficient. Calling this twice with different non-null\n * adapters replaces the previous one (the most recent registration wins);\n * a `console.warn` flags the overwrite so duplicate-provider mounts get\n * caught in dev.\n */\nexport function setEmbedAuthAdapter(adapter: EmbedAuthAdapter | null): void {\n if (adapter && getRegisteredAuthAdapter() && process.env.NODE_ENV !== 'production') {\n console.warn(\n '[setEmbedAuthAdapter] overwriting a previously-registered auth ' +\n 'adapter. Two chat-runtime providers should not coexist — verify ' +\n 'mount order and pass `null` from the unmounting provider.',\n );\n }\n storeRegisteredAuthAdapter(adapter);\n}\n\n/**\n * Whether a host auth adapter is currently registered. Lets sibling helpers\n * (e.g. `contentFetch`) route through `embedAuthedFetch` ONLY when a host has\n * opted into embedded auth, and stay a plain `fetch` otherwise — so there's a\n * single auth knob (the adapter), not a second content-fetch registration.\n */\nexport function hasEmbedAuthAdapter(): boolean {\n return getRegisteredAuthAdapter() !== null;\n}\n\n/**\n * Whether `url` is an asset the browser CANNOT load natively because its\n * auth rides in request headers.\n *\n * Native asset loads (`<img src>`, `<track src>`, CSS `background-image`)\n * can't carry custom headers, so a URL this returns `true` for must go\n * through `embedAuthedFetch` → blob object-URL instead (see\n * `useAuthedAssetSrc` / `useAuthedImageSrc`).\n *\n * The single signal is the registered adapter: when it supplies an\n * `Authorization` header, the host authenticates by HEADER, so nothing the\n * browser fetches on its own is authenticated. That holds for BOTH shapes a\n * header-auth host takes:\n *\n * - a cross-origin gateway URL — sanctioned via `allowedOrigins` (native\n * shells, whose page origin is `capacitor://` / `tauri://`);\n * - a same-origin / relative reverse-proxy path (`/content/api/...`) —\n * dev-ticket web, where the token lives in localStorage and there is NO\n * session cookie to fall back on. This case used to be excluded on the\n * assumption that same-origin implies \"cookies work\"; true for a cookie\n * session, false for every header-auth host, which is exactly when this\n * predicate is consulted at all.\n *\n * Everything else loads natively, unchanged: cookie-auth web (the adapter\n * supplies no `Authorization`), no adapter at all (the hub), and third-party\n * origins the bearer does NOT belong to (public images) — those stay out of\n * reach of the token by the same origin rules `embedAuthedFetch` enforces.\n */\nexport function needsBearerAssetFetch(url: string): boolean {\n if (typeof window === 'undefined') return false;\n const adapter = getRegisteredAuthAdapter();\n if (!adapter || adapter.getHeaders?.().Authorization === undefined) return false;\n let target: URL;\n let pageOrigin: string;\n try {\n target = new URL(url, window.location.href);\n // Same reason `assertSameOrigin` derives it this way: test environments\n // mock `window.location` as a plain object with no `origin` field.\n pageOrigin = new URL(window.location.href).origin;\n } catch {\n return false;\n }\n if (target.protocol !== 'http:' && target.protocol !== 'https:') return false;\n if (target.origin === pageOrigin) return true;\n return adapter.allowedOrigins?.includes(target.origin) ?? false;\n}\n\n/**\n * `fetch` wrapper that attaches embed-proxy bearer headers (when\n * present in sessionStorage) and forces `credentials: 'same-origin'`\n * so Supabase auth cookies travel too.\n *\n * **Header merge direction (proxy WINS over caller):** the implementation\n * spreads `baseHeaders` first inside `applyProxyAuth`, then sets the\n * `Authorization` / `X-Chat-*` keys — so the proxy values take precedence\n * over anything the caller passed. The motivation is that the bearer +\n * act-as identity is the source of truth for embedded auth; a caller\n * accidentally passing a stale `Authorization` header should NOT override\n * the live proxy creds.\n *\n * **Cross-origin defense:** the wrapper assumes a same-origin `/api/…`\n * relative URL. Absolute URLs are accepted only when their origin matches\n * the current window's origin — or appears in the registered adapter's\n * `allowedOrigins` (the native-shell hatch; see that field's doc) — and\n * cross-origin URLs otherwise throw before the bearer leaves the page.\n * This is a defense-in-depth guard for future call sites — outside the\n * allowlisted-shell case there is no legitimate cross-origin use of this\n * fetch wrapper.\n *\n * **401 self-heal:** when a registered adapter supplies `refresh`, a `401`\n * response triggers a single token refresh + retry of the same request\n * (see `EmbedAuthAdapter.refresh`). This is the openframe `apiClient`'s\n * refresh-then-retry behaviour, lifted into the lib so embedded surfaces\n * no longer need a host-side `window.fetch` monkey-patch to survive an\n * expired access token mid-chat. With no adapter (or no `refresh`), the\n * 401 passes straight through unchanged.\n */\nexport function embedAuthedFetch(url: string, init: RequestInit = {}): Promise<Response> {\n // Same-origin guard runs SYNCHRONOUSLY (not awaited inside the async\n // helper below) so a bearer-leaking cross-origin URL throws before any\n // promise is created — callers and tests rely on the synchronous throw.\n assertSameOrigin(url);\n\n // `applyProxyAuth` accepts `Record<string, string>`; normalize the\n // caller's headers to that shape ONCE, up front. RequestInit accepts\n // `HeadersInit` which is broader (Headers instance OR array of tuples).\n // We re-derive the per-request headers from this base on every attempt\n // (initial + post-refresh retry) so a rotated bearer is picked up.\n //\n // When the caller passes no headers, fall back to the same default\n // `applyProxyAuth` uses internally — `Content-Type: application/json` —\n // so JSON POSTs keep their content-type when only `embedAuthedFetch(url)`\n // is used at the call site. GET callers that explicitly want no body\n // headers can pass `init.headers = {}` to opt out.\n let baseHeaders: Record<string, string>;\n if (init.headers === undefined) {\n baseHeaders = { 'Content-Type': 'application/json' };\n } else {\n baseHeaders = {};\n if (init.headers instanceof Headers) {\n init.headers.forEach((v, k) => {\n baseHeaders[k] = v;\n });\n } else if (Array.isArray(init.headers)) {\n for (const [k, v] of init.headers) baseHeaders[k] = v;\n } else {\n Object.assign(baseHeaders, init.headers);\n }\n }\n\n return fetchWithRefresh(url, init, baseHeaders, false);\n}\n\n/**\n * Single in-flight refresh shared across all concurrent `embedAuthedFetch`\n * callers. A stampede of chat requests that all 401 at the same moment must\n * trigger the adapter's `refresh()` ONCE, not N times — otherwise an\n * expiring session fires a thundering herd of refresh calls at the auth\n * server. Resets to `null` once settled so the next genuine expiry can\n * refresh again.\n */\n// Stored on `globalThis` rather than a module-local so the \"single refresh\"\n// guarantee survives module duplication. Bundlers can ship more than one copy\n// of this module (e.g. across chunks or a host + embedded build); a per-module\n// variable would let each copy run its own refresh cycle, re-creating the\n// thundering-herd this dedupe exists to prevent.\nconst IN_FLIGHT_REFRESH_GLOBAL_KEY = '__embedAuthedFetchInFlightRefresh__';\n\nfunction getInFlightRefresh(): Promise<boolean> | null {\n if (typeof globalThis === 'undefined') return null;\n return (\n ((globalThis as Record<string, unknown>)[IN_FLIGHT_REFRESH_GLOBAL_KEY] as Promise<boolean> | null | undefined) ??\n null\n );\n}\n\nfunction setInFlightRefresh(refresh: Promise<boolean> | null): void {\n if (typeof globalThis === 'undefined') return;\n (globalThis as Record<string, unknown>)[IN_FLIGHT_REFRESH_GLOBAL_KEY] = refresh;\n}\n\nfunction dedupedRefresh(): Promise<boolean> {\n const adapter = getRegisteredAuthAdapter();\n // Bound and captured BEFORE the closure below. `refresh` is an optional\n // property, so TypeScript drops the `if (!adapter?.refresh)` narrowing inside\n // the `.then()` callback — the property could in principle be reassigned\n // between the guard and the call. `bind` keeps the adapter as the receiver.\n const refresh = adapter?.refresh?.bind(adapter);\n if (!refresh) return Promise.resolve(false);\n let inFlightRefresh = getInFlightRefresh();\n if (!inFlightRefresh) {\n // Wrap in `Promise.resolve` so an adapter that throws synchronously\n // (rather than rejecting) still funnels through the shared slot and\n // clears it. A rejected refresh is treated as \"could not refresh\".\n inFlightRefresh = Promise.resolve()\n .then(() => refresh())\n .catch(() => false)\n .finally(() => {\n setInFlightRefresh(null);\n });\n setInFlightRefresh(inFlightRefresh);\n }\n return inFlightRefresh;\n}\n\n/**\n * Core fetch path: merge proxy-auth + adapter headers, issue the request,\n * and — on a `401` with a refresh-capable adapter — refresh once and retry\n * the identical request a single time. Mirrors the openframe `apiClient`'s\n * refresh-then-retry contract (`isRetry` guards against infinite loops).\n */\nasync function fetchWithRefresh(\n url: string,\n init: RequestInit,\n baseHeaders: Record<string, string>,\n isRetry: boolean,\n): Promise<Response> {\n // Re-run the merge each attempt: `applyProxyAuth` reads the latest stored\n // proxy creds and `getHeaders()` reads the latest bearer, so a retry after\n // refresh carries the rotated token rather than the stale one. `{...baseHeaders}`\n // keeps the caller's normalized headers immutable across attempts.\n const { url: authedUrl, headers } = applyProxyAuth(url, { ...baseHeaders });\n\n // Host-supplied auth adapter layer. Runs AFTER the proxy-auth merge so\n // adapter headers override both caller and proxy values — the adapter\n // is the host's explicit \"this is my auth model\" override, intentionally\n // last-writer-wins. When no adapter is registered, this is a zero-cost\n // no-op (object spread of `{}`).\n const adapter = getRegisteredAuthAdapter();\n if (adapter?.getHeaders) {\n // Filter `undefined` values — the adapter type allows them so consumers\n // don't have to narrow `{ Authorization: token ? '…' : undefined }`-shaped\n // returns, but `fetch` headers must be strings.\n for (const [k, v] of Object.entries(adapter.getHeaders())) {\n if (v !== undefined) headers[k] = v;\n }\n }\n const credentials = adapter?.credentials ?? init.credentials ?? 'same-origin';\n\n const response = await fetch(authedUrl, {\n ...init,\n headers,\n // Default `same-origin` carries Supabase cookies for the MPH proxy-\n // auth model. Hosts on different origins (openframe-frontend ↔\n // openframe gateway) register `credentials: 'include'` via the\n // adapter to make their own cookies travel cross-origin (CORS +\n // `SameSite=None` must be configured server-side for that to work).\n credentials,\n });\n\n // 401 self-heal: refresh the token once and retry. Only when an adapter\n // opted into `refresh`, and only on the first attempt — a 401 on the\n // retry means the fresh token is also unauthorized, so surface it.\n if (response.status === 401 && !isRetry && adapter?.refresh) {\n const refreshed = await dedupedRefresh();\n if (refreshed) {\n return fetchWithRefresh(url, init, baseHeaders, true);\n }\n }\n\n return response;\n}\n\n/**\n * Reject any URL that resolves to a cross-origin destination or to a\n * non-http(s) scheme. Every input is resolved against\n * `window.location.href` so the same rule covers path-only\n * (`/api/...`), absolute (`https://...`), protocol-relative\n * (`//host/...`), AND whitespace-prefixed forms (`\\t//evil.com/...`) —\n * the WHATWG fetch spec strips leading ASCII whitespace before\n * parsing, so any regex-based \"skip relative\" shortcut is bypassable\n * with a leading `\\t`/`\\n`/`\\r`/space. We resolve unconditionally\n * instead and compare origins.\n *\n * Also blocks `javascript:` / `data:` / `blob:` etc. — only `http(s):`\n * is allowed. This is explicit allowlisting rather than relying on\n * `origin === 'null'` to fall out wrong.\n *\n * Server-side rendering: when `typeof window === 'undefined'` we skip\n * the check — the bearer comes from sessionStorage which doesn't exist\n * on the server, so there's nothing to leak anyway.\n */\nfunction assertSameOrigin(url: string): void {\n if (typeof window === 'undefined') return;\n let target: URL;\n let pageOrigin: string;\n try {\n target = new URL(url, window.location.href);\n // Derive the page origin from `href` rather than reading\n // `window.location.origin` directly so the check works in test\n // environments that mock `window.location` to a plain object\n // without an `origin` field (jsdom setups do this).\n pageOrigin = new URL(window.location.href).origin;\n } catch {\n throw new Error(`embedAuthedFetch: refusing to fetch malformed URL (${JSON.stringify(url)})`);\n }\n if (target.protocol !== 'http:' && target.protocol !== 'https:') {\n throw new Error(\n `embedAuthedFetch: refusing non-http(s) URL (${target.protocol}) — pass a relative /api/* path instead`,\n );\n }\n if (target.origin !== pageOrigin) {\n // Host-sanctioned cross-origin target (`EmbedAuthAdapter.allowedOrigins`).\n // Native shells serve the page from a local pseudo-origin with no server\n // behind it, so their gateway — the same backend the host already trusts\n // with this bearer — is unavoidably cross-origin. Exact `URL.origin`\n // match, and only reachable for http(s) targets (checked above).\n if (getRegisteredAuthAdapter()?.allowedOrigins?.includes(target.origin)) {\n return;\n }\n // Dev-mode escape hatch — embedded apps (e.g. openframe-frontend)\n // run on a different origin from their gateway during local dev,\n // and forcing a Next.js `rewrites()` workaround is more error-prone\n // than relaxing the guard for the dev build. In production\n // (`NODE_ENV === 'production'`) the guard stays absolute — same\n // defense-in-depth bearer-leak protection as before. The check is\n // baked at build time by Next/webpack/Turbopack so prod bundles\n // contain only the throwing branch (no dev string in the artifact).\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[embedAuthedFetch] cross-origin fetch to ${target.origin} ` +\n `allowed in dev (NODE_ENV !== 'production'). Production builds ` +\n `will reject this — wire a same-origin proxy before shipping.`,\n );\n return;\n }\n throw new Error(\n `embedAuthedFetch: refusing cross-origin fetch to ${target.origin} — pass a relative /api/* path instead`,\n );\n }\n}\n","'use client';\n\nimport { useEffect, useReducer } from 'react';\nimport { embedAuthedFetch, needsBearerAssetFetch } from '../utils/embed-authed-fetch';\n\n/**\n * Resolve ANY asset URL the browser would load natively — `<img src>`,\n * `<track src>`, a font, a poster — for hosts whose auth rides in request\n * HEADERS instead of cookies: native shells (`capacitor://`, `tauri://`) and\n * dev-ticket web, both in bearer mode. A native subresource load can't carry\n * an `Authorization` header, so a gateway URL that works on the cookie-auth\n * web 401s there.\n *\n * When `needsBearerAssetFetch` says the URL is bearer-authed, this hook\n * fetches it through `embedAuthedFetch` (bearer + deduped 401-refresh-retry +\n * the adapter's cross-origin guard — the SAME single auth knob every embedded\n * `fetch` in the lib rides) and returns a blob object-URL. Every other URL is\n * returned unchanged, so on the cookie-auth web the hook is a pass-through.\n *\n * Returns `undefined` while the fetch is in flight OR after it fails, so\n * callers show their existing placeholder / \"no captions\" branch instead of a\n * broken asset; a failed fetch retries on the next mount.\n *\n * Cache: module-level, session-lifetime, keyed by full URL — so the two\n * `<track>` URLs of one player, or the same avatar in twenty rows, cost one\n * request. Gateway URLs carry a `?v=<content-hash>` cache-buster, so changed\n * content is a new key; entries are never revoked (a VTT / avatar is a few KB\n * — refcount churn isn't worth it) and are dropped wholesale at session end\n * via `clearAuthedAssetCache`.\n */\n\nconst resolvedCache = new Map<string, string>();\nconst inFlight = new Map<string, Promise<void>>();\nlet cacheGeneration = 0;\n\n/**\n * Drop every cached blob and revoke its object URL. Hosts call this at\n * session end (logout / forced re-login) so a follow-on login as a\n * different identity cannot be served blobs fetched under the previous\n * one's bearer. Fetches still in flight when the clear happens are fenced\n * by a generation counter — their results are revoked instead of cached.\n */\nexport function clearAuthedAssetCache(): void {\n cacheGeneration++;\n for (const url of resolvedCache.values()) URL.revokeObjectURL(url);\n resolvedCache.clear();\n inFlight.clear();\n}\n\nfunction fetchAsBlobUrl(src: string, accept: string): Promise<void> {\n let pending = inFlight.get(src);\n if (!pending) {\n const startedGeneration = cacheGeneration;\n pending = embedAuthedFetch(src, { headers: { Accept: accept } })\n .then(async response => {\n if (!response.ok) throw new Error(`asset fetch failed: ${response.status}`);\n const blobUrl = URL.createObjectURL(await response.blob());\n if (startedGeneration === cacheGeneration) {\n resolvedCache.set(src, blobUrl);\n } else {\n URL.revokeObjectURL(blobUrl);\n }\n })\n .finally(() => {\n if (inFlight.get(src) === pending) inFlight.delete(src);\n });\n inFlight.set(src, pending);\n }\n return pending;\n}\n\n/**\n * @param src the asset URL (relative or absolute), or null/undefined\n * @param accept `Accept` header for the authed fetch — narrow it to what the\n * consumer renders (`image/*`, `text/vtt`); it also replaces\n * `embedAuthedFetch`'s default JSON `Content-Type` on the GET.\n */\nexport function useAuthedAssetSrc(src?: string | null, accept = '*/*'): string | undefined {\n const bearerSrc = src && needsBearerAssetFetch(src) ? src : null;\n const [, rerender] = useReducer((c: number) => c + 1, 0);\n\n useEffect(() => {\n if (!bearerSrc || resolvedCache.has(bearerSrc)) return undefined;\n let cancelled = false;\n fetchAsBlobUrl(bearerSrc, accept)\n .catch(() => {})\n .finally(() => {\n if (!cancelled) rerender();\n });\n return () => {\n cancelled = true;\n };\n }, [bearerSrc, accept]);\n\n if (!src) return undefined;\n if (!bearerSrc) return src;\n return resolvedCache.get(bearerSrc);\n}\n","'use client';\n\nimport { clearAuthedAssetCache, useAuthedAssetSrc } from './use-authed-asset-src';\n\n/**\n * Image flavor of `useAuthedAssetSrc` — see that hook for the full contract.\n * Kept as its own export because it is the lib's most-used consumer (avatars,\n * entity images, markdown `<img>`) and because hosts already import this name.\n *\n * Distinct from the legacy `useAuthenticatedImage`, which ALWAYS blob-fetches\n * with `credentials: 'include'` and its own global config. This hook is\n * pass-through-first and keys off the single auth knob the lib already has:\n * the registered `EmbedAuthAdapter`.\n */\nexport function useAuthedImageSrc(src?: string | null): string | undefined {\n return useAuthedAssetSrc(src, 'image/*');\n}\n\n/**\n * Session-end cache drop. Now an alias of `clearAuthedAssetCache` — one cache\n * backs every authed asset (images AND caption tracks), so hosts keep calling\n * this single function on logout / forced re-login.\n */\nexport const clearAuthedImageCache = clearAuthedAssetCache;\n","/**\n * Branded OG-placeholder URL construction — the DEFAULT cover-image fallback\n * for entity cards (onboarding guides, blog/case-study/release/etc.) that have\n * no image.\n *\n * ALL of the logic lives here, in the lib. A consumer hands over its runtime\n * `endpoints` object and NOTHING else — base resolution AND the `?title=…`\n * concatenation happen inside `buildOgPlaceholderUrl`. For the entity-card +\n * onboarding-detail surfaces this is the single entry point — no card builds an\n * og-placeholder URL itself (that was the bug this replaced: each embedder\n * wired a per-surface callback that concatenated the URL, and a host that\n * forgot it rendered a blank slot with no request). (Other server-side OG paths\n * such as the hub's blog og:image generator construct their own URLs and are\n * out of this module's scope.)\n *\n * The base API URL is taken from the endpoints the host already configures:\n * 1. explicit `endpoints.ogPlaceholderUrl`\n * 2. derived from the sibling `endpoints.imageProxyUrlPrefix` (same API base)\n * 3. same-origin relative `/api/og-placeholder`\n * The base may already carry pre-existing query params; they're preserved and\n * `title` (+ dimensions) are layered on top. Per-platform brand colors are NOT\n * baked into this URL — the `/api/og-placeholder` route resolves them\n * server-side from the platform. Most hosts leave `ogPlaceholderUrl` unset and\n * let the base derive from `imageProxyUrlPrefix`.\n */\n\n/** The slice of `ChatRuntime.endpoints` this module needs. */\nexport interface OgPlaceholderEndpoints {\n /** Explicit base URL for the og-placeholder route. May already carry query\n * params — they're preserved. Per-platform colors are NOT baked here; the\n * route resolves them server-side from the platform. */\n ogPlaceholderUrl?: string;\n /** Sibling image route under the SAME API base. When `ogPlaceholderUrl` is\n * unset, the base is derived from this by swapping the trailing\n * `/image-proxy` segment for `/og-placeholder` — so a host that already\n * proxies images gets the placeholder for free, with zero extra wiring. */\n imageProxyUrlPrefix?: string;\n}\n\nexport interface BuildOgPlaceholderOptions {\n /** Site name shown under the title. Skipped when empty. */\n site?: string;\n /** `'wide'` (1200×630, the route default — no `w`/`h` emitted) or\n * `'square'` (1024×1024, for compact 56×56 chat-inline slots). */\n aspect?: 'wide' | 'square';\n /** Explicit pixel overrides (win over `aspect`). */\n width?: number;\n height?: number;\n}\n\n/** Same-origin default — for hosts that serve the route themselves (the hub).\n * Cross-origin embedders override via `ogPlaceholderUrl` or inherit it from\n * `imageProxyUrlPrefix`. */\nconst DEFAULT_OG_PLACEHOLDER_PATH = '/api/og-placeholder';\n\n/** Resolve the og-placeholder route base from the host's endpoints.\n * Internal — callers go through `buildOgPlaceholderUrl(endpoints, …)`. */\nfunction resolveOgPlaceholderBase(endpoints?: OgPlaceholderEndpoints | null): string {\n if (endpoints?.ogPlaceholderUrl) return endpoints.ogPlaceholderUrl;\n const imageProxy = endpoints?.imageProxyUrlPrefix;\n if (imageProxy) {\n // `/image-proxy` and `/og-placeholder` are sibling API routes under one\n // base. Anchor to a path-segment boundary so we only rewrite the route\n // name, never an incidental substring.\n const derived = imageProxy.replace(/\\/image-proxy(?=$|[?/])/, '/og-placeholder');\n if (derived !== imageProxy) return derived;\n }\n return DEFAULT_OG_PLACEHOLDER_PATH;\n}\n\n/**\n * Build the branded og-placeholder image URL from the host's `endpoints` + a\n * title. This is the single entry point for entity-card + onboarding-detail\n * cover fallbacks: it resolves the route base from `endpoints` AND concatenates\n * `title` (+ dimensions), so those consumers never construct a URL themselves.\n *\n * Pure string construction — SSR- and browser-safe. Always returns a usable\n * URL (relative default at worst), so a missing/unknown image degrades\n * gracefully via the `<img onError>` recovery in the card components.\n */\nexport function buildOgPlaceholderUrl(\n endpoints: OgPlaceholderEndpoints | null | undefined,\n title: string,\n options: BuildOgPlaceholderOptions = {},\n): string {\n const base = resolveOgPlaceholderBase(endpoints);\n const qIndex = base.indexOf('?');\n const path = qIndex === -1 ? base : base.slice(0, qIndex);\n const params = new URLSearchParams(qIndex === -1 ? '' : base.slice(qIndex + 1));\n\n params.set('title', title);\n if (options.site) params.set('site', options.site);\n\n // Square aspect → request a 1024×1024 image so `object-cover` doesn't crop\n // the title off in compact slots. Wide leaves dimensions to the route\n // default (1200×630). Explicit width/height always win.\n const width = options.width ?? (options.aspect === 'square' ? 1024 : undefined);\n const height = options.height ?? (options.aspect === 'square' ? 1024 : undefined);\n // `Number.isFinite` does not coerce, so it already rejects `undefined` — no\n // separate `typeof === 'number'` guard needed.\n if (Number.isFinite(width)) params.set('w', String(width));\n if (Number.isFinite(height)) params.set('h', String(height));\n\n return `${path}?${params.toString()}`;\n}\n","'use client';\n\nimport { useMemo } from 'react';\n\nimport { useChatRuntime } from '../contexts/chat-runtime-context';\nimport { buildOgPlaceholderUrl } from '../utils/og-placeholder';\n\n/**\n * Resolve a branded og-placeholder image URL for a title, driven entirely by\n * the runtime `endpoints` (no injected builder).\n *\n * THE one og-placeholder hook. It reads the host's `endpoints` from\n * `ChatRuntime` and hands them to `buildOgPlaceholderUrl`, which resolves the\n * route base (explicit `ogPlaceholderUrl` → derived from `imageProxyUrlPrefix`\n * → same-origin `/api/og-placeholder`) and appends `?title=…`. Per-platform\n * brand colors are resolved SERVER-SIDE by the route — nothing is baked here.\n *\n * Replaces the old builder-injection `useOgPlaceholder(buildUrl, …)`: callers\n * no longer pass a URL builder. `useEntityCardPlaceholder` delegates here too,\n * so every surface shares one memo + one code path.\n */\nexport interface UseOgPlaceholderUrlArgs {\n /** Text to display on the placeholder. */\n title: string | undefined | null;\n /** Site name shown below the title (optional). */\n siteName?: string;\n /** `'wide'` (1200×630 social-card; default) or `'square'` (1024×1024 — for\n * compact chat-inline slots so `object-cover` doesn't crop the title off). */\n aspect?: 'wide' | 'square';\n /** When `false`, returns `null` instead of a URL. */\n enabled?: boolean;\n}\n\nexport function useOgPlaceholderUrl({\n title,\n siteName = '',\n aspect = 'wide',\n enabled = true,\n}: UseOgPlaceholderUrlArgs): string | null {\n const endpoints = useChatRuntime()?.endpoints;\n\n return useMemo(() => {\n if (!enabled || !title) return null;\n return buildOgPlaceholderUrl(endpoints, title, { site: siteName || undefined, aspect });\n }, [endpoints, title, siteName, aspect, enabled]);\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-KTBZJP5J.cjs","../src/components/faq/faq-section.tsx","../src/components/faq-accordion.tsx","../src/components/faq/json-ld.ts","../src/components/faq/faq-document-page.tsx"],"names":["useState","jsx"],"mappings":"AAAA,6rBAAY;AACZ;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;AChCA,8BAAkE;ADkClE;AACA;AEpCA;AA6CY,+CAAA;AA7BL,SAAS,YAAA,CAAa,EAAE,KAAA,EAAO,eAAA,EAAiB,CAAC,EAAE,CAAA,EAAsB;AAC9E,EAAA,MAAM,CAAC,OAAA,EAAS,UAAU,EAAA,EAAI,6BAAA,IAAmC,GAAA,CAAI,cAAc,CAAC,CAAA;AAEpF,EAAA,MAAM,OAAA,EAAS,CAAC,EAAA,EAAA,GAAwB;AACtC,IAAA,UAAA,CAAW,CAAA,IAAA,EAAA,GAAQ;AACjB,MAAA,MAAM,KAAA,EAAO,IAAI,GAAA,CAAI,IAAI,CAAA;AACzB,MAAA,GAAA,CAAI,IAAA,CAAK,GAAA,CAAI,EAA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EAAA;AACA,EAAA;AACa,EAAA;AACb,EAAA;AACA,EAAA;AACA,EAAA;AACa,EAAA;AACK;AACmD,EAAA;AAGjD,EAAA;AAC2B,IAAA;AACjC,IAAA;AACd,EAAA;AACkF,EAAA;AAIzB,EAAA;AAEwB,EAAA;AAMxC,EAAA;AAIvB,EAAA;AAC0B,EAAA;AACR,EAAA;AAG7B,IAAA;AAGP,EAAA;AAEmE,EAAA;AAI/D,EAAA;AACG,oBAAA;AAAA,MAAA;AAC8D,sBAAA;AACjE,IAAA;AAEEA,IAAAA;AAAC,MAAA;AAAA,MAAA;AACM,QAAA;AAGsD,QAAA;AAAA,MAAA;AAC7D,IAAA;AAEJ,EAAA;AAEJ;ADlGoF;AACA;AItO9E;AA5B0B;AACtB,EAAA;AACR,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACQ,EAAA;AACe;AACE,EAAA;AAQnB,EAAA;AAC8B,IAAA;AACsB,IAAA;AACpD,EAAA;AAGsD,EAAA;AACvD,IAAA;AAAA,IAAA;AACC,MAAA;AACS,MAAA;AACT,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AAAA,IAAA;AAEJ,EAAA;AAG8C,EAAA;AAClD;AJ2PoF;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-KTBZJP5J.cjs","sourcesContent":[null,"'use client';\n\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useScrollToHash } from '../../hooks/use-scroll-to-hash';\nimport { useSelfFetch } from '../../hooks/use-self-fetch';\nimport type { Faq } from '../../types/faq';\nimport { cn } from '../../utils/cn';\nimport { serializeJsonLd } from '../../utils/common';\nimport { faqSectionSlug, parseFaqHash, type FaqHashTarget } from '../../utils/faq-anchor';\nimport { navigateSamePageHash, STICKY_HEADER_OFFSET_PX } from '../../utils/same-page-hash-nav';\nimport { buildSuggestionUrl } from '../../utils/suggestion-url';\nimport { FaqAccordion, type FaqItem } from '../faq-accordion';\nimport { SECTION_HEADING_CLASS } from '../layout/page-heading';\nimport { buildFaqJsonLdFromFaqs, type FaqSchemaOptions } from './json-ld';\n\nexport interface FaqSectionProps {\n /**\n * SSR hydrate. When provided, the hook skips the first client fetch (per\n * useSelfFetch contract). The consuming server page resolves FAQs then drills\n * them into this prop — the lib never re-fetches what the host already gated on.\n */\n initialFaqs?: Faq[];\n /** Both required together for entity-attached FAQs; partial → bare /api/faqs. */\n entityType?: string;\n entityId?: number | string;\n /**\n * Heading node above the grouped list. `undefined` → default\n * `<h2>`\"Frequently Asked Questions\". `null` → no heading (the host page\n * owns the `<h1>`, as the standalone /faqs surface does). A React node lets a\n * platform drill its own <PageHeading> without the lib referencing platform\n * state. Also drives category nesting so the document outline stays correct:\n * `null` → categories render `<h2>` (directly under the page `<h1>`);\n * otherwise categories render `<h3>` beneath this heading.\n */\n heading?: React.ReactNode | null;\n /** Inject FAQPage schema.org JSON-LD as a <script>. Off by default so embeds\n * don't emit duplicate schema. */\n emitJsonLd?: boolean;\n /** Overrides for the JSON-LD's name/description/url. */\n jsonLd?: FaqSchemaOptions;\n className?: string;\n /** Maps to /api/faqs `?count=` (the 5-tier fill target). Absent → param\n * not sent (server default applies). */\n minResults?: number;\n /** Fetch-URL prefix for third-party embeds / reverse proxies\n * ('' = same-origin relative). */\n apiBaseUrl?: string;\n}\n\nconst DEFAULT_HEADING_TEXT = 'Frequently Asked Questions';\n\n/** URL composition shared with RelatedContentSection (`buildSuggestionUrl`)\n * — byte-identical to the historical `buildFaqsUrl` output when\n * `minResults`/`apiBaseUrl` are absent. */\nfunction buildFaqsUrl(entityType?: string, entityId?: number | string, minResults?: number, apiBaseUrl = ''): string {\n return buildSuggestionUrl('/api/faqs', { apiBaseUrl, entityType, entityId, count: minResults });\n}\n\ninterface FaqGroup {\n /** null → the uncategorized bucket: no heading, no jump pill, rendered last. */\n section: string | null;\n slug: string | null;\n items: FaqItem[];\n}\n\n/** Group FAQs by `faq.section`, preserving the server's first-seen\n * (display_order) order for BOTH the section order and the rows within each\n * section. The uncategorized bucket (blank/missing section) sinks to the end\n * since it renders without a heading. Items carry NO badge here — the `<h2>`\n * IS the category, so a per-row chip would be redundant. */\nfunction groupFaqsBySection(faqs: Faq[]): FaqGroup[] {\n // A Map iterates in insertion order, which is exactly the first-seen section\n // order this function promises — so the Map IS the ordering, and no parallel\n // array of names (plus a lookup that has to assert the key back) is needed.\n const byName = new Map<string, FaqGroup>();\n let uncategorized: FaqGroup | null = null;\n for (const faq of faqs) {\n const item: FaqItem = { id: faq.id, question: faq.question, answer: faq.answer };\n const name = faq.section?.trim();\n if (!name) {\n if (!uncategorized) uncategorized = { section: null, slug: null, items: [] };\n uncategorized.items.push(item);\n continue;\n }\n let group = byName.get(name);\n if (!group) {\n group = { section: name, slug: faqSectionSlug(name), items: [] };\n byName.set(name, group);\n }\n group.items.push(item);\n }\n const groups = [...byName.values()];\n if (uncategorized) groups.push(uncategorized);\n return groups;\n}\n\n/** Map key for the uncategorized bucket — `group.slug` is null for it, so\n * every per-group map (default-open ids, accordion keys) uses this sentinel\n * to keep the lookup typed. */\nconst UNCATEGORIZED_KEY = '__uncategorized__';\nconst groupKey = (g: FaqGroup): string => g.slug ?? UNCATEGORIZED_KEY;\n\n/**\n * Grouped FAQ layout: a category jump-nav above stacked `<h2>` category\n * sections (each its own accordion). Isolated into its own component so the\n * scroll-spy hooks only mount in grouped mode — `FaqSection`'s own hooks stay\n * unconditional.\n *\n * The pills are real `<a href=\"#slug\">` anchors (crawlable in-page links,\n * deep-linkable, work without JS); the click handler upgrades the jump to the\n * cancellation-proof `scrollElementIntoView` tween and syncs the URL hash.\n */\nfunction GroupedFaqList({\n groups,\n categoryHeadingAs,\n}: {\n groups: FaqGroup[];\n /** Heading tag for each category, so the document outline nests correctly\n * under whatever owns the heading above this block: `h2` on the standalone\n * page (the page owns the `<h1>`), `h3` beneath an embed's `<h2>` title.\n * The VISUAL is `SECTION_HEADING_CLASS` either way, so categories look\n * identical on every surface. */\n categoryHeadingAs: 'h2' | 'h3';\n}) {\n const CategoryHeading = categoryHeadingAs;\n const navGroups = useMemo(() => groups.filter(g => g.slug), [groups]);\n const [activeSlug, setActiveSlug] = useState<string | null>(navGroups[0]?.slug ?? null);\n // Identity-stable key for the section set so the observer re-binds only when\n // the categories actually change (not on every parent re-render).\n const slugKey = navGroups.map(g => g.slug).join('|');\n // Latest `navGroups` for the scroll-spy observer below, which re-observes on\n // `slugKey` (the section SET) and must not re-run when the array is merely\n // rebuilt with the same slugs.\n const navGroupsRef = useRef(navGroups);\n useEffect(() => {\n navGroupsRef.current = navGroups;\n });\n\n // Scroll-spy: mark the pill for the category currently at the top of the\n // viewport. rootMargin drops the trigger line just below the sticky header\n // and ignores the bottom ~55% so \"active\" is the section being read, not the\n // next one peeking in.\n useEffect(() => {\n if (navGroupsRef.current.length < 2) return undefined;\n const tops = new Map<string, number>();\n const observer = new IntersectionObserver(\n entries => {\n for (const entry of entries) {\n const id = (entry.target as HTMLElement).id;\n if (entry.isIntersecting) tops.set(id, entry.boundingClientRect.top);\n else tops.delete(id);\n }\n let bestId: string | null = null;\n let bestTop = Number.POSITIVE_INFINITY;\n for (const [id, top] of tops) {\n if (top < bestTop) {\n bestTop = top;\n bestId = id;\n }\n }\n if (bestId) setActiveSlug(bestId);\n },\n { rootMargin: `-${STICKY_HEADER_OFFSET_PX}px 0px -55% 0px`, threshold: 0 },\n );\n for (const group of navGroupsRef.current) {\n const el = group.slug ? document.getElementById(group.slug) : null;\n if (el) observer.observe(el);\n }\n return () => observer.disconnect();\n // slugKey encodes the section set; re-observe only when it changes.\n }, [slugKey]);\n\n // ─── Hash dispatch — `/faqs#faq-item-<id>` or `/faqs#faq-<section-slug>` ──\n // Tracks the current hash so:\n // 1. an item-kind hash seeds `defaultOpenIds` on the matching accordion\n // (auto-expands the cited question);\n // 2. either kind triggers the cancellation-proof tween scroll with the\n // sticky-header offset (native browser hash scroll runs once, ignores\n // our offset — re-running the tween puts the target in the right spot).\n // Listens to `hashchange` so back/forward replays the same behavior. SSR-\n // safe: initial null state matches the server render; the first effect\n // tick on the client updates it.\n const [hashTarget, setHashTarget] = useState<FaqHashTarget | null>(null);\n useEffect(() => {\n const refresh = () => setHashTarget(parseFaqHash(window.location.hash));\n refresh();\n window.addEventListener('hashchange', refresh);\n return () => window.removeEventListener('hashchange', refresh);\n }, []);\n\n // Per-group default-open set when the hash points at an item. The map key\n // matches `groupKey(group)` so the render-time lookup is O(1) per group.\n const defaultOpenByGroupKey = useMemo(() => {\n if (hashTarget?.kind !== 'item') return null;\n const targetId = hashTarget.rawId;\n const result = new Map<string, (string | number)[]>();\n for (const group of groups) {\n const hit = group.items.find(i => String(i.id) === targetId);\n if (hit) result.set(groupKey(group), [hit.id]);\n }\n return result.size > 0 ? result : null;\n }, [groups, hashTarget]);\n\n // Accordion is uncontrolled — `defaultOpenIds` is only consumed at mount,\n // so a new item hash needs a remount to honor it. Keying off the item-id\n // suffix triggers exactly the remount we need (and stays stable when the\n // hash points at a section, so category navigation never disturbs the\n // accordion's open state).\n const accordionKeySuffix = hashTarget?.kind === 'item' ? `item:${hashTarget.rawId}` : 'default';\n\n // Unified scroll-to-hash: rAF-polls for the target row (outlasts the SWR self-fetch\n // + Radix accordion expand) and re-fires on `hashchange` — including the synthetic\n // event `navigateSamePageHash` dispatches for a SOFT same-page chat-card nav (a\n // host-router `pushState` fires no `hashchange`). The ready-dep keys off BOTH the\n // loaded `groups` (so a deep-link / refresh scrolls once the self-fetched list\n // mounts) AND `hashTarget` (so a soft nav re-runs the scroll AFTER the re-render\n // that remounts + opens the cited row, landing on its FINAL expanded position\n // instead of racing the uncontrolled accordion's key-remount — the bare-`hashchange`\n // listener alone fires before the remount and lands on the stale closed position).\n const scrollDep =\n `${groups.length}|` +\n (hashTarget?.kind === 'item'\n ? `item:${hashTarget.rawId}`\n : hashTarget?.kind === 'section'\n ? `section:${hashTarget.slug}`\n : 'none');\n useScrollToHash(scrollDep, { headerOffset: STICKY_HEADER_OFFSET_PX });\n\n // A section hash also lights up its category pill; item hashes leave the pills\n // untouched so deep-linking a question never disturbs scroll-spy state.\n //\n // Adjusted while rendering (React's prop-sync pattern) rather than from an\n // effect: the pills below read `activeSlug` in THIS render, so an effect\n // painted the OLD pill lit and then re-rendered to move the highlight. The\n // initial value matches `hashTarget`'s own initial `null`, so a mount is a\n // no-op here exactly as the effect's first run was.\n const [pillSyncedHash, setPillSyncedHash] = useState(hashTarget);\n if (pillSyncedHash !== hashTarget) {\n setPillSyncedHash(hashTarget);\n if (hashTarget?.kind === 'section') setActiveSlug(hashTarget.slug);\n }\n\n // Category pill click. `navigateSamePageHash` owns the entire transition:\n // replaceState → synthetic `hashchange` → `scrollElementIntoView` tween\n // with `STICKY_HEADER_OFFSET_PX` so the section heading lands BELOW the\n // sticky category nav on the FIRST tween (covers the same-target\n // re-click case, where the `hashTarget` effect at L214 is a no-op\n // because the state reference is equal). For DIFFERENT-target clicks\n // the helper's synthetic `hashchange` re-fires that effect, which\n // re-scrolls with the same offset and cancels this tween (singleton)\n // — both paths land at the same position. The effect is still\n // required for back/forward + direct URL edits, where the helper\n // isn't in the call chain.\n //\n // `history: 'replace'` matches the pre-helper behavior: category pills\n // are a TOC, not a navigation step, so the Back button leaves the\n // FAQ page in one step regardless of how many categories the user\n // clicked through.\n const handleJump = useCallback((e: React.MouseEvent<HTMLAnchorElement>, slug: string) => {\n e.preventDefault();\n navigateSamePageHash('#' + slug, {\n headerOffset: STICKY_HEADER_OFFSET_PX,\n history: 'replace',\n });\n }, []);\n\n return (\n <div className=\"space-y-8\">\n {navGroups.length > 1 && (\n <nav aria-label=\"FAQ categories\" className=\"flex flex-wrap gap-2\">\n {navGroups.map(group => {\n const isActive = group.slug === activeSlug;\n return (\n <a\n key={group.slug}\n href={`#${group.slug}`}\n aria-current={isActive ? 'true' : undefined}\n onClick={e => handleJump(e, group.slug as string)}\n className={cn(\n 'rounded-full border px-4 py-2 transition-colors text-h6',\n isActive\n ? 'border-ods-text-primary bg-ods-card text-ods-text-primary'\n : 'border-ods-border bg-ods-card text-ods-text-secondary hover:border-ods-text-secondary hover:text-ods-text-primary',\n )}\n >\n {group.section}\n </a>\n );\n })}\n </nav>\n )}\n <div className=\"space-y-10\">\n {groups.map(group => {\n const key = groupKey(group);\n return (\n <section key={key} id={group.slug ?? undefined} className=\"scroll-mt-24 space-y-4\">\n {group.section && <CategoryHeading className={SECTION_HEADING_CLASS}>{group.section}</CategoryHeading>}\n <FaqAccordion\n // Re-key on item-hash changes so the remount picks up the new\n // `defaultOpenIds` (the accordion is uncontrolled). Stable for\n // section hashes — category navigation doesn't disturb state.\n key={`${key}:${accordionKeySuffix}`}\n items={group.items}\n defaultOpenIds={defaultOpenByGroupKey?.get(key)}\n />\n </section>\n );\n })}\n </div>\n </div>\n );\n}\n\nfunction FaqSkeleton() {\n return (\n <div className=\"animate-pulse space-y-8\">\n <div className=\"h-12 w-2/3 rounded bg-ods-border md:h-14\" />\n <div className=\"w-full divide-y divide-ods-border overflow-hidden rounded-md border border-ods-border bg-transparent\">\n {Array.from({ length: 8 }).map((_, idx) => (\n <div key={idx} className=\"flex items-center justify-between gap-6 px-6 py-4 md:gap-10\">\n <div className=\"h-6 w-5/6 rounded bg-ods-border\" />\n <div className=\"size-6 rounded bg-ods-border\" />\n </div>\n ))}\n </div>\n </div>\n );\n}\n\ninterface FaqsResponse {\n faqs: Faq[];\n}\n\n/**\n * The FAQ display surface — ONE rendering on every host: the list grouped by\n * `faq.section` (each category a heading + its own accordion, with a category\n * jump-nav once there are 2+ categories). There is no flat/ungrouped mode and\n * no page-vs-embedded shell fork; the standalone /faqs page and every embed\n * render through this single path, so they cannot drift.\n *\n * - Standalone /faqs page: pass `initialFaqs` (SSR) + `heading={null}` (the\n * page owns the <h1>) + `emitJsonLd` with `jsonLd` overrides for SEO.\n * - Per-entity embed: pass `entityType` + `entityId` (no `initialFaqs`); the\n * hook self-fetches `GET /api/faqs`, and `heading` is this block's own <h2>.\n *\n * CONTRACT: the consuming app MUST implement `GET /api/faqs`. On a fetch error\n * (or zero FAQs) the component renders nothing so the host page isn't\n * disfigured. The host always supplies the page shell — this renders a bare\n * <section>.\n */\nexport function FaqSection({\n initialFaqs,\n entityType,\n entityId,\n heading,\n emitJsonLd = false,\n jsonLd,\n className,\n minResults,\n apiBaseUrl = '',\n}: FaqSectionProps) {\n const url = buildFaqsUrl(entityType, entityId, minResults, apiBaseUrl);\n // Memoized — useSelfFetch re-syncs on [initialData]; a fresh per-render\n // wrapper object would setState-loop under re-rendering parents.\n const initialData = useMemo<FaqsResponse | undefined>(\n () => (initialFaqs ? { faqs: initialFaqs } : undefined),\n [initialFaqs],\n );\n const { data, isLoading, error } = useSelfFetch<FaqsResponse>(url, { initialData });\n\n // Memoised because the `??` fallback minted a NEW array on every\n // render, which made the memo below re-run every time — i.e. do nothing.\n const faqs = useMemo(() => data?.faqs ?? [], [data?.faqs]);\n // Grouped before the early returns so the hook order stays stable.\n const groups = useMemo(() => (faqs.length > 0 ? groupFaqsBySection(faqs) : []), [faqs]);\n\n // `undefined` → default <h2> title; `null` → the host page owns the <h1>, so\n // no title renders here. `heading === null` also makes the category headings\n // <h2> (directly under the page <h1>); otherwise they nest as <h3>.\n const headingNode =\n heading === undefined ? <h2 className={SECTION_HEADING_CLASS}>{DEFAULT_HEADING_TEXT}</h2> : heading;\n\n // Degrade silently — never show an error banner or an empty section shell\n // where FAQs would be (host pages and the standalone surface both rely on it).\n if (error) return null;\n if (!isLoading && faqs.length === 0) return null;\n if (isLoading && faqs.length === 0) {\n return (\n <div className={className}>\n <FaqSkeleton />\n </div>\n );\n }\n\n const schema = emitJsonLd ? buildFaqJsonLdFromFaqs(faqs, jsonLd) : null;\n\n return (\n <>\n <section className={className ?? 'space-y-10'}>\n {headingNode}\n <GroupedFaqList groups={groups} categoryHeadingAs={heading === null ? 'h2' : 'h3'} />\n </section>\n {schema && (\n <script\n type=\"application/ld+json\"\n // serializeJsonLd, NOT raw JSON.stringify — FAQ answers are\n // admin-entered; an embedded \"</script>\" must not break the tag.\n dangerouslySetInnerHTML={{ __html: serializeJsonLd(schema) }}\n />\n )}\n </>\n );\n}\n","'use client';\n\nimport { useState } from 'react';\nimport { cn } from '../utils/cn';\nimport { faqItemAnchor } from '../utils/faq-anchor';\nimport { Chevron02DownIcon } from './icons-v2-generated/arrows/chevron-02-down-icon';\n\nexport interface FaqItem {\n id: number | string;\n question: string;\n answer: string;\n}\n\ninterface FaqAccordionProps {\n items: FaqItem[];\n defaultOpenIds?: (number | string)[];\n}\n\nexport function FaqAccordion({ items, defaultOpenIds = [] }: FaqAccordionProps) {\n const [openSet, setOpenSet] = useState<Set<string | number>>(new Set(defaultOpenIds));\n\n const toggle = (id: string | number) => {\n setOpenSet(prev => {\n const next = new Set(prev);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n return next;\n });\n };\n\n return (\n <div className=\"divide-y divide-ods-border overflow-hidden rounded-md border border-ods-border bg-transparent\">\n {items.map(item => {\n const isOpen = openSet.has(item.id);\n\n return (\n <div\n key={item.id}\n // Per-row anchor — chat citation chips (`/faqs#faq-item-<id>`) land\n // here via native browser hash scroll AND via `FaqSection`'s tween\n // dispatch. `scroll-mt-24` keeps the row header below the 96px\n // sticky nav offset (matches `<section>`'s scroll-margin for\n // category anchors).\n id={faqItemAnchor(item.id)}\n className=\"scroll-mt-24 transition-colors hover:bg-ods-bg-hover\"\n >\n {/* Header */}\n <div\n role=\"button\"\n tabIndex={0}\n onClick={() => toggle(item.id)}\n onKeyDown={e => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n toggle(item.id);\n }\n }}\n aria-expanded={isOpen}\n className=\"flex w-full cursor-pointer items-center gap-6 px-6 py-4 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ods-focus md:gap-10\"\n >\n <h3 className=\"min-w-0 flex-1 break-words\">{item.question}</h3>\n <Chevron02DownIcon\n aria-hidden=\"true\"\n size={24}\n className={cn(\n 'shrink-0 text-ods-text-primary transition-transform duration-300',\n isOpen && 'rotate-180',\n )}\n />\n </div>\n {/* Content wrapper. Collapses with the grid 1fr->0fr transition the\n rest of the design system uses (see AnnouncementBar) rather than\n an animated max-height: measuring `scrollHeight` needed a hook\n PER ROW, which meant calling hooks inside `items.map` — the hook\n order then changed whenever `items` did. Grid needs no\n measurement, and it animates correctly when an answer's height\n changes after mount. */}\n <div\n className=\"grid transition-[grid-template-rows,opacity] duration-300 ease-in-out motion-reduce:transition-none\"\n style={{ gridTemplateRows: isOpen ? '1fr' : '0fr', opacity: isOpen ? 1 : 0 }}\n >\n {/* break-words: FAQ answers render as plain text, so a long URL or\n token has no wrap opportunity — and the row is overflow-hidden,\n which would CLIP it past the viewport on mobile. Mirrors the\n markdown-renderer overflow-wrap fix. */}\n <div className=\"overflow-hidden\">\n <div className=\"break-words px-6 pb-4 text-ods-text-primary text-h4\">{item.answer}</div>\n </div>\n </div>\n </div>\n );\n })}\n </div>\n );\n}\n","/**\n * Pure FAQ JSON-LD builder. No React, no client-only deps — safe to import from\n * Server Components via the `./components/faq` subpath export. (Do NOT import\n * through the root `./components` barrel — that barrel is `\"use client\"` and\n * dragging it into a Server Component would force the client graph into the\n * server.)\n *\n * The hub used to harcode `name`/`description` here for OpenMSP; in the lib we\n * accept overrides so every embedder can supply its own platform branding.\n */\nimport type { Faq } from '../../types/faq';\n\nexport interface FaqSchemaOptions {\n name?: string;\n description?: string;\n url?: string;\n}\n\nconst DEFAULT_NAME = 'Frequently Asked Questions';\nconst DEFAULT_DESCRIPTION = 'Answers to common questions.';\n\nexport function baseFaqSchema(opts: FaqSchemaOptions = {}) {\n return {\n '@context': 'https://schema.org',\n '@type': 'FAQPage',\n name: opts.name ?? DEFAULT_NAME,\n description: opts.description ?? DEFAULT_DESCRIPTION,\n ...(opts.url ? { url: opts.url } : {}),\n } as const;\n}\n\nexport function buildFaqJsonLdFromFaqs(faqs: Faq[], opts: FaqSchemaOptions = {}) {\n return {\n ...baseFaqSchema(opts),\n mainEntity: faqs.map(faq => ({\n '@type': 'Question',\n name: faq.question,\n acceptedAnswer: {\n '@type': 'Answer',\n text: faq.answer,\n },\n })),\n } as const;\n}\n","'use client';\n\n/**\n * FaqDocumentPage — the full `/faqs` page with chrome, so embedders drop in\n * ONE component instead of hand-assembling `PageShell` + `PageLayout` around\n * the bare `<FaqSection>`. Mirrors `LegalDocumentPage` / `DevSectionPage`: the\n * page-level layout lives in the lib, the host page is a thin wrapper that\n * passes only config + the SSR-resolved data.\n *\n * HERO: the title + subtitle route through the canonical (frozen) `PageLayout`\n * `TitleBlock` with `titleSize=\"h1\"` — the unified Help Center header (the\n * `TitleBlock` element is always an `<h1>`; `titleSize` only sets its typography,\n * here `text-h1`). The page owns that `<h1>`, so `<FaqSection heading={null}>`\n * nests its category headings as `<h2>`/`<h3>` (the SEO-recommended FAQ document\n * outline).\n *\n * DATA: pass `initialFaqs` (SSR-resolved, platform-scoped) so `FaqSection`\n * skips its client self-fetch — the standalone page's static platform-only\n * contract. Omit it for embeds that want the self-fetching `/api/faqs`\n * suggestion-fill instead.\n */\n\nimport { useRouter } from '../../embed-shims/next-navigation';\nimport type { Faq } from '../../types/faq';\nimport { PageShell, PageLayout } from '../ui';\nimport { FaqSection } from './faq-section';\nimport type { FaqSchemaOptions } from './json-ld';\n\nexport interface FaqDocumentPageProps {\n /** Page title (frozen `PageLayout` `TitleBlock`). Default \"Frequently Asked Questions\". */\n title?: string;\n /** Subtitle under the title. */\n subtitle?: string;\n /** Back-button config — same pattern as `DevSectionPage` / `LegalDocumentPage`.\n * Pass `false` to hide. Default `{ label: 'Back to home', href: '/' }`. */\n backButton?: { label?: string; href?: string } | false;\n /** Render the standalone `<PageShell>` (own `<main>` + bg + max-width). Default\n * true. Pass false when the host layout already provides the page container\n * (e.g. openframe-frontend's `AppLayout` `<main>`) — only the padding box\n * renders, avoiding a nested `<main>`. */\n shell?: boolean;\n /** SSR-hydrate `FaqSection` (skips the client fetch — the platform-only\n * contract for the standalone page). Omit for self-fetching embeds. */\n initialFaqs?: Faq[];\n /** Emit FAQPage schema.org JSON-LD (forwarded to `FaqSection`). Off by\n * default so embeds don't emit duplicate schema. */\n emitJsonLd?: boolean;\n /** JSON-LD name/description/url overrides (forwarded to `FaqSection`). */\n jsonLd?: FaqSchemaOptions;\n /** Base URL `FaqSection` appends `/api/faqs` to (reverse-proxy embedders). */\n apiBaseUrl?: string;\n /** Optional entity scoping forwarded to `FaqSection`. */\n entityType?: string;\n entityId?: number | string;\n /** Minimum FAQ count before the section renders (forwarded to `FaqSection`). */\n minResults?: number;\n}\n\nexport function FaqDocumentPage({\n title = 'Frequently Asked Questions',\n subtitle,\n backButton,\n initialFaqs,\n emitJsonLd,\n jsonLd,\n apiBaseUrl,\n entityType,\n entityId,\n minResults,\n shell = true,\n}: FaqDocumentPageProps) {\n const router = useRouter();\n\n // Back-button config — mirrors LegalDocumentPage / DevSectionPage. Hide\n // entirely when the caller passes `false` (embed-mode where the host owns\n // nav chrome).\n const backCfg =\n backButton === false\n ? undefined\n : {\n label: backButton?.label ?? 'Back to home',\n onClick: () => router.push(backButton?.href ?? '/'),\n };\n\n const inner = (\n <PageLayout title={title} subtitle={subtitle} backButton={backCfg} titleSize=\"h1\" titleWrap>\n <FaqSection\n initialFaqs={initialFaqs}\n heading={null}\n emitJsonLd={emitJsonLd}\n jsonLd={jsonLd}\n apiBaseUrl={apiBaseUrl}\n entityType={entityType}\n entityId={entityId}\n minResults={minResults}\n />\n </PageLayout>\n );\n\n return shell ? <PageShell>{inner}</PageShell> : <div className=\"page-shell-content\">{inner}</div>;\n}\n"]}
|