@flamingo-stack/openframe-frontend-core 0.0.626 → 0.0.627-2168.6177.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-63F2UQDW.cjs → chunk-2RWADKBR.cjs} +18 -18
- package/dist/{chunk-63F2UQDW.cjs.map → chunk-2RWADKBR.cjs.map} +1 -1
- package/dist/{chunk-X3LC6R37.js → chunk-32P6KUZP.js} +2 -2
- package/dist/{chunk-RVK3CL5S.js → chunk-3D45OAWL.js} +12 -12
- package/dist/{chunk-EHAYNUOL.cjs → chunk-4E7XCEV3.cjs} +77 -2
- package/dist/chunk-4E7XCEV3.cjs.map +1 -0
- package/dist/{chunk-L54LFB6V.cjs → chunk-5P3V6VFN.cjs} +15 -15
- package/dist/{chunk-L54LFB6V.cjs.map → chunk-5P3V6VFN.cjs.map} +1 -1
- package/dist/{chunk-2CCIF5QV.js → chunk-5YT6NGPV.js} +10 -8
- package/dist/{chunk-2CCIF5QV.js.map → chunk-5YT6NGPV.js.map} +1 -1
- 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-VOBOO7EF.cjs → chunk-76SF25HQ.cjs} +83 -83
- package/dist/{chunk-VOBOO7EF.cjs.map → chunk-76SF25HQ.cjs.map} +1 -1
- package/dist/{chunk-DLZFFGQ7.js → chunk-AGYKSJSE.js} +4 -4
- package/dist/{chunk-34GEH24Y.cjs → chunk-AONK75QT.cjs} +22 -20
- package/dist/chunk-AONK75QT.cjs.map +1 -0
- package/dist/{chunk-IJYP2DMW.js → chunk-B2DCZVUN.js} +8 -354
- package/dist/chunk-B2DCZVUN.js.map +1 -0
- package/dist/{chunk-QR2FJE2C.js → chunk-C6TNAYHO.js} +12 -12
- package/dist/{chunk-YQCA4ZEJ.js → chunk-CMUNJZWN.js} +2 -2
- package/dist/{chunk-F4TAUCHQ.js → chunk-CSP4GOQ2.js} +3 -3
- package/dist/{chunk-3LKJ6JWZ.cjs → chunk-DCBDNYYW.cjs} +34 -34
- package/dist/{chunk-3LKJ6JWZ.cjs.map → chunk-DCBDNYYW.cjs.map} +1 -1
- package/dist/{chunk-Z42VU7HF.cjs → chunk-DGYDHQWL.cjs} +49 -47
- package/dist/chunk-DGYDHQWL.cjs.map +1 -0
- package/dist/{chunk-QPQCQWAW.cjs → chunk-EAPER4P2.cjs} +28 -26
- package/dist/chunk-EAPER4P2.cjs.map +1 -0
- package/dist/{chunk-HTIDXF43.cjs → chunk-EH5BWSOS.cjs} +7 -7
- package/dist/{chunk-HTIDXF43.cjs.map → chunk-EH5BWSOS.cjs.map} +1 -1
- package/dist/{chunk-H7KQM3VI.js → chunk-FNT5JQDQ.js} +8 -8
- package/dist/{chunk-KK7YEVTQ.js → chunk-FRDSHK7F.js} +4 -4
- package/dist/{chunk-Q5XGBLT5.cjs → chunk-GESNG4HT.cjs} +509 -87
- package/dist/chunk-GESNG4HT.cjs.map +1 -0
- package/dist/{chunk-IZG3VYDV.js → chunk-GKCQIJE7.js} +4 -4
- package/dist/{chunk-E7YNDGRN.cjs → chunk-GNASINHO.cjs} +105 -105
- package/dist/{chunk-E7YNDGRN.cjs.map → chunk-GNASINHO.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-QJ6BCSFQ.cjs → chunk-LAYQ3VUW.cjs} +5 -5
- package/dist/{chunk-QJ6BCSFQ.cjs.map → chunk-LAYQ3VUW.cjs.map} +1 -1
- package/dist/{chunk-ESSHEVZQ.cjs → chunk-MFHGLBCL.cjs} +38 -38
- package/dist/chunk-MFHGLBCL.cjs.map +1 -0
- package/dist/{chunk-S43SLJIN.cjs → chunk-MVPPH4EZ.cjs} +25 -25
- package/dist/{chunk-S43SLJIN.cjs.map → chunk-MVPPH4EZ.cjs.map} +1 -1
- package/dist/{chunk-WEDSYUSR.js → chunk-ONTFCKVK.js} +6 -6
- package/dist/{chunk-3POP5WWC.cjs → chunk-P32VEWOW.cjs} +6 -6
- package/dist/{chunk-3POP5WWC.cjs.map → chunk-P32VEWOW.cjs.map} +1 -1
- 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-RGMUA4XB.js → chunk-PDFHLSPP.js} +7 -7
- package/dist/{chunk-MZWSJPDZ.js → chunk-QBX4BI5E.js} +16 -28
- package/dist/{chunk-MZWSJPDZ.js.map → chunk-QBX4BI5E.js.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-P7KIFYZI.js → chunk-QPHOTZDX.js} +10 -8
- package/dist/{chunk-P7KIFYZI.js.map → chunk-QPHOTZDX.js.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-BVCWBA2U.js → chunk-RD627HGV.js} +817 -395
- package/dist/chunk-RD627HGV.js.map +1 -0
- package/dist/{chunk-NLVBO3IR.js → chunk-RFM6NMF7.js} +10 -8
- package/dist/{chunk-NLVBO3IR.js.map → chunk-RFM6NMF7.js.map} +1 -1
- package/dist/{chunk-NZJNXGU2.cjs → chunk-S3WX4GNN.cjs} +280 -292
- package/dist/chunk-S3WX4GNN.cjs.map +1 -0
- package/dist/{chunk-RQQAPCOU.js → chunk-STRI4K3F.js} +3 -3
- package/dist/{chunk-LJ7KMQRM.cjs → chunk-T3HJAG5Y.cjs} +42 -42
- package/dist/{chunk-LJ7KMQRM.cjs.map → chunk-T3HJAG5Y.cjs.map} +1 -1
- package/dist/{chunk-DZ7CEES3.js → chunk-TIPGW4JM.js} +5 -5
- package/dist/{chunk-DZ7CEES3.js.map → chunk-TIPGW4JM.js.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-MSVEZB5D.cjs → chunk-W54VLUS5.cjs} +279 -625
- package/dist/chunk-W54VLUS5.cjs.map +1 -0
- package/dist/{chunk-F2KBCLUG.js → chunk-X5NN4NJM.js} +2 -2
- package/dist/{chunk-CPO5KPW6.cjs → chunk-XDZIHPF2.cjs} +9 -9
- package/dist/{chunk-CPO5KPW6.cjs.map → chunk-XDZIHPF2.cjs.map} +1 -1
- package/dist/{chunk-ZIEYC6ZB.js → chunk-YDZ5S3Z2.js} +4 -4
- 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/components/case-studies/index.cjs +14 -14
- package/dist/components/case-studies/index.js +8 -8
- package/dist/components/chat/entity-cards/ai-prompt-card.d.ts +2 -1
- package/dist/components/chat/entity-cards/ai-prompt-card.d.ts.map +1 -1
- package/dist/components/chat/entity-cards/employee-entry-card.d.ts +3 -3
- package/dist/components/chat/entity-cards/employee-entry-card.d.ts.map +1 -1
- package/dist/components/chat/entity-cards/entity-author-card.d.ts +8 -6
- package/dist/components/chat/entity-cards/entity-author-card.d.ts.map +1 -1
- 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/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 +75 -69
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.js +30 -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/card-registry.d.ts.map +1 -1
- 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 +21 -0
- package/dist/components/ui/department-badge.d.ts.map +1 -0
- package/dist/components/ui/index.cjs +14 -8
- package/dist/components/ui/index.cjs.map +1 -1
- package/dist/components/ui/index.d.ts +2 -0
- package/dist/components/ui/index.d.ts.map +1 -1
- package/dist/components/ui/index.js +13 -7
- package/dist/components/ui/palette-badge.d.ts +18 -0
- package/dist/components/ui/palette-badge.d.ts.map +1 -0
- package/dist/hooks/index.cjs +5 -5
- package/dist/hooks/index.js +4 -4
- package/dist/index.cjs +28 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +50 -40
- package/dist/index.js.map +1 -1
- package/dist/types/department.d.ts +4 -0
- package/dist/types/department.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 +32 -0
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +30 -1
- package/dist/utils/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/chat/entity-cards/ai-prompt-card.tsx +7 -4
- package/src/components/chat/entity-cards/employee-entry-card.tsx +21 -24
- package/src/components/chat/entity-cards/entity-author-card.tsx +10 -4
- package/src/components/related-content/card-registry.tsx +3 -1
- package/src/components/ui/.department-badge.md +2 -0
- package/src/components/ui/.palette-badge.md +2 -0
- package/src/components/ui/__tests__/department-badge.test.tsx +40 -0
- package/src/components/ui/color-preset-select.tsx +5 -21
- package/src/components/ui/department-badge.tsx +35 -0
- package/src/components/ui/index.ts +2 -0
- package/src/components/ui/palette-badge.tsx +35 -0
- package/src/types/department.ts +4 -0
- package/src/utils/.color-presets.md +2 -0
- package/src/utils/color-presets.ts +48 -0
- package/src/utils/index.ts +1 -0
- package/dist/chunk-34GEH24Y.cjs.map +0 -1
- package/dist/chunk-BVCWBA2U.js.map +0 -1
- package/dist/chunk-EHAYNUOL.cjs.map +0 -1
- package/dist/chunk-ESSHEVZQ.cjs.map +0 -1
- package/dist/chunk-IJYP2DMW.js.map +0 -1
- package/dist/chunk-MSVEZB5D.cjs.map +0 -1
- package/dist/chunk-NZJNXGU2.cjs.map +0 -1
- package/dist/chunk-Q5XGBLT5.cjs.map +0 -1
- package/dist/chunk-QPQCQWAW.cjs.map +0 -1
- package/dist/chunk-YXWGSDK4.cjs.map +0 -1
- package/dist/chunk-Z42VU7HF.cjs.map +0 -1
- /package/dist/{chunk-X3LC6R37.js.map → chunk-32P6KUZP.js.map} +0 -0
- /package/dist/{chunk-RVK3CL5S.js.map → chunk-3D45OAWL.js.map} +0 -0
- /package/dist/{chunk-S6WBBSII.js.map → chunk-76HB456V.js.map} +0 -0
- /package/dist/{chunk-DLZFFGQ7.js.map → chunk-AGYKSJSE.js.map} +0 -0
- /package/dist/{chunk-QR2FJE2C.js.map → chunk-C6TNAYHO.js.map} +0 -0
- /package/dist/{chunk-YQCA4ZEJ.js.map → chunk-CMUNJZWN.js.map} +0 -0
- /package/dist/{chunk-F4TAUCHQ.js.map → chunk-CSP4GOQ2.js.map} +0 -0
- /package/dist/{chunk-H7KQM3VI.js.map → chunk-FNT5JQDQ.js.map} +0 -0
- /package/dist/{chunk-KK7YEVTQ.js.map → chunk-FRDSHK7F.js.map} +0 -0
- /package/dist/{chunk-IZG3VYDV.js.map → chunk-GKCQIJE7.js.map} +0 -0
- /package/dist/{chunk-WEDSYUSR.js.map → chunk-ONTFCKVK.js.map} +0 -0
- /package/dist/{chunk-RGMUA4XB.js.map → chunk-PDFHLSPP.js.map} +0 -0
- /package/dist/{chunk-RQQAPCOU.js.map → chunk-STRI4K3F.js.map} +0 -0
- /package/dist/{chunk-F2KBCLUG.js.map → chunk-X5NN4NJM.js.map} +0 -0
- /package/dist/{chunk-ZIEYC6ZB.js.map → chunk-YDZ5S3Z2.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-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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AA;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,EAAA;AACM,EAAA;AACf;AAGgB;AACP,EAAA;AACT;AAEgB;AACP,EAAA;AACT;AAEgB;AACP,EAAA;AACT;AAGgB;AACE,EAAA;AAClB;AAEgB;AACE,EAAA;AAClB;AAGgB;AACA,EAAA;AAChB;AAEgB;AACA,EAAA;AAChB;AAGgB;AAOA,EAAA;AACC,EAAA;AACT,EAAA;AACC,EAAA;AACO,IAAA;AACF,IAAA;AACI,IAAA;AACd,IAAA;AACe,IAAA;AACjB,EAAA;AACF;AAGa;AACE,EAAA;AACf;AAEgB;AACP,EAAA;AACT;AAUa;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;AFrBmB;AACA;AGhRH;AAOV,EAAA;AACa,IAAA;AACT,EAAA;AACC,IAAA;AACT,EAAA;AACF;AH4QmB;AACA;AI1PV;AACI,EAAA;AACP,EAAA;AACK,IAA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F,MAAA;AACA,MAAA;AACF,IAAA;AACU,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AACF;AN8GmB;AACA;AO7iBV;AA6BH;AACW;AACb;AASY;AACd,EAAA;AACW,EAAA;AACG,EAAA;AACC,EAAA;AACjB;AAES;AACO,EAAA;AACA,EAAA;AACN,IAAA;AACI,IAAA;AAED,MAAA;AACC,MAAA;AACF,MAAA;AACF,QAAA;AACK,MAAA;AACD,QAAA;AACN,MAAA;AAEO,IAAA;AACM,MAAA;AACd,IAAA;AACU,IAAA;AACf,EAAA;AACO,EAAA;AACT;AAQgB;AACR,EAAA;AACW,EAAA;AAED,EAAA;AACT,IAAA;AACD,IAAA;AACW,IAAA;AAEJ,IAAA;AACF,MAAA;AACN,IAAA;AACU,IAAA;AACC,MAAA;AACd,IAAA;AACa,EAAA;AAEE,EAAA;AACD,EAAA;AACT,EAAA;AACT;AP8fmB;AACA;AQllBH;AACP,EAAA;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-ESSHEVZQ.cjs","../src/components/related-content/related-content-section.tsx","../src/components/related-content/card-registry.tsx"],"names":["jsx","buildListUrl"],"mappings":"AAAA,6rBAAY;AACZ;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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A,EAAA,MAAA,CAAM,CAAA;AAAA,IACpD,YAAA,CAAa,GAAA,CAAI,CAAA,IAAA,EAAA,mBAChBA,6BAAAA;AAAA,MAAC,YAAA;AAAA,MAAA;AAAA,QAEC,IAAA;AAAA,QACA,IAAA,EAAM,OAAA,CAAQ,IAAI,CAAA;AAAA,QAClB,OAAA;AAAA,QACA,QAAA,EAAU,qBAAA;AAAA,QACV,WAAA;AAAA,QACA,YAAA;AAAA,QACA,MAAA;AAAA,QACA,iBAAA;AAAA,QACA,OAAA,kBACEA,6BAAAA,IAAC,EAAA,EAAG,SAAA,EAAU,+CAAA,EAAiD,QAAA,EAAA,6DAAA,IAAkC,EAAA,CAAE;AAAA,MAAA,CAAA;AAAA,MAVhG;AAAA,IAYP,CACD;AAAA,EAAA,EAAA,CACH,CAAA;AAEJ;AD6JA;AACA;AACE;AACA;AACF,iGAAC","file":"/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-ESSHEVZQ.cjs","sourcesContent":[null,"'use client';\n\n/**\n * RelatedContentSection\n *\n * Renders content references grouped by type using the canonical card\n * components. MOVED from the hub (`components/shared/related-content-card.tsx`)\n * so any consuming app can embed it; the hub keeps a thin wrapper that\n * pre-binds its host-specific injections (nav hook, URL recomposition,\n * program configs, admin campaign card).\n *\n * THREE data modes (precedence top-down):\n * 1. CONTROLLED — `contentRefs` provided (even `[]`): render exactly those\n * refs, no suggestion fetch (the original investor-update behavior).\n * 2. SUGGESTION — `entityType` + `entityId` provided: self-fetch\n * `GET {apiBaseUrl}/api/related-content?entityType&entityId[&count][&excludeTypes]`\n * (the generic 5-tier engine's second web service). `minResults` maps to\n * `count`; absent → param not sent (server default applies). Each ref\n * carries a `reason` (data-only — never rendered, matching the\n * FaqSection/FaqWithReason precedent).\n * 3. SSR-HYDRATED suggestion — also pass `initialItems` (the server page\n * called the engine directly); the first client fetch is skipped per the\n * `useSelfFetch` initialData contract.\n *\n * Group layout (list vs grid) + card size (lg vs default) come from\n * `CONTENT_REF_GROUPS` in `../../utils/content-ref-groups` — single source of\n * truth, no per-type logic in this file. Skeletons come from\n * `renderSkeletonForType` so the placeholder height matches the loaded card\n * exactly (zero layout shift on resolve).\n *\n * One API call per content type via the shared list-URL builder\n * (`buildListUrl` — injectable; defaults to the lib's byte-parity-tested\n * builder prefixed with `apiBaseUrl`). Fetching uses `useSelfFetch` (plain\n * fetch, NO react-query) so third-party embedders need no QueryClientProvider;\n * cards are imported via DEEP module paths (not the chat barrel) so this\n * chunk never reaches `@tanstack/react-query`.\n *\n * The per-type card + skeleton dispatch lives in `./card-registry`\n * (`RELATED_CARD_REGISTRY`): ONE entry per content type, each carrying that\n * type's own row type and the `unknown` → row decode, so a fetched row reaches\n * its card concretely typed. This file only picks the entry and builds the\n * shared render context.\n *\n * LOCKSTEP NOTE: that registry is the SIZED sibling of the chat-side\n * `CHAT_CARD_REGISTRY` (`../chat/entity-cards/dispatch.tsx`), which renders\n * compact `size='sm'` cards wired to the chat runtime. Two dispatchers by\n * design — when registering a new fetch-mode content type, add it BOTH there\n * and in `./card-registry` (card + skeleton + list URL).\n */\n\nimport type React from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { useSelfFetch } from '../../hooks/use-self-fetch';\nimport type { ContentRef, ContentRefWithReason } from '../../types/content-ref';\nimport {\n CONTENT_REF_GROUPS,\n getContentRefLabelOrTitleCase,\n orderContentRefTypes,\n type ContentRefGroupConfig,\n} from '../../utils/content-ref-groups';\nimport { extractItems, extractItemId } from '../../utils/extract-items';\nimport { buildListUrl as libBuildListUrl, canonicalContentRefType } from '../../utils/list-url';\nimport { pageCount } from '../../utils/search-params';\nimport { buildSuggestionUrl } from '../../utils/suggestion-url';\n// Type-only — erased at build, no runtime dependency on the dispatch module.\nimport type { ChatCardDispatchExtras } from '../chat/entity-cards/dispatch';\nimport { decideNewTab } from '../chat/utils/decide-new-tab';\nimport { Pagination } from '../pagination';\n// The per-type card dispatch — one registry entry per content type, each\n// carrying its OWN row type — plus the DEEP card imports that keep this\n// chunk's source graph free of @tanstack/react-query (the `../chat` barrel\n// reaches it via embeddable-chat; deep paths don't). `CardSize` and\n// `CardLinkAnchorProps` are declared alongside the registry, its primary\n// consumer, and re-exported below so the subpath barrel is unchanged.\nimport {\n RELATED_CARD_REGISTRY,\n rowString,\n type CardLinkAnchorProps,\n type CardSize,\n type RelatedCardRegistryEntry,\n} from './card-registry';\n\nexport type { CardLinkAnchorProps };\n\n/** Render-prop component injection for the navigation decision — keeps hook\n * calls legal (hooks live INSIDE the injected component; `CardForType`\n * itself calls zero hooks). The hub injects a `useNavLink`-backed provider;\n * the default is hook-free (pure `decideNewTab`). MUST be defined at module\n * scope by hosts — an inline arrow would remount every card each render. */\nexport interface CardLinkProviderProps {\n href: string | null;\n targetPlatform: string | null;\n children: (linkProps: CardLinkAnchorProps | null) => React.ReactElement | null;\n}\nexport type CardLinkProvider = React.ComponentType<CardLinkProviderProps>;\n\n/** Default link provider for standalone embeds: relative/-same-origin hrefs\n * stay same-tab, cross-origin pops a new tab (pure `decideNewTab` with no\n * platform context — `currentSource: ''` falls through to the origin\n * check). No router integration, no hooks. */\nfunction DefaultLinkPropsProvider({\n href,\n targetPlatform,\n children,\n}: CardLinkProviderProps): React.ReactElement | null {\n if (!href) return children(null);\n const newTab = decideNewTab({ href, targetPlatform, currentSource: '' });\n return children(newTab ? { href, target: '_blank', rel: 'noopener noreferrer' } : { href });\n}\n\n/** Default href resolution: trust the ref's stored url/targetPlatform as the\n * API composed them. The hub overrides this with its `buildContentURL`\n * re-composition so dev gets localhost and prod gets platform domains. */\nfunction defaultResolveHref(ref: ContentRef): { href: string | null; targetPlatform: string | null } {\n return { href: ref.url || null, targetPlatform: ref.targetPlatform ?? null };\n}\n\n/** Host-injected renderer pair for the admin-only `marketing_campaign` type.\n * Absent (every non-hub embed) → the type renders nothing (its list URL\n * hits `/api/admin`, unreachable outside the hub anyway). */\nexport interface AdminCampaignCardSlot {\n /**\n * The host's own campaign card. Its `campaign` prop is a HOST row type this\n * lib cannot name (the hub's `MarketingCampaign`), and React props are\n * CONTRAVARIANT, so this is the one seam in the rail with no honest type.\n * All three alternatives were compiled against the hub's real\n * `CampaignCardAdmin`:\n *\n * - `unknown` — the host can no longer inject: TS2322, \"Type\n * '{ campaign: unknown }' is not assignable to\n * '{ campaign: MarketingCampaign }'\".\n * - `never` — every host component assigns, but the rail can no longer\n * hand it a row: TS2769, \"Type 'unknown' is not assignable to 'never'\".\n * - a generic on the slot's OWNER (`AdminCampaignCardSlot<TCampaign>`\n * threaded through `RelatedContentSectionProps`) — inference from the\n * host's card works, but the render still fails: TS2769, \"'TCampaign'\n * could be instantiated with an arbitrary type\". The rail holds an\n * unvalidated row; only the HOST knows how to narrow it.\n *\n * Typing this means changing the injection contract (a host-supplied\n * `render(row: unknown)` closure instead of a component), which is a\n * breaking change for every embedder that passes `{ Card, Skeleton }`.\n * Everything the rail renders ITSELF now goes through the per-type\n * `RELATED_CARD_REGISTRY`; this is the only `any` left.\n */\n Card: React.ComponentType<{ campaign: any }>;\n Skeleton: React.ComponentType<{ size?: 'default' | 'sm' }>;\n}\n\n/**\n * Per-type skeleton dispatch — returns the SAME colocated skeleton the\n * resolved card renders, sized to match (zero layout shift on resolve). One\n * lookup through `RELATED_CARD_REGISTRY`, exactly the way the chat-side\n * `CHAT_CARD_REGISTRY` does it via `entry.skeleton()`.\n *\n * `marketing_campaign` is the one type with no registry entry: BOTH its card\n * and its skeleton are host-injected (`AdminCampaignCardSlot`), so there is no\n * lib component to register.\n */\nfunction renderSkeletonForType(\n type: string,\n size: CardSize,\n adminCampaignCard?: AdminCampaignCardSlot,\n): React.ReactNode {\n if (type === 'marketing_campaign') {\n return adminCampaignCard ? <adminCampaignCard.Skeleton size={size === 'sm' ? 'sm' : 'default'} /> : null;\n }\n const entry: RelatedCardRegistryEntry | undefined = RELATED_CARD_REGISTRY[type];\n return entry ? entry.skeleton(size) : null;\n}\n\n/**\n * Per-type card dispatch — ONE lookup through `RELATED_CARD_REGISTRY`, whose\n * entries each pair a skeleton with a card renderer that closes over that\n * type's OWN row type. Sized cards (`'lg'` / `'default'`) are unique to this\n * rail; the chat dispatcher only renders `'sm'`.\n *\n * PURE FUNCTION COMPONENT WITH ZERO HOOK CALLS: the placeholder comes from a\n * plain `extras.buildOgPlaceholderUrl` call (the chat `dispatch.tsx`\n * pattern) and the anchor-prop bundle arrives via the `LinkProvider`\n * render-prop from the parent — so per-card hook legality is owned by the\n * injected provider component, not by this dispatcher.\n *\n * `href` comes from the host's `resolveHref(ref)` (hub: live\n * `buildContentURL` recomposition; default: the ref's stored url).\n */\nfunction CardForType({\n type,\n item,\n size,\n href,\n targetPlatform,\n linkProps,\n extras,\n adminCampaignCard,\n}: {\n type: string;\n /** One fetched row, still unvalidated. Its shape is decided at RUNTIME by\n * `type` (each group fetches from its own per-type list API), so it stays\n * `unknown` right up to the registry entry for that type — which owns the\n * `unknown` → row-type decode and hands its card a concretely typed row. */\n item: unknown;\n size: CardSize;\n href: string;\n targetPlatform: string | null;\n linkProps: CardLinkAnchorProps | null;\n extras?: ChatCardDispatchExtras;\n adminCampaignCard?: AdminCampaignCardSlot;\n}): React.ReactNode {\n // Host-injected admin slot — the only type with no registry entry, because\n // both its card and its skeleton come from the host (see\n // `AdminCampaignCardSlot`). Handled before the lookup so the registry stays\n // a pure lib-card table.\n if (type === 'marketing_campaign') {\n return adminCampaignCard ? <adminCampaignCard.Card campaign={item} /> : null;\n }\n\n const entry: RelatedCardRegistryEntry | undefined = RELATED_CARD_REGISTRY[type];\n if (!entry) return null;\n\n return entry.render(item, {\n size,\n // Most card variants accept only `{default, sm}`. `'lg'` collapses to\n // `'default'` for those. ProductReleaseCard uses its own lg/sm pair.\n legacySize: size === 'sm' ? 'sm' : 'default',\n href,\n targetPlatform,\n linkProps,\n // Top-level target/rel for cards that take them as separate props\n // (BlogCard, CaseStudyCard, …). ProductReleaseCard takes the bundle as a\n // single `anchorProps={...}` and uses `linkProps` directly. When the host\n // didn't surface a URL, `linkProps` is null and the card stays in\n // non-anchor mode.\n anchorAttrs: linkProps ? { target: linkProps.target, rel: linkProps.rel } : {},\n // OG placeholder URL — injected into the pure-presentation cards so they\n // render a branded fallback when the row's featured image is null. Plain\n // function call (NOT a hook). Title is the universal field across all card\n // row shapes used here.\n // `item?.title as string | undefined` claimed a string without checking one:\n // a numeric title reached `buildOgPlaceholderUrl` as a number. `rowString`\n // makes the claim true.\n placeholderUrl: extras?.buildOgPlaceholderUrl?.(rowString(item, 'title') ?? '') ?? undefined,\n extras,\n });\n}\n\n// =============================================================================\n// Fetch all items for a type in ONE server-sorted call, via the injectable\n// list-URL builder. `useSelfFetch` (URL = cache key) replaces the hub's old\n// react-query usage: `enabled` ≙ `url === null`, `!res.ok`/network error ≙\n// `error → items null → group renders nothing`. Accepted deltas vs\n// react-query: no retry/backoff, no focus refetch, no cross-mount cache.\n// =============================================================================\n\nfunction useGroupItems(type: string, refs: ContentRef[], buildUrl: (type: string, ids: string[]) => string | null) {\n const ids = refs.map(r => r.id);\n const url = ids.length > 0 ? buildUrl(type, ids) : null;\n const { data, isLoading } = useSelfFetch<unknown>(url);\n const items = data != null ? extractItems(data) : null;\n return { items, isLoading };\n}\n\n// =============================================================================\n// Per-group renderer — one API call, server-sorted, then render cards via the\n// dispatcher with per-type skeletons + per-type layout from CONTENT_REF_GROUPS.\n// =============================================================================\n\n/** Map columns prop → tailwind grid class. Only consulted for grid-layout\n * groups; list-layout groups stack vertically. */\nfunction gridClassFor(columns: 2 | 3): string {\n return columns === 3\n ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6'\n : 'grid grid-cols-1 sm:grid-cols-2 gap-6';\n}\n\n/** Resolve the group config for a type, falling back to a grid layout with\n * the default card size for unregistered types so the section still renders\n * rather than silently dropping them. The `label` field on the fallback is\n * intentionally a placeholder — the section heading goes through\n * `getContentRefLabelOrTitleCase(type)` instead so cross-surface labels\n * stay consistent between this rail and the investor-email builder. */\nfunction resolveGroupConfig(type: string): ContentRefGroupConfig {\n return (\n CONTENT_REF_GROUPS[type] ?? {\n label: type,\n order: 999,\n layout: 'grid',\n gridSize: 'default',\n }\n );\n}\n\n/** Items per page within one type group. Groups larger than this paginate\n * with the standard Pagination control (NO nested scrolling — a bounded\n * scrollbox inside the page traps wheel events and hides the sections\n * below it). MUST stay at or above the largest suggestion fill\n * (RELATED_SAME_TYPE_COUNT in the hub's lib/constants/suggestions.ts) so\n * current rails never paginate — only genuinely big groups (author pages)\n * do. Exported through the subpath barrel for the hub's module-load\n * assertion of that relation (entity-suggestion-sections.tsx). */\nexport const GROUP_PAGE_SIZE = 12;\n\nfunction ContentGroup({\n type,\n refs,\n columns,\n buildUrl,\n resolveHref,\n LinkProvider,\n extras,\n adminCampaignCard,\n heading,\n}: {\n type: string;\n refs: ContentRef[];\n columns: 2 | 3;\n buildUrl: (type: string, ids: string[]) => string | null;\n resolveHref: (ref: ContentRef) => { href: string | null; targetPlatform: string | null };\n LinkProvider: CardLinkProvider;\n extras?: ChatCardDispatchExtras;\n adminCampaignCard?: AdminCampaignCardSlot;\n /** Group heading, rendered INSIDE the group so a group that resolves to\n * nothing (fetch miss / unsupported type / missing program config) drops\n * its heading too — no orphaned titles. */\n heading: React.ReactNode;\n}) {\n const { items, isLoading } = useGroupItems(type, refs, buildUrl);\n const config = resolveGroupConfig(type);\n const isListLayout = config.layout === 'list';\n const cardSize = config.gridSize;\n\n // Per-group pagination for big groups (author pages): GROUP_PAGE_SIZE items\n // per page with the standard Pagination control below the group. Client-side\n // slicing — useGroupItems already fetched every row in one batched call, so\n // page flips are instant. Hooks live above every early return (file\n // convention). Page is clamped so a shrinking refs array (suggestion\n // refetch) can never strand the view past the last page, and RESET when the\n // ref set actually changes (shrink→grow must not return to a stale page).\n const [page, setPage] = useState(1);\n const refsKey = refs.map(r => r.id).join('|');\n const prevRefsKeyRef = useRef(refsKey);\n useEffect(() => {\n if (prevRefsKeyRef.current !== refsKey) {\n prevRefsKeyRef.current = refsKey;\n setPage(1);\n }\n }, [refsKey]);\n const totalGroupPages = pageCount(refs.length, GROUP_PAGE_SIZE);\n const safePage = Math.min(page, totalGroupPages);\n const visibleGroupRefs =\n refs.length > GROUP_PAGE_SIZE ? refs.slice((safePage - 1) * GROUP_PAGE_SIZE, safePage * GROUP_PAGE_SIZE) : refs;\n const groupPagination =\n totalGroupPages > 1 ? (\n <Pagination currentPage={safePage} totalPages={totalGroupPages} onPageChange={setPage} />\n ) : null;\n\n // Skeleton gate: `isLoading && !items` — SSR HTML and the client's first\n // paint render identical skeletons (useSelfFetch starts isLoading=true on\n // both sides), and once items exist they are never replaced by skeletons.\n if (isLoading && !items) {\n const skeletons = visibleGroupRefs.map(r => (\n <div key={r.id}>{renderSkeletonForType(type, cardSize, adminCampaignCard)}</div>\n ));\n return (\n <div className=\"space-y-4\">\n {heading}\n {isListLayout ? (\n <div className=\"space-y-4\">{skeletons}</div>\n ) : (\n <div className={gridClassFor(columns)}>{skeletons}</div>\n )}\n </div>\n );\n }\n\n if (!items || items.length === 0) return null;\n\n // Index fetched rows by id, then render in REF order — refs carry the\n // intended sequence (suggestion mode: the engine's tier order, so\n // same-platform/tag-matched items lead; controlled mode: the curated\n // display_order). The list APIs return rows date-sorted, which would\n // otherwise scramble that ordering (same-platform items sinking below\n // newer cross-platform ones).\n // Shared extractor (NOT raw `.id`) — some API shapes key items differently\n // (e.g. external_id types); raw access would silently drop valid items.\n const rowKey = (it: unknown): string => {\n const extracted = extractItemId(type, it);\n if (extracted !== null) return extracted;\n // Fallback for shapes `extractItemId` doesn't recognise — same\n // `String(it?.id)` the untyped version produced.\n return String(typeof it === 'object' && it !== null ? (it as { id?: unknown }).id : undefined);\n };\n const itemById = new Map(items.map(it => [rowKey(it), it]));\n\n const cards = visibleGroupRefs\n .map(contentRef => {\n const itemId = String(contentRef.id);\n const item = itemById.get(itemId);\n if (!item) return null;\n // Re-compose the URL via the host's resolver (hub: buildContentURL so\n // dev gets localhost and prod the right platform domain; default: the\n // ref's stored url as the API composed it).\n const resolved = resolveHref(contentRef);\n const href = resolved.href ?? '';\n const targetPlatform = resolved.targetPlatform ?? contentRef.targetPlatform ?? null;\n return (\n <div key={itemId}>\n <LinkProvider href={href || null} targetPlatform={targetPlatform}>\n {linkProps => (\n <CardForType\n type={type}\n item={item}\n size={cardSize}\n href={href}\n targetPlatform={targetPlatform}\n linkProps={linkProps}\n extras={extras}\n adminCampaignCard={adminCampaignCard}\n />\n )}\n </LinkProvider>\n </div>\n );\n })\n .filter(Boolean);\n\n if (cards.length === 0) {\n // Current PAGE resolved zero cards (rows deleted between the ref fetch\n // and the group fetch, or a stricter list-API gate dropped them). When a\n // pager exists the user must keep the controls to navigate back —\n // dropping the whole group would strand them. A genuinely empty group\n // (no pager) still vanishes with its heading.\n if (groupPagination) {\n return (\n <div className=\"space-y-4\">\n {heading}\n {groupPagination}\n </div>\n );\n }\n return null;\n }\n\n return (\n <div className=\"space-y-4\">\n {heading}\n {isListLayout ? <div className=\"space-y-4\">{cards}</div> : <div className={gridClassFor(columns)}>{cards}</div>}\n {groupPagination}\n </div>\n );\n}\n\n// =============================================================================\n// Main component\n// =============================================================================\n\ninterface RelatedContentResponse {\n refs: ContentRefWithReason[];\n}\n\nexport interface RelatedContentSectionProps {\n /** CONTROLLED mode (the original behavior). When defined — even `[]` — no\n * suggestion fetch runs and exactly these refs render. */\n contentRefs?: ContentRef[];\n /** SUGGESTION mode (with `entityId`): self-fetch suggestions for this host\n * entity from `{apiBaseUrl}/api/related-content`. Ignored when\n * `contentRefs` is provided. */\n entityType?: string;\n entityId?: number | string;\n /** AUTHOR mode: self-fetch ALL published content authored by this profile\n * from `{apiBaseUrl}/api/related-content?authorId=…` (grouped per type,\n * endless within each group). Ignored when `contentRefs` is provided;\n * takes precedence over the entityType/entityId suggestion scope.\n * SSR-hydrate via `initialItems`, same as suggestion mode. */\n authorId?: string;\n /** Maps to the suggestion API's `count` param — the PER-TYPE fill target\n * for every candidate type EXCEPT the host's own. Absent → param not sent\n * (server default applies). */\n minResults?: number;\n /** Maps to the suggestion API's `sameTypeCount` param — the budget for the\n * candidate type MATCHING the host's own `entityType` (same-type boost:\n * a blog post's rail leads with more blog posts). Absent → param not\n * sent (host's type uses the server's `count`). */\n sameTypeMinResults?: number;\n /** SSR hydrate for suggestion mode — the server page ran the engine and\n * drills the refs here; the first client fetch is skipped (useSelfFetch\n * initialData contract). */\n initialItems?: ContentRefWithReason[];\n /** Section title (default: \"Related Content\") */\n title?: string;\n /**\n * Grid columns at desktop. 2 = denser cards / wider summary (original\n * investor-update layout); 3 = more cards per row for dashboards.\n * Only consulted for grid-layout groups. Default: 2.\n */\n columns?: 2 | 3;\n /**\n * ContentRef.type values to exclude. Honored in ALL modes — controlled\n * mode post-filters (original behavior); suggestion mode ALSO forwards the\n * list verbatim as the API's `excludeTypes=` param so excluded types never\n * consume engine fill slots (`minResults` stays honored). The subtraction\n * happens SERVER-side — this component never mirrors the hub's candidate\n * list.\n */\n excludeTypes?: string[];\n /**\n * SUGGESTION-mode allow-list (rail vocabulary): which content types\n * participate in this rail. Sent verbatim as the API's `types=` param —\n * the SERVER intersects it with its own allowed candidate set, and\n * platform policy gates (e.g. internal-only types) ALWAYS win: the client\n * cannot request its way past them. Absent → all server-side candidates.\n */\n includeTypes?: string[];\n /** Fetch-URL prefix for third-party embeds / reverse proxies\n * ('' = same-origin). Applied to BOTH the suggestion fetch and the\n * default per-group list fetches. */\n apiBaseUrl?: string;\n /** Host injection bundle — REUSES the chat dispatcher's\n * `ChatCardDispatchExtras` (programConfigs, buildOgPlaceholderUrl,\n * buildProductReleaseCardProps override). Program groups render nothing\n * when their config is absent. */\n extras?: ChatCardDispatchExtras;\n /** Hub injects its `buildContentURL` recomposition; default uses the\n * ref's stored `url`/`targetPlatform` as the API composed them. */\n resolveHref?: (ref: ContentRef) => { href: string | null; targetPlatform: string | null };\n /** Hub injects its registry-driven entity-list-api builder; default = the\n * lib's `buildListUrl(type, ids, apiBaseUrl)`. */\n buildListUrl?: (type: string, ids: string[]) => string | null;\n /** Hub injects a `useNavLink`-backed render-prop provider; default = pure\n * anchor via `decideNewTab`. MUST be a module-scope component. */\n LinkProvider?: CardLinkProvider;\n /** Renderer pair for the admin-only `marketing_campaign` type. Absent →\n * the type renders nothing. */\n adminCampaignCard?: AdminCampaignCardSlot;\n /** When true, render the section shell (title + an empty-state line) even\n * with ZERO refs, instead of returning null. Default false (the original\n * behavior — empty rail = no shell). Opt-in per host page (e.g. people-hub's\n * \"What I Shipped\", where the section should always be present). */\n showWhenEmpty?: boolean;\n /** Empty-state copy shown under the title when `showWhenEmpty` and no refs.\n * Default: \"No related content yet.\" */\n emptyStateText?: string;\n /** Custom empty-state node (e.g. a hub `<EmptyState/>`) rendered under the\n * title when `showWhenEmpty` and there are no refs — overrides\n * `emptyStateText`. Lets a host match its canonical empty state. */\n emptyState?: React.ReactNode;\n}\n\nexport function RelatedContentSection({\n contentRefs,\n entityType,\n entityId,\n authorId,\n minResults,\n sameTypeMinResults,\n includeTypes,\n initialItems,\n title = 'Related Content',\n columns = 2,\n excludeTypes,\n apiBaseUrl = '',\n extras,\n resolveHref = defaultResolveHref,\n buildListUrl,\n LinkProvider = DefaultLinkPropsProvider,\n adminCampaignCard,\n showWhenEmpty = false,\n emptyStateText = 'No related content yet.',\n emptyState,\n}: RelatedContentSectionProps) {\n // ── Hooks above EVERY early return (the original `if (!contentRefs.length)\n // return null` guard moved below them). ──\n\n // Suggestion-mode fetch URL — null in controlled mode (contentRefs defined,\n // even []) or when the entity scope is incomplete.\n // `includeTypes: []` is an explicit \"nothing participates\" — skip the fetch\n // entirely (an empty-string `types=` param would be dropped by the URL\n // builder and read server-side as \"all candidates\") AND ignore SSR refs.\n const suggestionsDisabled = includeTypes?.length === 0;\n // Shared type-filter params — one spelling for both fetch modes so a future\n // normalization (trim/dedupe) can't diverge between them.\n const typeFilterParams = {\n types: includeTypes !== undefined ? includeTypes.join(',') : undefined,\n excludeTypes: excludeTypes && excludeTypes.length > 0 ? excludeTypes.join(',') : undefined,\n };\n // AUTHOR mode beats suggestion mode: when `authorId` is set the rail lists\n // everything that profile authored (the server returns ALL, no count).\n const authorUrl =\n contentRefs === undefined && authorId && !suggestionsDisabled\n ? buildSuggestionUrl('/api/related-content', {\n apiBaseUrl,\n extraParams: { authorId, ...typeFilterParams },\n })\n : null;\n const suggestUrl =\n authorUrl ??\n (contentRefs === undefined &&\n entityType &&\n entityId !== undefined &&\n entityId !== null &&\n entityId !== '' &&\n !suggestionsDisabled\n ? buildSuggestionUrl('/api/related-content', {\n apiBaseUrl,\n entityType,\n entityId,\n count: minResults,\n extraParams: {\n sameTypeCount: sameTypeMinResults !== undefined ? String(sameTypeMinResults) : undefined,\n ...typeFilterParams,\n },\n })\n : null);\n // Memoize the initialData wrapper — useSelfFetch re-syncs on [initialData],\n // and a fresh per-render object would loop setState under re-rendering\n // parents (the latent FaqSection bug, fixed there in the same change).\n const initialData = useMemo<RelatedContentResponse | undefined>(\n // An explicitly disabled rail (includeTypes: []) must ignore SSR-hydrated\n // refs too — otherwise useSelfFetch(null, {initialData}) keeps serving\n // initialItems and the \"nothing participates\" contract silently breaks.\n () => (!suggestionsDisabled && initialItems ? { refs: initialItems } : undefined),\n [initialItems, suggestionsDisabled],\n );\n const { data, isLoading } = useSelfFetch<RelatedContentResponse>(suggestUrl, { initialData });\n\n // Default group fetcher: the lib's byte-parity-tested builder, prefixed for\n // embeds. Memoized so group-fetch URLs stay value-stable across renders.\n const effectiveBuildListUrl = useMemo(\n () => buildListUrl ?? ((type: string, ids: string[]) => libBuildListUrl(type, ids, apiBaseUrl)),\n [buildListUrl, apiBaseUrl],\n );\n\n const refs: ContentRef[] = contentRefs ?? data?.refs ?? [];\n\n // Per-consumer type gating — drops refs whose `type` is in the exclude\n // list. In suggestion mode the server already subtracted these (the param\n // is forwarded above); the client filter stays as an idempotent guard and\n // IS the mechanism in controlled mode (original behavior).\n const exclude = new Set(excludeTypes || []);\n const visibleRefs = exclude.size > 0 ? refs.filter(r => !exclude.has(r.type)) : refs;\n // Zero refs (still loading in suggestion mode, or genuinely empty). Default:\n // no empty shell. Opt-in (`showWhenEmpty`): render the title + an empty-state\n // line so the section is always present (e.g. people-hub \"What I Shipped\").\n if (!visibleRefs.length) {\n if (!showWhenEmpty) return null; // non-showWhenEmpty consumers stay blank (unchanged)\n // Client-fetch loading (author/suggestion mode, no SSR initialItems): render a\n // SKELETON grid — reserves height + matches the rest of the app's loading, so\n // there's no blank-then-pop jump (the prior `return null` collapsed the tab to\n // zero height during the fetch). SSR controlled mode has isLoading=false → it\n // skips straight to the empty state below. Skeleton type = the requested rail\n // type (author mode passes a single `includeTypes`).\n if (isLoading) {\n const skeletonType = includeTypes?.[0] ?? entityType ?? 'blog_post_existing';\n return (\n <div className=\"space-y-8\">\n <h2 className=\"text-ods-text-primary text-h2\">{title}</h2>\n <div className={gridClassFor(columns)}>\n {Array.from({ length: 3 }).map((_, i) => (\n <div key={i}>{renderSkeletonForType(skeletonType, 'default', adminCampaignCard)}</div>\n ))}\n </div>\n </div>\n );\n }\n return (\n <div className=\"space-y-8\">\n <h2 className=\"text-2xl font-bold text-ods-text-primary\">{title}</h2>\n {emptyState ?? <p className=\"text-ods-text-secondary\">{emptyStateText}</p>}\n </div>\n );\n }\n\n const grouped: Record<string, ContentRef[]> = {};\n for (const ref of visibleRefs) {\n if (!grouped[ref.type]) grouped[ref.type] = [];\n grouped[ref.type].push(ref);\n }\n\n // Registered types in CONTENT_REF_GROUPS order, then any unregistered\n // types appended (same shape the investor-email builder uses — both\n // consume `orderContentRefTypes` so cross-surface ordering matches).\n // SAME-TYPE FIRST: when a host entityType is known (suggestion / SSR\n // modes), its own content-type group is hoisted to the top — a blog\n // post's rail leads with blog posts. Rail group keys are compared via\n // the shared alias canonicalizer (blog_post_existing ↔ blog_post).\n let orderedTypes = orderContentRefTypes(Object.keys(grouped));\n if (entityType) {\n // Canonicalize BOTH sides — hosts pass registry vocab ('blog_post') but\n // rail-vocab aliases ('blog_post_existing') are also legal inputs; a raw\n // comparison would silently lose the same-type-first hoist for aliases.\n const canonicalEntityType = canonicalContentRefType(entityType);\n const sameType = orderedTypes.filter(t => canonicalContentRefType(t) === canonicalEntityType);\n if (sameType.length > 0) {\n orderedTypes = [...sameType, ...orderedTypes.filter(t => canonicalContentRefType(t) !== canonicalEntityType)];\n }\n }\n\n return (\n <div className=\"space-y-8\">\n <h2 className=\"text-ods-text-primary text-h2\">{title}</h2>\n {orderedTypes.map(type => (\n <ContentGroup\n key={type}\n type={type}\n refs={grouped[type]}\n columns={columns}\n buildUrl={effectiveBuildListUrl}\n resolveHref={resolveHref}\n LinkProvider={LinkProvider}\n extras={extras}\n adminCampaignCard={adminCampaignCard}\n heading={\n <h3 className=\"font-semibold text-ods-text-secondary text-h5\">{getContentRefLabelOrTitleCase(type)}</h3>\n }\n />\n ))}\n </div>\n );\n}\n","'use client';\n\n/**\n * Per-type card registry for the related-content rail — the SIZED sibling of\n * the chat side's `CHAT_CARD_REGISTRY` (`../chat/entity-cards/dispatch.tsx`),\n * and built to the same shape: ONE entry per content type, carrying that\n * type's skeleton and its card renderer, dispatched once from\n * `related-content-section.tsx`.\n *\n * WHY THIS FILE EXISTS\n * --------------------\n * The rail fetches one row per ref from that type's public list API. The row\n * arrives as `unknown` (`useSelfFetch<unknown>` → `extractItems`), and its\n * SHAPE is decided at runtime by the ref's `type`. The rail used to bridge\n * that with a single `item: any` threaded through a ten-branch switch, so\n * every `prop={item}` forward was an unchecked promise: a row missing a field\n * reached a card that declared it required, and the card rendered the miss\n * (an empty heading, a version pill reading \"vundefined\").\n *\n * Each entry here closes over its OWN row type instead. `cardEntry<Row>` pairs\n * a `decode` (runtime `unknown` → `Row`) with a `render` that receives `Row`,\n * and erases `Row` from the stored entry — so the registry is homogeneous\n * (`Record<string, RelatedCardRegistryEntry>`) while every branch stays\n * concretely typed. No `any`, no assertions into card row types.\n *\n * ON THE `*_ROW_DEFAULTS` CONSTANTS\n * ---------------------------------\n * Each card declares the FULL entity type as its row prop (`BlogPostSummary`,\n * `CaseStudy`, …) while reading only a handful of fields off it, and the list\n * APIs return projections rather than whole rows. A decoder therefore reads\n * the card's read set from the row and takes every other required field from\n * a `*_ROW_DEFAULTS` literal. Those placeholders are inert BY CONSTRUCTION —\n * the decoded row goes nowhere but its own card, and the card never reads\n * them. They are annotated with the entity type on purpose: a new required\n * field on `CaseStudy` surfaces as a compile error here instead of silently\n * reaching a card as `undefined`, which is the exact failure this file\n * replaces.\n *\n * ADDING A TYPE: one entry below (skeleton + decode + render), plus the chat\n * side's `CHAT_CARD_REGISTRY` and the list-URL builder — see the LOCKSTEP note\n * in `related-content-section.tsx`.\n */\n\nimport type React from 'react';\nimport type { BlogPostSummary } from '../../types/blog';\nimport type { CaseStudy } from '../../types/case-study';\nimport type { CustomerInterview } from '../../types/customer-interview';\nimport type { EntityAuthor } from '../../types/entity-author';\nimport type { MSP } from '../../types/stack';\nimport type { UserProfile } from '../../types/user';\nimport { AiPromptCard, AiPromptCardSkeleton, type AiPromptCardData } from '../chat/entity-cards/ai-prompt-card';\n// DEEP card imports — NOT the `../chat` barrel. See the import note in\n// `related-content-section.tsx`: the barrel statically reaches\n// @tanstack/react-query, deep paths keep this module's source graph free of it.\nimport { BlogCard, BlogCardSkeleton } from '../chat/entity-cards/blog-card';\nimport { CaseStudyCard, CaseStudyCardSkeleton } from '../chat/entity-cards/case-study-card';\nimport { CustomerInterviewCard, CustomerInterviewCardSkeleton } from '../chat/entity-cards/customer-interview-card';\n// Type-only — erased at build, no runtime dependency on the dispatch module.\nimport type { ChatCardDispatchExtras } from '../chat/entity-cards/dispatch';\nimport { HowIWorkCard, HowIWorkCardSkeleton, type HowIWorkCardData } from '../chat/entity-cards/how-i-work-card';\nimport { InvestorUpdateCard, InvestorUpdateCardSkeleton } from '../chat/entity-cards/investor-update-card';\nimport { OnboardingGuideCard, OnboardingGuideCardSkeleton } from '../chat/entity-cards/onboarding-guide-card';\nimport { ProductReleaseCard, ProductReleaseCardSkeleton } from '../chat/entity-cards/product-release-card';\nimport { buildProductReleaseCardProps } from '../chat/entity-cards/product-release-card-defaults';\nimport { ProgramCard, ProgramCardSkeleton } from '../chat/entity-cards/program-card';\nimport { RoadmapCard, RoadmapCardSkeleton } from '../chat/entity-cards/roadmap-card';\nimport {\n WhatIShippedCard,\n WhatIShippedCardSkeleton,\n type WhatIShippedCardData,\n} from '../chat/entity-cards/what-i-shipped-card';\nimport type { InvestorUpdate } from '../chat/types/entities/investor-update';\nimport type { OnboardingGuide } from '../chat/types/entities/onboarding-guide';\nimport type { BaseProgramItem, ProgramHost } from '../chat/types/entities/program-types';\nimport type { RoadmapItem } from '../chat/types/entities/roadmap-item';\n\nexport type CardSize = 'lg' | 'default' | 'sm';\n\n/** Anchor prop bundle the per-card link surface receives — same shape the\n * hub's `useNavLink` returns and the chat dispatcher's anchor builders\n * produce. `null` = non-anchor mode (no URL). */\nexport interface CardLinkAnchorProps {\n href: string;\n target?: '_blank';\n rel?: 'noopener noreferrer';\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n}\n\n// =============================================================================\n// Row reading — the ONE place a runtime row is inspected.\n// =============================================================================\n\n/**\n * View an unvalidated row as a keyed bag. This claims nothing about the row's\n * SHAPE — every read below still checks the value's type — it only says \"this\n * is an object I may look keys up on\". A non-object row (null, a string, a\n * number) collapses to `{}`, so every decoder degrades to its defaults instead\n * of throwing.\n */\nfunction asRecord(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};\n}\n\n/** A STRING field, or `undefined` when missing or wrong-typed. */\nexport function rowString(row: unknown, key: string): string | undefined {\n const value = asRecord(row)[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction str(row: Record<string, unknown>, key: string): string {\n const value = row[key];\n return typeof value === 'string' ? value : '';\n}\n\nfunction strOrNull(row: Record<string, unknown>, key: string): string | null {\n const value = row[key];\n return typeof value === 'string' ? value : null;\n}\n\nfunction numOrNull(row: Record<string, unknown>, key: string): number | null {\n const value = row[key];\n return typeof value === 'number' ? value : null;\n}\n\n/** `Array.isArray` narrows `unknown` to `any[]`; annotating the result keeps\n * the elements `unknown` so nothing downstream inherits `any`. Same guard the\n * shared `extractItems` normalizer uses. */\nfunction arrayOf(value: unknown): unknown[] {\n const list: unknown[] = Array.isArray(value) ? value : [];\n return list;\n}\n\nfunction stringList(value: unknown): string[] {\n return arrayOf(value).filter((entry): entry is string => typeof entry === 'string');\n}\n\n// =============================================================================\n// Shared nested-shape decoders (joins hydrated onto several row types).\n// =============================================================================\n\n/** `{ name, slug }` tag / category joins. Rows that carry only `name` (the\n * chat-side row shape) keep their label and get an empty slug — the cards\n * read `name` and nothing else. */\nfunction namedSlugList(value: unknown): { name: string; slug: string }[] {\n const out: { name: string; slug: string }[] = [];\n for (const entry of arrayOf(value)) {\n const record = asRecord(entry);\n const name = strOrNull(record, 'name');\n if (name === null) continue;\n out.push({ name, slug: str(record, 'slug') });\n }\n return out;\n}\n\nconst USER_PROFILE_DEFAULTS: UserProfile = {\n id: '',\n full_name: null,\n email: '',\n avatar_url: null,\n job_title: null,\n company: null,\n bio: null,\n employee_id: null,\n department_id: null,\n department: null,\n role: 'user',\n msp_id: null,\n created_at: '',\n updated_at: '',\n};\n\n/** The customer/author join on case studies + customer interviews. The cards\n * read `full_name`, `avatar_url` and `job_title`; absent join → `undefined`,\n * which is what those cards already fall back on. */\nfunction decodeUserProfile(value: unknown): UserProfile | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = asRecord(value);\n return {\n ...USER_PROFILE_DEFAULTS,\n id: str(record, 'id'),\n full_name: strOrNull(record, 'full_name'),\n avatar_url: strOrNull(record, 'avatar_url'),\n job_title: strOrNull(record, 'job_title'),\n };\n}\n\nconst MSP_DEFAULTS: MSP = { id: '', name: '', seat_count: 0, created_at: '', updated_at: '' };\n\n/** The MSP join — cards read `name` and `icon_url`. */\nfunction decodeMsp(value: unknown): MSP | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = asRecord(value);\n return {\n ...MSP_DEFAULTS,\n id: str(record, 'id'),\n name: str(record, 'name'),\n icon_url: rowString(record, 'icon_url'),\n };\n}\n\n/** The shared hydrated-author shape (`EntityAuthor`) — only `full_name` and\n * `avatar_url` are required, so this needs no defaults literal. */\nfunction decodeEntityAuthor(value: unknown): EntityAuthor | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = asRecord(value);\n return {\n id: rowString(record, 'id'),\n full_name: strOrNull(record, 'full_name'),\n avatar_url: strOrNull(record, 'avatar_url'),\n job_title: strOrNull(record, 'job_title'),\n about: strOrNull(record, 'about'),\n slug: rowString(record, 'slug'),\n };\n}\n\n/** Program hosts / speakers. `name` is the only required field; an entry\n * without one is dropped rather than rendered as a nameless avatar. */\nfunction decodeProgramHosts(value: unknown): ProgramHost[] | null {\n if (value == null) return null;\n const out: ProgramHost[] = [];\n for (const entry of arrayOf(value)) {\n const record = asRecord(entry);\n const name = strOrNull(record, 'name');\n if (name === null) continue;\n out.push({\n name,\n id: rowString(record, 'id'),\n email: rowString(record, 'email'),\n avatar_url: rowString(record, 'avatar_url'),\n bio: rowString(record, 'bio'),\n role: rowString(record, 'role'),\n });\n }\n return out;\n}\n\n// =============================================================================\n// Per-type row decoders. Each reads the fields ITS card renders; every other\n// required field comes from the type-annotated defaults literal above it.\n// =============================================================================\n\nfunction decodeBlogRow(row: unknown): BlogPostSummary {\n const record = asRecord(row);\n return {\n id: numOrNull(record, 'id') ?? 0,\n title: str(record, 'title'),\n slug: str(record, 'slug'),\n summary: strOrNull(record, 'summary'),\n featured_image: strOrNull(record, 'featured_image'),\n published_at: strOrNull(record, 'published_at'),\n author_name: strOrNull(record, 'author_name'),\n author_avatar: strOrNull(record, 'author_avatar'),\n categories: namedSlugList(record.categories),\n tags: namedSlugList(record.tags),\n view_count: numOrNull(record, 'view_count') ?? undefined,\n };\n}\n\nconst CASE_STUDY_ROW_DEFAULTS: CaseStudy = {\n id: 0,\n title: '',\n slug: '',\n summary: null,\n featured_image: null,\n user_id: null,\n challenge: null,\n solution: null,\n results: null,\n testimonial_video_url: null,\n main_video_url: null,\n video_source_type: null,\n video_source: null,\n video_bites: [],\n customer_interview_id: null,\n seo_title: null,\n seo_description: null,\n seo_keywords: null,\n og_image_url: null,\n status: 'published',\n published_at: null,\n author_id: null,\n created_at: '',\n updated_at: '',\n view_count: 0,\n};\n\nfunction decodeCaseStudyRow(row: unknown): CaseStudy {\n const record = asRecord(row);\n return {\n ...CASE_STUDY_ROW_DEFAULTS,\n id: numOrNull(record, 'id') ?? 0,\n title: str(record, 'title'),\n summary: strOrNull(record, 'summary'),\n featured_image: strOrNull(record, 'featured_image'),\n msp: decodeMsp(record.msp),\n user: decodeUserProfile(record.user),\n };\n}\n\nconst CUSTOMER_INTERVIEW_ROW_DEFAULTS: CustomerInterview = {\n id: 0,\n title: '',\n slug: '',\n video_summary: null,\n transcript: null,\n user_id: null,\n main_video_url: null,\n teasers: [],\n case_study_id: null,\n seo_title: null,\n seo_description: null,\n seo_keywords: null,\n og_image_url: null,\n featured_image: null,\n status: 'completed',\n completed_at: null,\n author_id: null,\n custom_instructions: null,\n created_at: '',\n updated_at: '',\n view_count: 0,\n};\n\nfunction decodeCustomerInterviewRow(row: unknown): CustomerInterview {\n const record = asRecord(row);\n return {\n ...CUSTOMER_INTERVIEW_ROW_DEFAULTS,\n id: numOrNull(record, 'id') ?? 0,\n title: str(record, 'title'),\n video_summary: strOrNull(record, 'video_summary'),\n main_video_url: strOrNull(record, 'main_video_url'),\n featured_image: strOrNull(record, 'featured_image'),\n msp: decodeMsp(record.msp),\n user: decodeUserProfile(record.user),\n };\n}\n\nconst INVESTOR_UPDATE_ROW_DEFAULTS: InvestorUpdate = {\n id: '',\n title: '',\n slug: '',\n update_number: null,\n period_start: null,\n period_end: null,\n platform_id: null,\n content: null,\n video_summary: null,\n transcript: null,\n main_video_url: null,\n highlight_video_url: null,\n highlight_video_thumbnail: null,\n main_video_thumbnail: null,\n video_bites: [],\n featured_image: null,\n strategic_update: null,\n financials: {},\n metrics_snapshot: {},\n content_refs: [],\n highlights: null,\n section_visibility: {},\n status: 'published',\n published_at: null,\n author_id: null,\n seo_title: null,\n seo_description: null,\n seo_keywords: null,\n og_image_url: null,\n hubspot_email_id: null,\n custom_instructions: null,\n created_at: '',\n updated_at: '',\n created_by: null,\n updated_by: null,\n};\n\nfunction decodeInvestorUpdateRow(row: unknown): InvestorUpdate {\n const record = asRecord(row);\n return {\n ...INVESTOR_UPDATE_ROW_DEFAULTS,\n id: str(record, 'id'),\n title: str(record, 'title'),\n update_number: numOrNull(record, 'update_number'),\n period_start: strOrNull(record, 'period_start'),\n period_end: strOrNull(record, 'period_end'),\n content: strOrNull(record, 'content'),\n strategic_update: strOrNull(record, 'strategic_update'),\n featured_image: strOrNull(record, 'featured_image'),\n };\n}\n\nconst ONBOARDING_GUIDE_ROW_DEFAULTS: OnboardingGuide = {\n id: '',\n title: '',\n slug: '',\n section: '',\n step_order: 0,\n section_order: 0,\n content: null,\n video_summary: null,\n transcript: null,\n transcript_words_data: null,\n srt_content: null,\n ai_transcript_formatted: null,\n main_video_url: null,\n main_video_thumbnail: null,\n youtube_url: null,\n highlight_video_url: null,\n highlight_video_thumbnail: null,\n highlight_video_duration_ms: null,\n highlight_video_source: null,\n video_bites: [],\n featured_image: null,\n og_image_url: null,\n seo_title: null,\n seo_description: null,\n seo_keywords: null,\n status: 'published',\n published_at: null,\n author_id: null,\n custom_instructions: null,\n config: null,\n ai_effort_score: null,\n created_at: '',\n updated_at: '',\n created_by: null,\n updated_by: null,\n};\n\nfunction decodeOnboardingGuideRow(row: unknown): OnboardingGuide {\n const record = asRecord(row);\n return {\n ...ONBOARDING_GUIDE_ROW_DEFAULTS,\n id: str(record, 'id'),\n title: str(record, 'title'),\n section: str(record, 'section'),\n step_order: numOrNull(record, 'step_order') ?? 0,\n content: strOrNull(record, 'content'),\n video_summary: strOrNull(record, 'video_summary'),\n featured_image: strOrNull(record, 'featured_image'),\n og_image_url: strOrNull(record, 'og_image_url'),\n main_video_thumbnail: strOrNull(record, 'main_video_thumbnail'),\n highlight_video_thumbnail: strOrNull(record, 'highlight_video_thumbnail'),\n highlight_video_duration_ms: numOrNull(record, 'highlight_video_duration_ms'),\n author: decodeEntityAuthor(record.author),\n };\n}\n\n/**\n * `RoadmapItem` is the one row type the card reads WHOLE, so this decoder\n * carries no defaults literal — every field is read off the row.\n *\n * `upvotes` / `downvotes` / `quarter` are required `number`/`string` props the\n * card renders directly. Read off an untyped row they were `any`, so a row\n * without them rendered the miss (a blank vote count). They now fall back to\n * `0` / `''`, matching how the card renders a genuinely zero-vote item.\n */\nfunction decodeRoadmapRow(row: unknown): RoadmapItem {\n const record = asRecord(row);\n const assignees: NonNullable<RoadmapItem['assignees']> = [];\n for (const entry of arrayOf(record.assignees)) {\n const assignee = asRecord(entry);\n assignees.push({\n id: numOrNull(assignee, 'id') ?? 0,\n name: strOrNull(assignee, 'name'),\n avatarUrl: strOrNull(assignee, 'avatarUrl'),\n });\n }\n return {\n id: str(record, 'id'),\n title: str(record, 'title'),\n description: str(record, 'description'),\n status: str(record, 'status'),\n statusColor: str(record, 'statusColor'),\n icon: strOrNull(record, 'icon'),\n figmaUrl: strOrNull(record, 'figmaUrl'),\n screenshots: stringList(record.screenshots),\n targetVersion: strOrNull(record, 'targetVersion'),\n upvotes: numOrNull(record, 'upvotes') ?? 0,\n downvotes: numOrNull(record, 'downvotes') ?? 0,\n quarter: str(record, 'quarter'),\n clickupUrl: str(record, 'clickupUrl'),\n customItemId: numOrNull(record, 'customItemId'),\n assignees,\n };\n}\n\n/**\n * Program rows (podcast / webinar / event) keep their EXTRA columns.\n *\n * `<ProgramCard>` is generic over the item, and the config the rail threads in\n * is an `AnyProgramConfig` — `ProgramConfig<BaseProgramItem &\n * Record<string, unknown>>` — precisely so per-program columns ride along. The\n * card branches on `'duration_seconds' in item` / `'location_name' in item` /\n * `'start_at' in item`, so dropping the unrecognised columns would silently\n * strip a podcast's runtime and an event's venue. The raw row is spread first\n * and the base fields are decoded over it.\n */\nfunction decodeProgramRow(row: unknown): BaseProgramItem & Record<string, unknown> {\n const record = asRecord(row);\n return {\n ...record,\n id: str(record, 'id'),\n title: str(record, 'title'),\n description: strOrNull(record, 'description'),\n cover_url: strOrNull(record, 'cover_url'),\n date: str(record, 'date'),\n external_url: strOrNull(record, 'external_url'),\n hosts: decodeProgramHosts(record.hosts),\n };\n}\n\n/** The two employee-entry cards already declare MINIMAL row shapes\n * (`EmployeeEntryCardData` + one date column each), so their decoders read\n * exactly the card's fields with nothing left over. */\nfunction decodeEmployeeEntryRow(row: unknown): WhatIShippedCardData & HowIWorkCardData & AiPromptCardData {\n const record = asRecord(row);\n const department = asRecord(record.department);\n const stepCount = record.step_count;\n return {\n title: strOrNull(record, 'title'),\n summary: strOrNull(record, 'summary'),\n status: strOrNull(record, 'status'),\n featured_image: strOrNull(record, 'featured_image'),\n main_video_thumbnail: strOrNull(record, 'main_video_thumbnail'),\n author: decodeEntityAuthor(record.author),\n entry_month: strOrNull(record, 'entry_month'),\n session_date: strOrNull(record, 'session_date'),\n discipline: strOrNull(record, 'discipline'),\n published_at: strOrNull(record, 'published_at'),\n department: record.department ? { name: strOrNull(department, 'name') } : null,\n step_count: typeof stepCount === 'number' ? stepCount : null,\n };\n}\n\n// =============================================================================\n// Registry\n// =============================================================================\n\n/** Everything a card branch needs beyond its own row — computed once per card\n * by the rail's dispatcher and shared by every entry. */\nexport interface RelatedCardContext {\n /** Card density for this group, from `CONTENT_REF_GROUPS`. */\n size: CardSize;\n /** `size` with `'lg'` collapsed to `'default'` — most card variants accept\n * only that pair. */\n legacySize: 'default' | 'sm';\n href: string;\n targetPlatform: string | null;\n /** `null` = the host surfaced no URL; the card stays in non-anchor mode. */\n linkProps: CardLinkAnchorProps | null;\n /** `{ target, rel }` for the cards that take them as separate props. */\n anchorAttrs: Pick<CardLinkAnchorProps, 'target' | 'rel'>;\n /** Branded OG fallback for cards whose row has no featured image. */\n placeholderUrl?: string;\n extras?: ChatCardDispatchExtras;\n}\n\n/** One registered content type. `Row` is erased here — `cardEntry` below is\n * what keeps each branch's row type concrete. */\nexport interface RelatedCardRegistryEntry {\n /** Sized to match the resolved card exactly (zero layout shift). */\n skeleton: (size: CardSize) => React.ReactNode;\n render: (row: unknown, ctx: RelatedCardContext) => React.ReactNode;\n}\n\n/**\n * Register one type with its OWN row type.\n *\n * `Row` is bound by the definition object and never escapes: `render` is\n * handed a decoded `Row`, and the stored entry exposes only\n * `(row: unknown) => ReactNode`. That is what lets a single registry hold ten\n * heterogeneous row shapes without a shared supertype — the job `item: any`\n * used to do, minus the promise it could not keep.\n */\nfunction cardEntry<Row>(definition: {\n skeleton: (size: CardSize) => React.ReactNode;\n decode: (row: unknown) => Row;\n render: (row: Row, ctx: RelatedCardContext) => React.ReactNode;\n}): RelatedCardRegistryEntry {\n return {\n skeleton: definition.skeleton,\n render: (row, ctx) => definition.render(definition.decode(row), ctx),\n };\n}\n\n/** Podcast / webinar / event share one card + one skeleton and differ only by\n * which host-supplied `ProgramConfig` they render with. A group whose config\n * the host didn't supply renders nothing (the skeleton still reserves its\n * height, so a rail that never resolves collapses instead of flickering). */\nfunction programEntry(configKey: 'podcast' | 'webinar' | 'event'): RelatedCardRegistryEntry {\n return cardEntry({\n skeleton: size => <ProgramCardSkeleton size={size === 'sm' ? 'sm' : 'default'} />,\n decode: decodeProgramRow,\n render: (item, ctx) => {\n const config = ctx.extras?.programConfigs?.[configKey];\n if (!config) return null;\n return (\n <ProgramCard\n config={config}\n item={item}\n size={ctx.legacySize}\n href={ctx.href}\n targetPlatform={ctx.targetPlatform}\n placeholderUrl={ctx.placeholderUrl}\n {...ctx.anchorAttrs}\n />\n );\n },\n });\n}\n\n/** The three ClickUp-backed types render the same card, distinguished by\n * `cardType` (drives the compact icon slot). */\nfunction roadmapEntry(cardType: 'roadmap_item' | 'delivery_item' | 'internal_task'): RelatedCardRegistryEntry {\n return cardEntry({\n skeleton: size => <RoadmapCardSkeleton size={size === 'sm' ? 'sm' : 'default'} />,\n decode: decodeRoadmapRow,\n render: (item, ctx) => (\n <RoadmapCard\n item={item}\n href={ctx.href}\n targetPlatform={ctx.targetPlatform}\n userVote={null}\n onVote={() => {}}\n size={ctx.legacySize}\n cardType={cardType}\n {...ctx.anchorAttrs}\n />\n ),\n });\n}\n\nexport const RELATED_CARD_REGISTRY: Record<string, RelatedCardRegistryEntry> = {\n blog_post_existing: cardEntry({\n skeleton: size => <BlogCardSkeleton size={size === 'sm' ? 'sm' : 'default'} />,\n decode: decodeBlogRow,\n render: (post, ctx) => (\n <BlogCard\n post={post}\n size={ctx.legacySize}\n href={ctx.href}\n targetPlatform={ctx.targetPlatform}\n placeholderUrl={ctx.placeholderUrl}\n {...ctx.anchorAttrs}\n />\n ),\n }),\n\n case_study: cardEntry({\n skeleton: size => <CaseStudyCardSkeleton size={size === 'sm' ? 'sm' : 'default'} />,\n decode: decodeCaseStudyRow,\n render: (study, ctx) => (\n <CaseStudyCard\n study={study}\n size={ctx.legacySize}\n href={ctx.href}\n targetPlatform={ctx.targetPlatform}\n placeholderUrl={ctx.placeholderUrl}\n {...ctx.anchorAttrs}\n />\n ),\n }),\n\n customer_interview: cardEntry({\n skeleton: size => <CustomerInterviewCardSkeleton size={size === 'sm' ? 'sm' : 'default'} />,\n decode: decodeCustomerInterviewRow,\n render: (interview, ctx) => (\n <CustomerInterviewCard\n interview={interview}\n size={ctx.legacySize}\n href={ctx.href}\n targetPlatform={ctx.targetPlatform}\n placeholderUrl={ctx.placeholderUrl}\n {...ctx.anchorAttrs}\n />\n ),\n }),\n\n /**\n * Product releases derive their whole prop bundle through a HOST seam\n * (`extras.buildProductReleaseCardProps`, defaulting to the lib builder)\n * which already takes `unknown` — so this entry's row type is the bare\n * record, and the three props the rail sets itself are read off it.\n */\n product_release: cardEntry({\n skeleton: size => <ProductReleaseCardSkeleton size={size === 'sm' ? 'sm' : 'lg'} />,\n decode: asRecord,\n render: (release, ctx) => {\n const buildReleaseProps = ctx.extras?.buildProductReleaseCardProps ?? buildProductReleaseCardProps;\n const releaseProps = buildReleaseProps(release);\n return (\n <ProductReleaseCard\n size={ctx.size === 'sm' ? 'sm' : 'lg'}\n // `title` and `version` are REQUIRED `string` props. Read off an\n // untyped row they were `any`, so a release row missing either one\n // rendered an empty heading and a version pill reading \"vundefined\".\n // `summary` is `string | null | undefined` and the card renders\n // `summary ?? ''`, so a dropped one is indistinguishable from null.\n title={str(release, 'title')}\n summary={rowString(release, 'summary')}\n version={str(release, 'version')}\n {...releaseProps}\n // The card wraps in `<a {...anchorProps}>` ONLY when\n // `anchorProps.href` is set — `undefined` (not an empty object)\n // keeps it in non-anchor mode instead of rendering a dead <a>.\n anchorProps={ctx.linkProps ?? undefined}\n />\n );\n },\n }),\n\n podcast: programEntry('podcast'),\n webinar: programEntry('webinar'),\n event: programEntry('event'),\n\n investor_update: cardEntry({\n skeleton: size => <InvestorUpdateCardSkeleton size={size === 'sm' ? 'sm' : 'default'} />,\n decode: decodeInvestorUpdateRow,\n render: (update, ctx) => (\n <InvestorUpdateCard\n update={update}\n size={ctx.legacySize}\n href={ctx.href}\n targetPlatform={ctx.targetPlatform}\n placeholderUrl={ctx.placeholderUrl}\n {...ctx.anchorAttrs}\n />\n ),\n }),\n\n /** The rich CATALOG variant (hero + author grid, clamped description) — the\n * step-numbered 'default' variant is for the guide detail page's \"More in\n * section\" rail, not this full-width row. */\n onboarding_guide: cardEntry({\n skeleton: size => <OnboardingGuideCardSkeleton size={size === 'sm' ? 'sm' : 'catalog'} />,\n decode: decodeOnboardingGuideRow,\n render: (guide, ctx) => (\n <OnboardingGuideCard\n guide={guide}\n size={ctx.size === 'sm' ? 'sm' : 'catalog'}\n href={ctx.href}\n targetPlatform={ctx.targetPlatform}\n placeholderUrl={ctx.placeholderUrl}\n {...ctx.anchorAttrs}\n />\n ),\n }),\n\n /** THE single What I Shipped card — same lib component the people-hub\n * dashboard renders. `anchorProps` makes the whole card a click-through\n * (the rail is read-only — no owner actions). Only pass it with a REAL\n * href: an object with `href: undefined` is still truthy and would wrap the\n * card in a dead <a>. */\n what_i_shipped: cardEntry({\n skeleton: () => <WhatIShippedCardSkeleton />,\n decode: decodeEmployeeEntryRow,\n render: (entry, ctx) => (\n <WhatIShippedCard\n entry={entry}\n placeholderUrl={ctx.placeholderUrl}\n anchorProps={ctx.linkProps ?? (ctx.href ? { href: ctx.href, ...ctx.anchorAttrs } : undefined)}\n />\n ),\n }),\n\n /** Same shared employee-entry shape + anchor contract as What I Shipped. */\n how_i_work: cardEntry({\n skeleton: () => <HowIWorkCardSkeleton />,\n decode: decodeEmployeeEntryRow,\n render: (entry, ctx) => (\n <HowIWorkCard\n entry={entry}\n placeholderUrl={ctx.placeholderUrl}\n anchorProps={ctx.linkProps ?? (ctx.href ? { href: ctx.href, ...ctx.anchorAttrs } : undefined)}\n />\n ),\n }),\n\n /** Same shared employee-entry shape + anchor contract as What I Shipped. */\n ai_prompt: cardEntry({\n skeleton: () => <AiPromptCardSkeleton />,\n decode: decodeEmployeeEntryRow,\n render: (entry, ctx) => (\n <AiPromptCard\n entry={entry}\n placeholderUrl={ctx.placeholderUrl}\n anchorProps={ctx.linkProps ?? (ctx.href ? { href: ctx.href, ...ctx.anchorAttrs } : undefined)}\n />\n ),\n }),\n\n roadmap_item: roadmapEntry('roadmap_item'),\n delivery_item: roadmapEntry('delivery_item'),\n internal_task: roadmapEntry('internal_task'),\n};\n"]}
|