doccupine 0.0.147 → 0.0.149

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.
Files changed (55) hide show
  1. package/dist/generator/app-scaffolder.js +1 -0
  2. package/dist/generator/icon-asset-manager.d.ts +13 -0
  3. package/dist/generator/icon-asset-manager.js +87 -0
  4. package/dist/generator/page-renderer.js +14 -3
  5. package/dist/generator/project-config-repository.d.ts +3 -1
  6. package/dist/generator/project-config-repository.js +9 -1
  7. package/dist/generator/public-asset-manager.d.ts +1 -0
  8. package/dist/generator/public-asset-manager.js +11 -0
  9. package/dist/generator/watch-coordinator.d.ts +2 -0
  10. package/dist/generator/watch-coordinator.js +31 -2
  11. package/dist/lib/generated-artifacts.d.ts +3 -0
  12. package/dist/lib/generated-artifacts.js +23 -0
  13. package/dist/lib/layout.js +14 -4
  14. package/dist/lib/metadata.js +8 -8
  15. package/dist/lib/output-safety.js +1 -0
  16. package/dist/lib/structures.js +2 -2
  17. package/dist/mdx-to-nextjs-generator.d.ts +2 -0
  18. package/dist/mdx-to-nextjs-generator.js +10 -1
  19. package/dist/templates/app/theme.d.ts +1 -1
  20. package/dist/templates/app/theme.js +1 -2
  21. package/dist/templates/components/Chat.d.ts +1 -1
  22. package/dist/templates/components/Chat.js +235 -795
  23. package/dist/templates/components/SearchDocs.d.ts +1 -1
  24. package/dist/templates/components/SearchDocs.js +20 -15
  25. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  26. package/dist/templates/components/SearchModalContent.js +7 -1
  27. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  28. package/dist/templates/components/layout/CherryThemeProvider.js +33 -30
  29. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  30. package/dist/templates/components/layout/DocsComponents.js +9 -8
  31. package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
  32. package/dist/templates/components/layout/DocsNavigation.js +2 -3
  33. package/dist/templates/components/layout/Footer.d.ts +1 -1
  34. package/dist/templates/components/layout/Footer.js +2 -4
  35. package/dist/templates/components/layout/Header.d.ts +1 -1
  36. package/dist/templates/components/layout/Header.js +3 -3
  37. package/dist/templates/components/layout/StaticLinks.d.ts +1 -1
  38. package/dist/templates/components/layout/StaticLinks.js +2 -3
  39. package/dist/templates/env.example.d.ts +1 -1
  40. package/dist/templates/env.example.js +8 -0
  41. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  42. package/dist/templates/mdx/commands.mdx.js +17 -1
  43. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  44. package/dist/templates/mdx/globals.mdx.js +27 -4
  45. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  46. package/dist/templates/mdx/media-and-assets.mdx.js +3 -7
  47. package/dist/templates/mdx/theme.mdx.d.ts +1 -1
  48. package/dist/templates/mdx/theme.mdx.js +2 -0
  49. package/dist/templates/next.config.js +40 -0
  50. package/dist/templates/package.js +11 -11
  51. package/dist/templates/utils/icons.d.ts +1 -0
  52. package/dist/templates/utils/icons.js +44 -0
  53. package/package.json +4 -4
  54. package/dist/templates/components/ChatStyles.d.ts +0 -1
  55. package/dist/templates/components/ChatStyles.js +0 -695
@@ -1,3 +1,3 @@
1
1
  export declare const SIDEBAR_WIDTH = 280;
2
2
  export declare const CHAT_WIDTH = 420;
3
- export declare const themeTemplate = "\"use client\";\nimport customThemeJson from \"@/theme.json\";\n\n// Users can only override the brand palette via theme.json \u2014 semantic tokens\n// (accent, surface, etc.) are derived in GlobalStyles from the brand colors\n// and are not directly overridable.\ntype CustomColors = Omit<\n Colors,\n \"accent\" | \"accentStrong\" | \"accentMuted\" | \"surface\"\n>;\n\ninterface CustomTheme {\n default?: Partial<CustomColors>;\n dark?: Partial<CustomColors>;\n}\n\nconst customTheme = customThemeJson as CustomTheme;\n\nconst breakpoints: Breakpoints = {\n xs: 0,\n sm: 576,\n md: 768,\n lg: 992,\n xl: 1200,\n xxl: 1440,\n xxxl: 1920,\n};\n\nexport function mq(minWidth: keyof Breakpoints) {\n return `@media screen and (min-width: ${breakpoints[minWidth]}px)`;\n}\n\nconst spacing: Spacing = {\n maxWidth: { xs: \"1280px\", xxxl: \"1440px\" },\n padding: { xs: \"20px\", lg: \"40px\" },\n radius: { xs: \"6px\", lg: \"12px\", xl: \"30px\" },\n gridGap: { xs: \"20px\", lg: \"40px\" },\n};\n\n// Resolved hex palettes for each mode. GlobalStyles emits them as CSS custom\n// properties, one block per mode, and that is where every painted color\n// actually comes from \u2014 the theme objects below only reference those variables.\n// Custom theme.json overrides are merged here, so they flow through both.\nexport const colorsLight: CustomColors = {\n primaryLight: \"#d1d5db\",\n primary: \"#556272\",\n primaryDark: \"#374151\",\n secondaryLight: \"#c4b5fd\",\n secondary: \"#8b5cf6\",\n secondaryDark: \"#5b21b6\",\n tertiaryLight: \"#86efac\",\n tertiary: \"#22c55e\",\n tertiaryDark: \"#15803d\",\n grayLight: \"#e5e7eb\",\n gray: \"#9ca3af\",\n grayDark: \"#4b5563\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#000000\",\n light: \"#ffffff\",\n ...(customTheme.default\n ? (customTheme.default as Partial<CustomColors>)\n : {}),\n};\n\nexport const colorsDark: CustomColors = {\n primaryLight: \"#9ca3af\",\n primary: \"#6b7280\",\n primaryDark: \"#374151\",\n secondaryLight: \"#ddd6fe\",\n secondary: \"#a78bfa\",\n secondaryDark: \"#7c3aed\",\n tertiaryLight: \"#6ee7b7\",\n tertiary: \"#10b981\",\n tertiaryDark: \"#065f46\",\n grayLight: \"#1a1a1a\",\n gray: \"#454444\",\n grayDark: \"#808080\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#ffffff\",\n light: \"#000000\",\n ...(customTheme.dark ? (customTheme.dark as Partial<CustomColors>) : {}),\n};\n\nexport const shadowsLight: Shadows = {\n xs: \"0px 4px 4px 0px rgba(18, 18, 18, 0.04), 0px 1px 3px 0px rgba(39, 41, 45, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(18, 18, 18, 0.08), 0px 1px 3px 0px rgba(39, 41, 45, 0.04)\",\n md: \"0px 8px 8px 0px rgba(18, 18, 18, 0.16), 0px 2px 3px 0px rgba(39, 41, 45, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(18, 18, 18, 0.20), 0px 2px 3px 0px rgba(39, 41, 45, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(18, 18, 18, 0.24), 0px 2px 3px 0px rgba(39, 41, 45, 0.12)\",\n};\n\nexport const shadowsDark: Shadows = {\n xs: \"0px 4px 4px 0px rgba(255, 255, 255, 0.04), 0px 1px 3px 0px rgba(255, 255, 255, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(255, 255, 255, 0.08), 0px 1px 3px 0px rgba(255, 255, 255, 0.04)\",\n md: \"0px 8px 8px 0px rgba(255, 255, 255, 0.16), 0px 2px 3px 0px rgba(255, 255, 255, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(255, 255, 255, 0.20), 0px 2px 3px 0px rgba(255, 255, 255, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(255, 255, 255, 0.24), 0px 2px 3px 0px rgba(255, 255, 255, 0.12)\",\n};\n\nconst fonts: Fonts = {\n text: \"Inter\",\n head: \"Inter\",\n mono: \"Roboto Mono, monospace\",\n};\n\nconst fontSizes: FontSizes = {\n hero1: { xs: \"72px\", lg: \"128px\" },\n hero2: { xs: \"60px\", lg: \"96px\" },\n hero3: { xs: \"36px\", lg: \"72px\" },\n\n h1: { xs: \"40px\", lg: \"60px\" },\n h2: { xs: \"30px\", lg: \"36px\" },\n h3: { xs: \"28px\", lg: \"30px\" },\n h4: { xs: \"24px\", lg: \"26px\" },\n h5: { xs: \"18px\", lg: \"20px\" },\n h6: { xs: \"16px\", lg: \"18px\" },\n\n text: { xs: \"14px\", lg: \"16px\" },\n strong: { xs: \"14px\", lg: \"16px\" },\n small: { xs: \"12px\", lg: \"14px\" },\n\n blockquote: { xs: \"16px\", lg: \"18px\" },\n code: { xs: \"14px\", lg: \"16px\" },\n\n button: { xs: \"16px\", lg: \"16px\" },\n buttonBig: { xs: \"18px\", lg: \"18px\" },\n buttonSmall: { xs: \"14px\", lg: \"14px\" },\n\n input: { xs: \"16px\", lg: \"16px\" },\n inputBig: { xs: \"18px\", lg: \"18px\" },\n inputSmall: { xs: \"14px\", lg: \"14px\" },\n};\n\nconst lineHeights: LineHeights = {\n hero1: { xs: \"1.1\", lg: \"1.1\" },\n hero2: { xs: \"1.1\", lg: \"1.1\" },\n hero3: { xs: \"1.17\", lg: \"1.1\" },\n\n h1: { xs: \"1\", lg: \"1.07\" },\n h2: { xs: \"1.2\", lg: \"1.2\" },\n h3: { xs: \"1.3\", lg: \"1.5\" },\n h4: { xs: \"1.3\", lg: \"1.5\" },\n h5: { xs: \"1.6\", lg: \"1.5\" },\n h6: { xs: \"1.6\", lg: \"1.6\" },\n\n text: { xs: \"1.7\", lg: \"1.7\" },\n strong: { xs: \"1.7\", lg: \"1.7\" },\n small: { xs: \"1.7\", lg: \"1.7\" },\n\n blockquote: { xs: \"1.7\", lg: \"1.7\" },\n code: { xs: \"1.7\", lg: \"1.7\" },\n\n button: { xs: \"1\", lg: \"1\" },\n buttonBig: { xs: \"1\", lg: \"1\" },\n buttonSmall: { xs: \"1\", lg: \"1\" },\n\n input: { xs: \"1\", lg: \"1\" },\n inputBig: { xs: \"1\", lg: \"1\" },\n inputSmall: { xs: \"1\", lg: \"1\" },\n};\n\n// Builds the full Colors record for a mode: the resolved brand palette plus\n// the semantic tokens derived from it. Used here only as the key template for\n// the CSS-variable theme below; the resolved values themselves are emitted as\n// custom properties by GlobalStyles.\nexport function buildColors(palette: CustomColors, isDark: boolean): Colors {\n const accent = isDark ? palette.primaryLight : palette.primaryDark;\n return {\n ...palette,\n accent,\n // accent shifted ~10% toward black (light mode) or white (dark mode).\n accentStrong: `color-mix(in srgb, ${accent} 90%, ${isDark ? \"white\" : \"black\"})`,\n accentMuted: isDark ? palette.grayDark : palette.primary,\n surface: isDark ? palette.dark : palette.light,\n };\n}\n\n// Maps every key of a token record to the CSS custom property that holds its\n// value, keeping the record's exact shape. Passing the resolved light objects\n// as templates means a new token can never be forgotten here.\nfunction cssVarTokens<T extends object>(prefix: string, template: T): T {\n return Object.fromEntries(\n Object.keys(template).map((key) => [key, `var(--${prefix}-${key})`]),\n ) as T;\n}\n\n// Every painted color and shadow resolves through a CSS custom property rather\n// than a literal, so the CSS styled-components generates is identical in light\n// and dark mode. That is what makes a statically rendered page paint the right\n// theme on its first frame: the data-theme attribute the blocking script in the\n// root layout stamps on <html> before paint selects the variable block, and\n// nothing has to wait for hydration to swap a theme object. `theme` and\n// `themeDark` therefore differ only in `isDark`, which Cherry's\n// ClientThemeProvider reads to persist the choice, and which\n// ThemeModeAttribute mirrors back onto the attribute.\nconst colors = cssVarTokens(\"color\", buildColors(colorsLight, false));\nconst shadows = cssVarTokens(\"shadow\", shadowsLight);\n\nexport const theme: Theme = {\n breakpoints,\n spacing,\n colors,\n shadows,\n fonts,\n fontSizes,\n lineHeights,\n isDark: false,\n};\n\nexport const themeDark: Theme = {\n ...theme,\n isDark: true,\n};\n\ninterface Breakpoints<TNumber = number> {\n xs: TNumber;\n sm: TNumber;\n md: TNumber;\n lg: TNumber;\n xl: TNumber;\n xxl: TNumber;\n xxxl: TNumber;\n}\n\ninterface Spacing<TString = string> {\n maxWidth: { xs: TString; xxxl: TString };\n padding: { xs: TString; lg: TString };\n radius: { xs: TString; lg: TString; xl: TString };\n gridGap: { xs: TString; lg: TString };\n}\n\n// Matches cherry-styled-components' Colors shape for the brand keys, plus a\n// handful of semantic tokens derived from the brand palette by buildColors.\n// The brand keys (primaryLight\u2026light) are customizable via theme.json; the\n// semantic keys (accent*, surface) are derived and not overridable \u2014 see\n// CustomColors above.\ninterface Colors<TString = string> {\n primaryLight: TString;\n primary: TString;\n primaryDark: TString;\n\n secondaryLight: TString;\n secondary: TString;\n secondaryDark: TString;\n\n tertiaryLight: TString;\n tertiary: TString;\n tertiaryDark: TString;\n\n grayLight: TString;\n gray: TString;\n grayDark: TString;\n\n success: TString;\n error: TString;\n warning: TString;\n info: TString;\n\n dark: TString;\n light: TString;\n\n /** High-contrast accent text. Was: isDark ? primaryLight : primaryDark. */\n accent: TString;\n /** Slightly stronger accent (lightened/darkened by ~10%). */\n accentStrong: TString;\n /** Muted body text. Was: isDark ? grayDark : primary. */\n accentMuted: TString;\n /** Elevated surface color, white-ish in both modes. Was: isDark ? dark : light. */\n surface: TString;\n}\n\ninterface Shadows<TString = string> {\n xs: TString;\n sm: TString;\n md: TString;\n lg: TString;\n xl: TString;\n}\n\ninterface Fonts<TString = string> {\n head: TString;\n text: TString;\n mono: TString;\n}\n\ninterface FontSizes<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\ninterface LineHeights<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\nexport interface Theme {\n breakpoints: Breakpoints;\n spacing: Spacing;\n colors: Colors;\n shadows: Shadows;\n fonts: Fonts;\n fontSizes: FontSizes;\n lineHeights: LineHeights;\n isDark: boolean;\n}\n";
3
+ export declare const themeTemplate = "import customThemeJson from \"@/theme.json\";\n\n// Users can only override the brand palette via theme.json \u2014 semantic tokens\n// (accent, surface, etc.) are derived in GlobalStyles from the brand colors\n// and are not directly overridable.\ntype CustomColors = Omit<\n Colors,\n \"accent\" | \"accentStrong\" | \"accentMuted\" | \"surface\"\n>;\n\ninterface CustomTheme {\n default?: Partial<CustomColors>;\n dark?: Partial<CustomColors>;\n}\n\nconst customTheme = customThemeJson as CustomTheme;\n\nconst breakpoints: Breakpoints = {\n xs: 0,\n sm: 576,\n md: 768,\n lg: 992,\n xl: 1200,\n xxl: 1440,\n xxxl: 1920,\n};\n\nexport function mq(minWidth: keyof Breakpoints) {\n return `@media screen and (min-width: ${breakpoints[minWidth]}px)`;\n}\n\nconst spacing: Spacing = {\n maxWidth: { xs: \"1280px\", xxxl: \"1440px\" },\n padding: { xs: \"20px\", lg: \"40px\" },\n radius: { xs: \"6px\", lg: \"12px\", xl: \"30px\" },\n gridGap: { xs: \"20px\", lg: \"40px\" },\n};\n\n// Resolved hex palettes for each mode. GlobalStyles emits them as CSS custom\n// properties, one block per mode, and that is where every painted color\n// actually comes from \u2014 the theme objects below only reference those variables.\n// Custom theme.json overrides are merged here, so they flow through both.\nexport const colorsLight: CustomColors = {\n primaryLight: \"#d1d5db\",\n primary: \"#556272\",\n primaryDark: \"#374151\",\n secondaryLight: \"#c4b5fd\",\n secondary: \"#8b5cf6\",\n secondaryDark: \"#5b21b6\",\n tertiaryLight: \"#86efac\",\n tertiary: \"#22c55e\",\n tertiaryDark: \"#15803d\",\n grayLight: \"#e5e7eb\",\n gray: \"#9ca3af\",\n grayDark: \"#4b5563\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#000000\",\n light: \"#ffffff\",\n ...(customTheme.default\n ? (customTheme.default as Partial<CustomColors>)\n : {}),\n};\n\nexport const colorsDark: CustomColors = {\n primaryLight: \"#9ca3af\",\n primary: \"#6b7280\",\n primaryDark: \"#374151\",\n secondaryLight: \"#ddd6fe\",\n secondary: \"#a78bfa\",\n secondaryDark: \"#7c3aed\",\n tertiaryLight: \"#6ee7b7\",\n tertiary: \"#10b981\",\n tertiaryDark: \"#065f46\",\n grayLight: \"#1a1a1a\",\n gray: \"#454444\",\n grayDark: \"#808080\",\n success: \"#84cc16\",\n error: \"#ef4444\",\n warning: \"#eab308\",\n info: \"#06b6d4\",\n dark: \"#ffffff\",\n light: \"#000000\",\n ...(customTheme.dark ? (customTheme.dark as Partial<CustomColors>) : {}),\n};\n\nexport const shadowsLight: Shadows = {\n xs: \"0px 4px 4px 0px rgba(18, 18, 18, 0.04), 0px 1px 3px 0px rgba(39, 41, 45, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(18, 18, 18, 0.08), 0px 1px 3px 0px rgba(39, 41, 45, 0.04)\",\n md: \"0px 8px 8px 0px rgba(18, 18, 18, 0.16), 0px 2px 3px 0px rgba(39, 41, 45, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(18, 18, 18, 0.20), 0px 2px 3px 0px rgba(39, 41, 45, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(18, 18, 18, 0.24), 0px 2px 3px 0px rgba(39, 41, 45, 0.12)\",\n};\n\nexport const shadowsDark: Shadows = {\n xs: \"0px 4px 4px 0px rgba(255, 255, 255, 0.04), 0px 1px 3px 0px rgba(255, 255, 255, 0.02)\",\n sm: \"0px 4px 4px 0px rgba(255, 255, 255, 0.08), 0px 1px 3px 0px rgba(255, 255, 255, 0.04)\",\n md: \"0px 8px 8px 0px rgba(255, 255, 255, 0.16), 0px 2px 3px 0px rgba(255, 255, 255, 0.06)\",\n lg: \"0px 16px 24px 0px rgba(255, 255, 255, 0.20), 0px 2px 3px 0px rgba(255, 255, 255, 0.08)\",\n xl: \"0px 24px 32px 0px rgba(255, 255, 255, 0.24), 0px 2px 3px 0px rgba(255, 255, 255, 0.12)\",\n};\n\nconst fonts: Fonts = {\n text: \"Inter\",\n head: \"Inter\",\n mono: \"Roboto Mono, monospace\",\n};\n\nconst fontSizes: FontSizes = {\n hero1: { xs: \"72px\", lg: \"128px\" },\n hero2: { xs: \"60px\", lg: \"96px\" },\n hero3: { xs: \"36px\", lg: \"72px\" },\n\n h1: { xs: \"40px\", lg: \"60px\" },\n h2: { xs: \"30px\", lg: \"36px\" },\n h3: { xs: \"28px\", lg: \"30px\" },\n h4: { xs: \"24px\", lg: \"26px\" },\n h5: { xs: \"18px\", lg: \"20px\" },\n h6: { xs: \"16px\", lg: \"18px\" },\n\n text: { xs: \"14px\", lg: \"16px\" },\n strong: { xs: \"14px\", lg: \"16px\" },\n small: { xs: \"12px\", lg: \"14px\" },\n\n blockquote: { xs: \"16px\", lg: \"18px\" },\n code: { xs: \"14px\", lg: \"16px\" },\n\n button: { xs: \"16px\", lg: \"16px\" },\n buttonBig: { xs: \"18px\", lg: \"18px\" },\n buttonSmall: { xs: \"14px\", lg: \"14px\" },\n\n input: { xs: \"16px\", lg: \"16px\" },\n inputBig: { xs: \"18px\", lg: \"18px\" },\n inputSmall: { xs: \"14px\", lg: \"14px\" },\n};\n\nconst lineHeights: LineHeights = {\n hero1: { xs: \"1.1\", lg: \"1.1\" },\n hero2: { xs: \"1.1\", lg: \"1.1\" },\n hero3: { xs: \"1.17\", lg: \"1.1\" },\n\n h1: { xs: \"1\", lg: \"1.07\" },\n h2: { xs: \"1.2\", lg: \"1.2\" },\n h3: { xs: \"1.3\", lg: \"1.5\" },\n h4: { xs: \"1.3\", lg: \"1.5\" },\n h5: { xs: \"1.6\", lg: \"1.5\" },\n h6: { xs: \"1.6\", lg: \"1.6\" },\n\n text: { xs: \"1.7\", lg: \"1.7\" },\n strong: { xs: \"1.7\", lg: \"1.7\" },\n small: { xs: \"1.7\", lg: \"1.7\" },\n\n blockquote: { xs: \"1.7\", lg: \"1.7\" },\n code: { xs: \"1.7\", lg: \"1.7\" },\n\n button: { xs: \"1\", lg: \"1\" },\n buttonBig: { xs: \"1\", lg: \"1\" },\n buttonSmall: { xs: \"1\", lg: \"1\" },\n\n input: { xs: \"1\", lg: \"1\" },\n inputBig: { xs: \"1\", lg: \"1\" },\n inputSmall: { xs: \"1\", lg: \"1\" },\n};\n\n// Builds the full Colors record for a mode: the resolved brand palette plus\n// the semantic tokens derived from it. Used here only as the key template for\n// the CSS-variable theme below; the resolved values themselves are emitted as\n// custom properties by GlobalStyles.\nexport function buildColors(palette: CustomColors, isDark: boolean): Colors {\n const accent = isDark ? palette.primaryLight : palette.primaryDark;\n return {\n ...palette,\n accent,\n // accent shifted ~10% toward black (light mode) or white (dark mode).\n accentStrong: `color-mix(in srgb, ${accent} 90%, ${isDark ? \"white\" : \"black\"})`,\n accentMuted: isDark ? palette.grayDark : palette.primary,\n surface: isDark ? palette.dark : palette.light,\n };\n}\n\n// Maps every key of a token record to the CSS custom property that holds its\n// value, keeping the record's exact shape. Passing the resolved light objects\n// as templates means a new token can never be forgotten here.\nfunction cssVarTokens<T extends object>(prefix: string, template: T): T {\n return Object.fromEntries(\n Object.keys(template).map((key) => [key, `var(--${prefix}-${key})`]),\n ) as T;\n}\n\n// Every painted color and shadow resolves through a CSS custom property rather\n// than a literal, so the CSS styled-components generates is identical in light\n// and dark mode. That is what makes a statically rendered page paint the right\n// theme on its first frame: the data-theme attribute the blocking script in the\n// root layout stamps on <html> before paint selects the variable block, and\n// nothing has to wait for hydration to swap a theme object. `theme` and\n// `themeDark` therefore differ only in `isDark`, which Cherry's\n// ClientThemeProvider reads to persist the choice, and which\n// ThemeModeAttribute mirrors back onto the attribute.\nconst colors = cssVarTokens(\"color\", buildColors(colorsLight, false));\nconst shadows = cssVarTokens(\"shadow\", shadowsLight);\n\nexport const theme: Theme = {\n breakpoints,\n spacing,\n colors,\n shadows,\n fonts,\n fontSizes,\n lineHeights,\n isDark: false,\n};\n\nexport const themeDark: Theme = {\n ...theme,\n isDark: true,\n};\n\ninterface Breakpoints<TNumber = number> {\n xs: TNumber;\n sm: TNumber;\n md: TNumber;\n lg: TNumber;\n xl: TNumber;\n xxl: TNumber;\n xxxl: TNumber;\n}\n\ninterface Spacing<TString = string> {\n maxWidth: { xs: TString; xxxl: TString };\n padding: { xs: TString; lg: TString };\n radius: { xs: TString; lg: TString; xl: TString };\n gridGap: { xs: TString; lg: TString };\n}\n\n// Matches cherry-styled-components' Colors shape for the brand keys, plus a\n// handful of semantic tokens derived from the brand palette by buildColors.\n// The brand keys (primaryLight\u2026light) are customizable via theme.json; the\n// semantic keys (accent*, surface) are derived and not overridable \u2014 see\n// CustomColors above.\ninterface Colors<TString = string> {\n primaryLight: TString;\n primary: TString;\n primaryDark: TString;\n\n secondaryLight: TString;\n secondary: TString;\n secondaryDark: TString;\n\n tertiaryLight: TString;\n tertiary: TString;\n tertiaryDark: TString;\n\n grayLight: TString;\n gray: TString;\n grayDark: TString;\n\n success: TString;\n error: TString;\n warning: TString;\n info: TString;\n\n dark: TString;\n light: TString;\n\n /** High-contrast accent text. Was: isDark ? primaryLight : primaryDark. */\n accent: TString;\n /** Slightly stronger accent (lightened/darkened by ~10%). */\n accentStrong: TString;\n /** Muted body text. Was: isDark ? grayDark : primary. */\n accentMuted: TString;\n /** Elevated surface color, white-ish in both modes. Was: isDark ? dark : light. */\n surface: TString;\n}\n\ninterface Shadows<TString = string> {\n xs: TString;\n sm: TString;\n md: TString;\n lg: TString;\n xl: TString;\n}\n\ninterface Fonts<TString = string> {\n head: TString;\n text: TString;\n mono: TString;\n}\n\ninterface FontSizes<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\ninterface LineHeights<TString = string> {\n hero1: { xs: TString; lg: TString };\n hero2: { xs: TString; lg: TString };\n hero3: { xs: TString; lg: TString };\n\n h1: { xs: TString; lg: TString };\n h2: { xs: TString; lg: TString };\n h3: { xs: TString; lg: TString };\n h4: { xs: TString; lg: TString };\n h5: { xs: TString; lg: TString };\n h6: { xs: TString; lg: TString };\n\n text: { xs: TString; lg: TString };\n strong: { xs: TString; lg: TString };\n small: { xs: TString; lg: TString };\n\n blockquote: { xs: TString; lg: TString };\n code: { xs: TString; lg: TString };\n\n button: { xs: TString; lg: TString };\n buttonBig: { xs: TString; lg: TString };\n buttonSmall: { xs: TString; lg: TString };\n\n input: { xs: TString; lg: TString };\n inputBig: { xs: TString; lg: TString };\n inputSmall: { xs: TString; lg: TString };\n}\n\nexport interface Theme {\n breakpoints: Breakpoints;\n spacing: Spacing;\n colors: Colors;\n shadows: Shadows;\n fonts: Fonts;\n fontSizes: FontSizes;\n lineHeights: LineHeights;\n isDark: boolean;\n}\n";
@@ -1,7 +1,6 @@
1
1
  export const SIDEBAR_WIDTH = 280;
2
2
  export const CHAT_WIDTH = 420;
3
- export const themeTemplate = `"use client";
4
- import customThemeJson from "@/theme.json";
3
+ export const themeTemplate = `import customThemeJson from "@/theme.json";
5
4
 
6
5
  // Users can only override the brand palette via theme.json — semantic tokens
7
6
  // (accent, surface, etc.) are derived in GlobalStyles from the brand colors
@@ -1 +1 @@
1
- export declare const chatTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { IconButton } from \"cherry-styled-components\";\nimport { ArrowUp, LoaderPinwheel, RotateCcw, Sparkles, X } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport { theme } from \"@/app/theme\";\nimport {\n StyledAnswer,\n StyledChat,\n StyledChatForm,\n StyledChatSurface,\n StyledChatTitle,\n StyledChatTitleIconWrapper,\n StyledError,\n StyledGlowSmallButton,\n StyledLoading,\n StyledRainbowButton,\n StyledRainbowInput,\n StyledRainbowInputWrapper,\n StyledSourceLink,\n StyledSources,\n StyledSparkle,\n StyledSparkleContainer,\n} from \"@/components/ChatStyles\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useLockBodyScroll } from \"@/components/LockBodyScroll\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\n\nconst mdxComponents = getMDXComponents({});\n\nconst MOBILE_CHAT_QUERY = `(max-width: ${theme.breakpoints.lg - 1}px)`;\n\nfunction subscribeToMobileChat(callback: () => void) {\n const mediaQuery = window.matchMedia(MOBILE_CHAT_QUERY);\n mediaQuery.addEventListener(\"change\", callback);\n return () => mediaQuery.removeEventListener(\"change\", callback);\n}\n\nfunction getMobileChatSnapshot() {\n return window.matchMedia(MOBILE_CHAT_QUERY).matches;\n}\n\nfunction useIsMobileChat() {\n return useSyncExternalStore(\n subscribeToMobileChat,\n getMobileChatSnapshot,\n () => false,\n );\n}\n\ntype Source = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\ntype Answer = {\n text: string;\n answer?: boolean;\n mdx?: MDXRemoteSerializeResult;\n sources?: Source[];\n};\n\nconst SPARKLE_COLORS = [\n \"#ff6b6b\",\n \"#feca57\",\n \"#48dbfb\",\n \"#ff9ff3\",\n \"#54a0ff\",\n \"#5f27cd\",\n];\n\n// Deterministic sparkle positions to avoid hydration mismatch\nconst SPARKLE_POSITIONS = [\n { left: 8, top: 35 },\n { left: 17, top: 55 },\n { left: 26, top: 28 },\n { left: 35, top: 68 },\n { left: 44, top: 42 },\n { left: 53, top: 75 },\n { left: 62, top: 32 },\n { left: 71, top: 58 },\n { left: 80, top: 45 },\n { left: 89, top: 65 },\n];\n\ninterface RainbowInputProps {\n id?: string;\n value: string;\n onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n placeholder?: string;\n autoComplete?: string;\n \"aria-label\"?: string;\n inputRef?: React.Ref<HTMLInputElement>;\n}\n\nfunction RainbowInput({\n id,\n value,\n onChange,\n placeholder,\n autoComplete,\n \"aria-label\": ariaLabel,\n inputRef,\n}: RainbowInputProps) {\n const [isFocused, setIsFocused] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const isActive = isFocused || isHovered;\n\n const sparkles = SPARKLE_POSITIONS.map((pos, i) => ({\n color: SPARKLE_COLORS[i % SPARKLE_COLORS.length],\n left: pos.left,\n top: pos.top,\n delay: i * 0.12,\n }));\n\n return (\n <StyledRainbowInputWrapper\n $isActive={isActive}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n >\n <StyledSparkleContainer $isActive={isActive}>\n {sparkles.map((sparkle, i) => (\n <StyledSparkle\n key={i}\n $color={sparkle.color}\n $left={sparkle.left}\n $top={sparkle.top}\n $delay={sparkle.delay}\n />\n ))}\n </StyledSparkleContainer>\n <StyledRainbowInput\n ref={inputRef}\n id={id}\n value={value}\n onChange={onChange}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-label={ariaLabel}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n />\n </StyledRainbowInputWrapper>\n );\n}\n\nfunction ChatButtonCTA() {\n const { toggleChat, isOpen } = useContext(ChatContext);\n\n return (\n <StyledGlowSmallButton\n onClick={toggleChat}\n aria-label=\"Ask AI Assistant\"\n $hasContent={isOpen}\n type=\"button\"\n >\n <span>\n <Sparkles size={16} />\n Ask AI\n </span>\n </StyledGlowSmallButton>\n );\n}\n\nfunction Chat() {\n const {\n isOpen,\n question,\n setQuestion,\n loading,\n error,\n answer,\n ask,\n closeChat,\n resetChat,\n chatInputRef,\n } = useContext(ChatContext);\n const chatSurfaceRef = useRef<HTMLDivElement | null>(null);\n const chatScrollRef = useRef<HTMLDivElement | null>(null);\n const scrollFrameRef = useRef<number | null>(null);\n const shouldAutoScrollRef = useRef(true);\n const loadingRef = useRef(loading);\n const isMobileChat = useIsMobileChat();\n const isMobileModal = isOpen && isMobileChat;\n\n useLockBodyScroll(isOpen);\n\n useEffect(() => {\n loadingRef.current = loading;\n }, [loading]);\n\n useLayoutEffect(() => {\n if (isOpen) {\n shouldAutoScrollRef.current = true;\n return;\n }\n\n if (scrollFrameRef.current !== null) {\n cancelAnimationFrame(scrollFrameRef.current);\n scrollFrameRef.current = null;\n }\n }, [isOpen]);\n\n useEffect(() => {\n if (!isOpen || !shouldAutoScrollRef.current) return;\n if (scrollFrameRef.current !== null) return;\n\n scrollFrameRef.current = requestAnimationFrame(() => {\n scrollFrameRef.current = null;\n const scrollContainer = chatScrollRef.current;\n if (!scrollContainer || !shouldAutoScrollRef.current) return;\n const reduceMotion = window.matchMedia(\n \"(prefers-reduced-motion: reduce)\",\n ).matches;\n scrollContainer.scrollTo({\n top: scrollContainer.scrollHeight,\n behavior: reduceMotion || loadingRef.current ? \"auto\" : \"smooth\",\n });\n });\n }, [answer, isOpen, loading]);\n\n useEffect(() => {\n return () => {\n if (scrollFrameRef.current !== null) {\n cancelAnimationFrame(scrollFrameRef.current);\n }\n };\n }, []);\n\n useEffect(() => {\n if (!isMobileModal || !chatSurfaceRef.current) return;\n\n const surface = chatSurfaceRef.current;\n const inertSiblings: Array<{\n element: HTMLElement;\n wasInert: boolean;\n }> = [];\n let current: HTMLElement = surface;\n\n while (current.parentElement) {\n const parent = current.parentElement;\n for (const sibling of Array.from(parent.children)) {\n if (sibling === current || !(sibling instanceof HTMLElement)) continue;\n inertSiblings.push({ element: sibling, wasInert: sibling.inert });\n sibling.inert = true;\n }\n if (parent === document.body) break;\n current = parent;\n }\n\n const containFocus = (event: FocusEvent) => {\n if (event.target instanceof Node && !surface.contains(event.target)) {\n chatInputRef.current?.focus();\n }\n };\n\n document.addEventListener(\"focusin\", containFocus);\n chatInputRef.current?.focus();\n\n return () => {\n document.removeEventListener(\"focusin\", containFocus);\n for (const { element, wasInert } of inertSiblings) {\n element.inert = wasInert;\n }\n };\n }, [chatInputRef, isMobileModal]);\n\n const handleChatScroll = () => {\n const scrollContainer = chatScrollRef.current;\n if (!scrollContainer) return;\n const distanceFromBottom =\n scrollContainer.scrollHeight -\n scrollContainer.scrollTop -\n scrollContainer.clientHeight;\n shouldAutoScrollRef.current =\n distanceFromBottom <= scrollContainer.clientHeight * 0.15;\n };\n\n const handleSurfaceKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"Escape\" && isMobileModal) {\n event.preventDefault();\n event.stopPropagation();\n closeChat();\n return;\n }\n\n if (event.key !== \"Tab\" || !isMobileModal) return;\n const focusable = Array.from(\n chatSurfaceRef.current?.querySelectorAll<HTMLElement>(\n 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n ) ?? [],\n ).filter(\n (element) =>\n element.offsetParent !== null &&\n element.getAttribute(\"aria-hidden\") !== \"true\",\n );\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n return (\n <StyledChatSurface\n ref={chatSurfaceRef}\n $isVisible={isOpen}\n inert={!isOpen}\n aria-hidden={!isOpen}\n role={isMobileModal ? \"dialog\" : \"complementary\"}\n aria-modal={isMobileModal ? \"true\" : undefined}\n aria-label=\"AI Assistant\"\n data-chat-surface\n data-markdown-ignore\n onKeyDownCapture={handleSurfaceKeyDown}\n >\n <StyledChat\n ref={chatScrollRef}\n $isVisible={isOpen}\n onScroll={handleChatScroll}\n >\n <StyledChatTitle>\n <StyledChatTitleIconWrapper>\n <Sparkles />\n <h3>AI Assistant</h3>\n </StyledChatTitleIconWrapper>\n <StyledChatTitleIconWrapper>\n <IconButton\n onClick={resetChat}\n aria-label=\"Reset chat history\"\n title=\"Reset chat history\"\n >\n <RotateCcw />\n </IconButton>\n <IconButton\n onClick={() => closeChat()}\n aria-label=\"Close chat\"\n title=\"Close chat\"\n >\n <X />\n </IconButton>\n </StyledChatTitleIconWrapper>\n </StyledChatTitle>\n {answer &&\n answer.map((a, i) => (\n <React.Fragment key={i}>\n <StyledAnswer $isAnswer={a.answer ?? false}>\n {a.answer && a.mdx ? (\n <MDXRemote {...a.mdx} components={mdxComponents} />\n ) : (\n a.text\n )}\n </StyledAnswer>\n {a.answer && a.sources && a.sources.length > 0 && (\n <StyledSources>\n {a.sources.map((src) => {\n const slug = src.uri\n .replace(\"docs://\", \"\")\n .replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return (\n <StyledSourceLink\n key={src.id}\n href={href}\n onClick={() => {\n if (window.innerWidth <= 992) {\n closeChat();\n }\n }}\n >\n {label}\n </StyledSourceLink>\n );\n })}\n </StyledSources>\n )}\n </React.Fragment>\n ))}\n {loading && !answer[answer.length - 1]?.answer && (\n <StyledLoading>\n Answering<span>.</span>\n <span>.</span>\n <span>.</span>\n </StyledLoading>\n )}\n {error && (\n <StyledError>\n <Callout type=\"danger\">\n <p>\n <strong>Error:</strong> {error}\n </p>\n </Callout>\n </StyledError>\n )}\n </StyledChat>\n\n <StyledChatForm onSubmit={ask} $isVisible={isOpen} data-markdown-ignore>\n <RainbowInput\n id=\"chat-bottom-input\"\n inputRef={chatInputRef}\n value={question}\n onChange={(e) => setQuestion(e.target.value)}\n placeholder=\"Ask AI Assistant...\"\n autoComplete=\"off\"\n aria-label=\"Ask a follow-up question\"\n />\n <StyledRainbowButton\n type=\"submit\"\n disabled={loading || question.trim() === \"\"}\n $hasContent={question.trim().length > 0}\n aria-label={loading ? \"Loading response\" : \"Submit question\"}\n >\n {loading ? <LoaderPinwheel className=\"loading\" /> : <ArrowUp />}\n </StyledRainbowButton>\n </StyledChatForm>\n </StyledChatSurface>\n );\n}\n\nconst ChatContext = createContext<{\n isOpen: boolean;\n setIsOpen: (isOpen: boolean) => void;\n toggleChat: () => void;\n isChatActive: boolean;\n question: string;\n setQuestion: (q: string) => void;\n loading: boolean;\n error: string | null;\n answer: Answer[];\n setAnswer: (answers: Answer[]) => void;\n ask: (e: React.FormEvent) => void;\n askAssistant: (question: string, returnFocusTo?: HTMLElement | null) => void;\n closeChat: (restoreFocus?: boolean) => HTMLElement | null;\n registerSearchClose: (\n closeSearch: (restoreFocus?: boolean) => HTMLElement | null,\n ) => () => void;\n resetChat: () => void;\n chatInputRef: React.RefObject<HTMLInputElement | null>;\n}>({\n isOpen: false,\n setIsOpen: () => {},\n toggleChat: () => {},\n isChatActive: false,\n question: \"\",\n setQuestion: () => {},\n loading: false,\n error: null,\n answer: [],\n setAnswer: () => {},\n ask: () => {},\n askAssistant: () => {},\n closeChat: () => null,\n registerSearchClose: () => () => {},\n resetChat: () => {},\n chatInputRef: { current: null },\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst INITIAL_GREETING = \"Hey there, how can I assist you?\";\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const [isOpen, setIsOpen] = useState(false);\n const [question, setQuestion] = useState(\"\");\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [answer, setAnswer] = useState<Answer[]>([]);\n const abortRef = useRef<AbortController | null>(null);\n const chatInputRef = useRef<HTMLInputElement | null>(null);\n const focusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const restoreFocusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(\n null,\n );\n const pendingRestoreFocusRef = useRef<HTMLElement | null>(null);\n const openerRef = useRef<HTMLElement | null>(null);\n const closeSearchRef = useRef<\n ((restoreFocus?: boolean) => HTMLElement | null) | null\n >(null);\n const isOpenRef = useRef(isOpen);\n\n useEffect(() => {\n isOpenRef.current = isOpen;\n }, [isOpen]);\n\n const showChat = useCallback((returnFocusTo?: HTMLElement | null) => {\n const previousOverlayOpener = closeSearchRef.current?.(false) ?? null;\n const pendingChatOpener = pendingRestoreFocusRef.current;\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n restoreFocusTimeoutRef.current = null;\n }\n pendingRestoreFocusRef.current = null;\n if (!isOpenRef.current) {\n const activeElement = document.activeElement;\n openerRef.current =\n returnFocusTo?.isConnected === true\n ? returnFocusTo\n : previousOverlayOpener?.isConnected === true\n ? previousOverlayOpener\n : pendingChatOpener?.isConnected === true\n ? pendingChatOpener\n : activeElement instanceof HTMLElement &&\n activeElement !== document.body\n ? activeElement\n : null;\n }\n isOpenRef.current = true;\n setIsOpen(true);\n if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);\n focusTimeoutRef.current = setTimeout(() => {\n focusTimeoutRef.current = null;\n chatInputRef.current?.focus();\n }, 0);\n }, []);\n\n // Open the assistant and seed its greeting on the first visit. The opener is\n // captured before the mobile dialog makes the rest of the page inert.\n const openChat = useCallback(() => {\n showChat();\n setAnswer((prev) =>\n prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,\n );\n }, [showChat]);\n\n const closeChat = useCallback((restoreFocus = true) => {\n const pendingOpener = pendingRestoreFocusRef.current;\n if (!restoreFocus && restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n restoreFocusTimeoutRef.current = null;\n pendingRestoreFocusRef.current = null;\n }\n if (!isOpenRef.current) return pendingOpener;\n if (focusTimeoutRef.current) {\n clearTimeout(focusTimeoutRef.current);\n focusTimeoutRef.current = null;\n }\n const activeElement = document.activeElement;\n if (\n activeElement instanceof HTMLElement &&\n activeElement.closest(\"[data-chat-surface]\")\n ) {\n activeElement.blur();\n }\n const opener = openerRef.current;\n openerRef.current = null;\n isOpenRef.current = false;\n setIsOpen(false);\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n }\n if (restoreFocus) {\n pendingRestoreFocusRef.current = opener;\n restoreFocusTimeoutRef.current = setTimeout(() => {\n const focusTarget = pendingRestoreFocusRef.current;\n restoreFocusTimeoutRef.current = null;\n pendingRestoreFocusRef.current = null;\n if (focusTarget?.isConnected) focusTarget.focus();\n }, 0);\n } else {\n pendingRestoreFocusRef.current = null;\n }\n return opener;\n }, []);\n\n const registerSearchClose = useCallback(\n (closeSearch: (restoreFocus?: boolean) => HTMLElement | null) => {\n closeSearchRef.current = closeSearch;\n return () => {\n if (closeSearchRef.current === closeSearch) {\n closeSearchRef.current = null;\n }\n };\n },\n [],\n );\n\n const toggleChat = useCallback(() => {\n if (isOpenRef.current) {\n closeChat();\n } else {\n openChat();\n }\n }, [closeChat, openChat]);\n\n useEffect(() => {\n return () => {\n if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n }\n };\n }, []);\n\n // Global Cmd/Ctrl+I toggles the assistant, but only when chat is enabled.\n useEffect(() => {\n if (!isChatActive) return;\n function handleKeyDown(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"i\") {\n e.preventDefault();\n toggleChat();\n }\n }\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }, [isChatActive, toggleChat]);\n\n async function runQuestion(\n currentQuestion: string,\n returnFocusTo?: HTMLElement | null,\n ) {\n setQuestion(\"\");\n showChat(returnFocusTo);\n setLoading(true);\n setError(null);\n\n const base =\n answer.length > 0 ? answer : [{ text: INITIAL_GREETING, answer: true }];\n const mergedQuestions = [...base, { text: currentQuestion, answer: false }];\n\n setAnswer(mergedQuestions);\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n try {\n const history = answer\n .filter((a) => a.text.trim() !== \"\")\n .slice(-20)\n .map((a) => ({\n role: a.answer ? (\"assistant\" as const) : (\"user\" as const),\n content: a.text.slice(0, 4000),\n }));\n\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ question: currentQuestion, history }),\n signal: controller.signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: Source[] = [];\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n // Don't insert the answer bubble yet - an empty bubble renders a blank\n // gap above the \"Answering...\" loader. The bubble is created on the first\n // streamed token (or the done event) instead, so the loader stays put\n // until real text appears.\n const streamingAnswerIndex = mergedQuestions.length;\n\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop to the\n // outer catch so it renders in the chat's error callout instead\n // of dying in a parse-error log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: Source[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources.filter((s: Source) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n });\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n\n setAnswer((prev) => {\n const newAnswers = [...prev];\n newAnswers[streamingAnswerIndex] = {\n text: streamedContent,\n answer: true,\n sources,\n };\n return newAnswers;\n });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAnswer((prev) => {\n const newAnswers = [...prev];\n newAnswers[streamingAnswerIndex] = {\n text: streamedContent,\n answer: true,\n mdx: mdxSource || undefined,\n sources,\n };\n return newAnswers;\n });\n }\n }\n }\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === \"AbortError\") return;\n setError(err instanceof Error ? err.message : \"Unknown error\");\n } finally {\n abortRef.current = null;\n setLoading(false);\n }\n }\n\n async function ask(e: React.FormEvent) {\n e.preventDefault();\n if (loading || question.trim() === \"\") return;\n await runQuestion(question);\n }\n\n // Bridge from the search modal: hand the typed query to the assistant. If a\n // response is already streaming (loading), we can't submit yet - open the\n // panel and pre-fill the input so the user can send it the moment the\n // current answer finishes. Otherwise submit it right away.\n function askAssistant(\n rawQuestion: string,\n returnFocusTo?: HTMLElement | null,\n ) {\n const trimmed = rawQuestion.trim();\n if (trimmed === \"\") return;\n if (loading) {\n showChat(returnFocusTo);\n setQuestion(trimmed);\n } else {\n void runQuestion(trimmed, returnFocusTo);\n }\n }\n\n function resetChat() {\n abortRef.current?.abort();\n setLoading(false);\n setError(null);\n setAnswer([{ text: INITIAL_GREETING, answer: true }]);\n }\n\n return (\n <ChatContext.Provider\n value={{\n isOpen,\n setIsOpen,\n toggleChat,\n isChatActive,\n question,\n setQuestion,\n loading,\n error,\n answer,\n setAnswer,\n ask,\n askAssistant,\n closeChat,\n registerSearchClose,\n resetChat,\n chatInputRef,\n }}\n >\n {children}\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext, ChatButtonCTA };\n";
1
+ export declare const chatTemplate = "\"use client\";\nimport React, { createContext, useMemo } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport {\n ChatInput,\n ChatMessage,\n ChatMessageList,\n ChatPanel,\n ChatProvider,\n ChatSource,\n ChatSources,\n ChatTyping,\n IconButton,\n Prose,\n useBelowBreakpoint,\n useChat,\n type ChatSendContext,\n type ChatSourceData,\n} from \"cherry-styled-components\";\nimport { RotateCcw } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\n\nconst mdxComponents = getMDXComponents({});\n\ntype RagSource = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\n// Map a retrieval hit onto the chip the transcript renders: docs://<slug>\n// becomes an app-relative href, and the slug's last segment becomes a\n// title-cased label.\nfunction toSourceChip(src: RagSource): ChatSourceData {\n const slug = src.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return { id: src.id, label, href };\n}\n\n// Cherry's ChatProvider owns the transcript, panel state, and streaming\n// bookkeeping; this handler owns the transport: POST the question to\n// /api/rag, stream the SSE frames, and patch the assistant bubble as tokens\n// arrive. The provider bounds `history` to the RAG contract (20 entries,\n// 4000 chars each), swallows aborts, and surfaces thrown errors as `error`.\nasync function sendToAssistant(\n question: string,\n { signal, history, setAssistant }: ChatSendContext,\n) {\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ question, history }),\n signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: ChatSourceData[] = [];\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop so it lands\n // in the provider's error state instead of dying in a parse-error\n // log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: RagSource[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources\n .filter((s) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n })\n .map(toSourceChip);\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n setAssistant(streamedContent, { text: streamedContent, sources });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAssistant(\n mdxSource ? (\n <MDXRemote {...mdxSource} components={mdxComponents} />\n ) : (\n streamedContent\n ),\n { text: streamedContent, sources },\n );\n }\n }\n }\n}\n\nfunction ChatSourceLink({ source }: { source: ChatSourceData }) {\n const { close } = useChat();\n const isMobileChat = useBelowBreakpoint(\"lg\");\n const router = useRouter();\n\n return (\n <ChatSource\n href={source.href}\n onClick={(event) => {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n // ChatSource renders a plain anchor, so route unmodified left clicks\n // client-side to keep the transcript alive; below lg the panel is a\n // fullscreen dialog, so close it to reveal the navigated page.\n event.preventDefault();\n if (isMobileChat) close();\n router.push(source.href);\n }}\n >\n {source.label}\n </ChatSource>\n );\n}\n\nfunction ChatTranscript() {\n const { messages, loading, error } = useChat();\n const lastMessage = messages[messages.length - 1];\n\n return (\n <ChatMessageList>\n {messages.map((message) => (\n <ChatMessage key={message.id} $role={message.role}>\n {message.role === \"assistant\" ? (\n // The docs' typographic context lives on the docs page wrapper,\n // so a rendered MDX answer would arrive margin-less here. Prose\n // $compact is Cherry's document styling for chat replies: a 10px\n // rhythm between elements, inline-code chips, lists, and tables.\n <Prose $compact>{message.content}</Prose>\n ) : (\n message.content\n )}\n {message.role === \"assistant\" &&\n message.sources &&\n message.sources.length > 0 && (\n <ChatSources>\n {message.sources.map((source) => (\n <ChatSourceLink key={source.id} source={source} />\n ))}\n </ChatSources>\n )}\n </ChatMessage>\n ))}\n {loading && lastMessage?.role !== \"assistant\" && <ChatTyping />}\n {error && (\n <Callout type=\"danger\">\n <p>\n <strong>Error:</strong> {error}\n </p>\n </Callout>\n )}\n </ChatMessageList>\n );\n}\n\nfunction ChatActions() {\n const { reset } = useChat();\n\n return (\n <IconButton\n onClick={reset}\n aria-label=\"Reset chat history\"\n title=\"Reset chat history\"\n >\n <RotateCcw />\n </IconButton>\n );\n}\n\nfunction Chat() {\n return (\n <ChatPanel $title=\"AI Assistant\" $actions={<ChatActions />}>\n <ChatTranscript />\n <ChatInput $glow />\n </ChatPanel>\n );\n}\n\n// App-level chat context: only whether the AI assistant is enabled (an LLM\n// provider is configured). Panel state, the transcript, and streaming all\n// live in Cherry's ChatProvider - read those with useChat() from\n// \"cherry-styled-components\".\nconst ChatContext = createContext<{ isChatActive: boolean }>({\n isChatActive: false,\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const value = useMemo(() => ({ isChatActive }), [isChatActive]);\n\n return (\n <ChatContext.Provider value={value}>\n <ChatProvider\n onSend={sendToAssistant}\n shortcut={isChatActive ? \"i\" : null}\n >\n {children}\n </ChatProvider>\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext };\n";