@e-llm-studio/citation 0.0.251 → 0.0.253

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 (271) hide show
  1. package/dist/cjs/features/CognitiveCompare/CitationAnchor.js +1 -1
  2. package/dist/cjs/features/CognitiveCompare/CitationAnchor.js.map +1 -1
  3. package/dist/cjs/features/CognitiveCompare/CitationRenderer.js +1 -1
  4. package/dist/cjs/features/CognitiveCompare/CitationRenderer.js.map +1 -1
  5. package/dist/cjs/features/CognitiveCompare/CitationRendererInner.js +2 -0
  6. package/dist/cjs/features/CognitiveCompare/CitationRendererInner.js.map +1 -0
  7. package/dist/cjs/features/CognitiveCompare/CognitiveCompare.js +1 -1
  8. package/dist/cjs/features/CognitiveCompare/CognitiveCompare.js.map +1 -1
  9. package/dist/cjs/features/CognitiveCompare/CognitiveCompareConstants.js +1 -1
  10. package/dist/cjs/features/CognitiveCompare/CognitiveCompareConstants.js.map +1 -1
  11. package/dist/cjs/features/CognitiveCompare/CognitiveComparehelpers.js +1 -1
  12. package/dist/cjs/features/CognitiveCompare/CognitiveComparehelpers.js.map +1 -1
  13. package/dist/cjs/features/CognitiveCompare/CognitivePopup.js +1 -1
  14. package/dist/cjs/features/CognitiveCompare/CognitivePopup.js.map +1 -1
  15. package/dist/cjs/features/CognitiveCompare/CompareContext.js +1 -1
  16. package/dist/cjs/features/CognitiveCompare/CompareContext.js.map +1 -1
  17. package/dist/cjs/features/CognitiveCompare/GptWebCitationPanel.js +2 -0
  18. package/dist/cjs/features/CognitiveCompare/GptWebCitationPanel.js.map +1 -0
  19. package/dist/cjs/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js +1 -1
  20. package/dist/cjs/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js.map +1 -1
  21. package/dist/cjs/features/CognitiveCompare/Guidelines/components/WebGptPanel.js +1 -1
  22. package/dist/cjs/features/CognitiveCompare/Guidelines/components/WebGptPanel.js.map +1 -1
  23. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/guidelineTargets.js +2 -0
  24. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/guidelineTargets.js.map +1 -0
  25. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/hasGptCitationObjects.js +2 -0
  26. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/hasGptCitationObjects.js.map +1 -0
  27. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js +1 -1
  28. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js.map +1 -1
  29. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/resolveGuidelineSelection.js +2 -0
  30. package/dist/cjs/features/CognitiveCompare/Guidelines/utils/resolveGuidelineSelection.js.map +1 -0
  31. package/dist/cjs/features/CognitiveCompare/components/GuidelineSkeletonLoader.js +2 -0
  32. package/dist/cjs/features/CognitiveCompare/components/GuidelineSkeletonLoader.js.map +1 -0
  33. package/dist/cjs/features/CognitiveCompare/components/LHSSectionRow.js +1 -1
  34. package/dist/cjs/features/CognitiveCompare/components/LHSSectionRow.js.map +1 -1
  35. package/dist/cjs/features/CognitiveCompare/components/RHSSectionRow.js +1 -1
  36. package/dist/cjs/features/CognitiveCompare/components/RHSSectionRow.js.map +1 -1
  37. package/dist/cjs/features/CognitiveCompare/components/SectionAccordion.js +1 -1
  38. package/dist/cjs/features/CognitiveCompare/components/SectionAccordion.js.map +1 -1
  39. package/dist/cjs/features/CognitiveCompare/components/SubSectionAccordion.js +1 -1
  40. package/dist/cjs/features/CognitiveCompare/components/SubSectionAccordion.js.map +1 -1
  41. package/dist/cjs/features/CognitiveCompare/components/SvgConnectors.js +1 -1
  42. package/dist/cjs/features/CognitiveCompare/components/SvgConnectors.js.map +1 -1
  43. package/dist/cjs/features/CognitiveCompare/hooks/memoizedMarkdown.js +1 -1
  44. package/dist/cjs/features/CognitiveCompare/hooks/memoizedMarkdown.js.map +1 -1
  45. package/dist/cjs/features/CognitiveCompare/hooks/useCompareData.js +1 -1
  46. package/dist/cjs/features/CognitiveCompare/hooks/useCompareData.js.map +1 -1
  47. package/dist/cjs/features/CognitiveCompare/hooks/useLinesCalculator.js +1 -1
  48. package/dist/cjs/features/CognitiveCompare/hooks/useLinesCalculator.js.map +1 -1
  49. package/dist/cjs/features/CognitiveCompare/hooks/useOnDemandCitationCache.js +2 -0
  50. package/dist/cjs/features/CognitiveCompare/hooks/useOnDemandCitationCache.js.map +1 -0
  51. package/dist/cjs/features/CognitiveCompare/hooks/useSideBySide.js +1 -1
  52. package/dist/cjs/features/CognitiveCompare/hooks/useSideBySide.js.map +1 -1
  53. package/dist/cjs/features/CognitiveCompare/onDemandCitations/cacheKey.js +2 -0
  54. package/dist/cjs/features/CognitiveCompare/onDemandCitations/cacheKey.js.map +1 -0
  55. package/dist/cjs/features/CognitiveCompare/onDemandCitations/contextBuilder.js +2 -0
  56. package/dist/cjs/features/CognitiveCompare/onDemandCitations/contextBuilder.js.map +1 -0
  57. package/dist/cjs/features/CognitiveCompare/onDemandCitations/href.js +2 -0
  58. package/dist/cjs/features/CognitiveCompare/onDemandCitations/href.js.map +1 -0
  59. package/dist/cjs/features/CognitiveCompare/onDemandCitations/payload.js +2 -0
  60. package/dist/cjs/features/CognitiveCompare/onDemandCitations/payload.js.map +1 -0
  61. package/dist/cjs/features/CognitiveCompare/onDemandCitations/response.js +2 -0
  62. package/dist/cjs/features/CognitiveCompare/onDemandCitations/response.js.map +1 -0
  63. package/dist/cjs/features/CognitiveCompare/utils/normalizeCompactedGfmTables.js +2 -0
  64. package/dist/cjs/features/CognitiveCompare/utils/normalizeCompactedGfmTables.js.map +1 -0
  65. package/dist/cjs/features/CognitiveCompare/utils/normalizeInlineMarkdown.js +2 -0
  66. package/dist/cjs/features/CognitiveCompare/utils/normalizeInlineMarkdown.js.map +1 -0
  67. package/dist/cjs/features/CognitiveCompare/utils/normalizeRedlineMarkdown.js +2 -0
  68. package/dist/cjs/features/CognitiveCompare/utils/normalizeRedlineMarkdown.js.map +1 -0
  69. package/dist/cjs/features/PdfViewer/PdfContainer.js +1 -1
  70. package/dist/cjs/features/PdfViewer/PdfContainer.js.map +1 -1
  71. package/dist/cjs/features/PdfViewer/PdfViewer.js +1 -1
  72. package/dist/cjs/features/PdfViewer/PdfViewer.js.map +1 -1
  73. package/dist/cjs/features/SegmentReviewComponents/ApprovalDescriptionBanner.js +2 -0
  74. package/dist/cjs/features/SegmentReviewComponents/ApprovalDescriptionBanner.js.map +1 -0
  75. package/dist/cjs/features/SegmentReviewComponents/BoundaryCard.js +1 -1
  76. package/dist/cjs/features/SegmentReviewComponents/BoundaryCard.js.map +1 -1
  77. package/dist/cjs/features/SegmentReviewComponents/RevertCard.js +1 -1
  78. package/dist/cjs/features/SegmentReviewComponents/RevertCard.js.map +1 -1
  79. package/dist/cjs/features/SegmentReviewComponents/SaveAsLearningCard.js +2 -0
  80. package/dist/cjs/features/SegmentReviewComponents/SaveAsLearningCard.js.map +1 -0
  81. package/dist/cjs/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js +1 -1
  82. package/dist/cjs/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js.map +1 -1
  83. package/dist/cjs/hooks/useOnDemandCitationFetch.js +1 -1
  84. package/dist/cjs/hooks/useOnDemandCitationFetch.js.map +1 -1
  85. package/dist/cjs/service/onDemandApi.js +1 -1
  86. package/dist/cjs/service/onDemandApi.js.map +1 -1
  87. package/dist/features/CognitiveCompare/CitationAnchor.js +1 -1
  88. package/dist/features/CognitiveCompare/CitationAnchor.js.map +1 -1
  89. package/dist/features/CognitiveCompare/CitationRenderer.js +1 -1
  90. package/dist/features/CognitiveCompare/CitationRenderer.js.map +1 -1
  91. package/dist/features/CognitiveCompare/CitationRendererInner.js +2 -0
  92. package/dist/features/CognitiveCompare/CitationRendererInner.js.map +1 -0
  93. package/dist/features/CognitiveCompare/CognitiveCompare.js +1 -1
  94. package/dist/features/CognitiveCompare/CognitiveCompare.js.map +1 -1
  95. package/dist/features/CognitiveCompare/CognitiveCompareConstants.js +1 -1
  96. package/dist/features/CognitiveCompare/CognitiveCompareConstants.js.map +1 -1
  97. package/dist/features/CognitiveCompare/CognitiveComparehelpers.js +1 -1
  98. package/dist/features/CognitiveCompare/CognitiveComparehelpers.js.map +1 -1
  99. package/dist/features/CognitiveCompare/CognitivePopup.js +1 -1
  100. package/dist/features/CognitiveCompare/CognitivePopup.js.map +1 -1
  101. package/dist/features/CognitiveCompare/CompareContext.js +1 -1
  102. package/dist/features/CognitiveCompare/CompareContext.js.map +1 -1
  103. package/dist/features/CognitiveCompare/GptWebCitationPanel.js +2 -0
  104. package/dist/features/CognitiveCompare/GptWebCitationPanel.js.map +1 -0
  105. package/dist/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js +1 -1
  106. package/dist/features/CognitiveCompare/Guidelines/components/GuidelinePanel.js.map +1 -1
  107. package/dist/features/CognitiveCompare/Guidelines/components/WebGptPanel.js +1 -1
  108. package/dist/features/CognitiveCompare/Guidelines/components/WebGptPanel.js.map +1 -1
  109. package/dist/features/CognitiveCompare/Guidelines/utils/guidelineTargets.js +2 -0
  110. package/dist/features/CognitiveCompare/Guidelines/utils/guidelineTargets.js.map +1 -0
  111. package/dist/features/CognitiveCompare/Guidelines/utils/hasGptCitationObjects.js +2 -0
  112. package/dist/features/CognitiveCompare/Guidelines/utils/hasGptCitationObjects.js.map +1 -0
  113. package/dist/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js +1 -1
  114. package/dist/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.js.map +1 -1
  115. package/dist/features/CognitiveCompare/Guidelines/utils/resolveGuidelineSelection.js +2 -0
  116. package/dist/features/CognitiveCompare/Guidelines/utils/resolveGuidelineSelection.js.map +1 -0
  117. package/dist/features/CognitiveCompare/components/GuidelineSkeletonLoader.js +2 -0
  118. package/dist/features/CognitiveCompare/components/GuidelineSkeletonLoader.js.map +1 -0
  119. package/dist/features/CognitiveCompare/components/LHSSectionRow.js +1 -1
  120. package/dist/features/CognitiveCompare/components/LHSSectionRow.js.map +1 -1
  121. package/dist/features/CognitiveCompare/components/RHSSectionRow.js +1 -1
  122. package/dist/features/CognitiveCompare/components/RHSSectionRow.js.map +1 -1
  123. package/dist/features/CognitiveCompare/components/SectionAccordion.js +1 -1
  124. package/dist/features/CognitiveCompare/components/SectionAccordion.js.map +1 -1
  125. package/dist/features/CognitiveCompare/components/SubSectionAccordion.js +1 -1
  126. package/dist/features/CognitiveCompare/components/SubSectionAccordion.js.map +1 -1
  127. package/dist/features/CognitiveCompare/components/SvgConnectors.js +1 -1
  128. package/dist/features/CognitiveCompare/components/SvgConnectors.js.map +1 -1
  129. package/dist/features/CognitiveCompare/hooks/memoizedMarkdown.js +1 -1
  130. package/dist/features/CognitiveCompare/hooks/memoizedMarkdown.js.map +1 -1
  131. package/dist/features/CognitiveCompare/hooks/useCompareData.js +1 -1
  132. package/dist/features/CognitiveCompare/hooks/useCompareData.js.map +1 -1
  133. package/dist/features/CognitiveCompare/hooks/useLinesCalculator.js +1 -1
  134. package/dist/features/CognitiveCompare/hooks/useLinesCalculator.js.map +1 -1
  135. package/dist/features/CognitiveCompare/hooks/useOnDemandCitationCache.js +2 -0
  136. package/dist/features/CognitiveCompare/hooks/useOnDemandCitationCache.js.map +1 -0
  137. package/dist/features/CognitiveCompare/hooks/useSideBySide.js +1 -1
  138. package/dist/features/CognitiveCompare/hooks/useSideBySide.js.map +1 -1
  139. package/dist/features/CognitiveCompare/onDemandCitations/cacheKey.js +2 -0
  140. package/dist/features/CognitiveCompare/onDemandCitations/cacheKey.js.map +1 -0
  141. package/dist/features/CognitiveCompare/onDemandCitations/contextBuilder.js +2 -0
  142. package/dist/features/CognitiveCompare/onDemandCitations/contextBuilder.js.map +1 -0
  143. package/dist/features/CognitiveCompare/onDemandCitations/href.js +2 -0
  144. package/dist/features/CognitiveCompare/onDemandCitations/href.js.map +1 -0
  145. package/dist/features/CognitiveCompare/onDemandCitations/payload.js +2 -0
  146. package/dist/features/CognitiveCompare/onDemandCitations/payload.js.map +1 -0
  147. package/dist/features/CognitiveCompare/onDemandCitations/response.js +2 -0
  148. package/dist/features/CognitiveCompare/onDemandCitations/response.js.map +1 -0
  149. package/dist/features/CognitiveCompare/utils/normalizeCompactedGfmTables.js +2 -0
  150. package/dist/features/CognitiveCompare/utils/normalizeCompactedGfmTables.js.map +1 -0
  151. package/dist/features/CognitiveCompare/utils/normalizeInlineMarkdown.js +2 -0
  152. package/dist/features/CognitiveCompare/utils/normalizeInlineMarkdown.js.map +1 -0
  153. package/dist/features/CognitiveCompare/utils/normalizeRedlineMarkdown.js +2 -0
  154. package/dist/features/CognitiveCompare/utils/normalizeRedlineMarkdown.js.map +1 -0
  155. package/dist/features/PdfViewer/PdfContainer.js +1 -1
  156. package/dist/features/PdfViewer/PdfContainer.js.map +1 -1
  157. package/dist/features/PdfViewer/PdfViewer.js +1 -1
  158. package/dist/features/PdfViewer/PdfViewer.js.map +1 -1
  159. package/dist/features/SegmentReviewComponents/ApprovalDescriptionBanner.js +2 -0
  160. package/dist/features/SegmentReviewComponents/ApprovalDescriptionBanner.js.map +1 -0
  161. package/dist/features/SegmentReviewComponents/BoundaryCard.js +1 -1
  162. package/dist/features/SegmentReviewComponents/BoundaryCard.js.map +1 -1
  163. package/dist/features/SegmentReviewComponents/RevertCard.js +1 -1
  164. package/dist/features/SegmentReviewComponents/RevertCard.js.map +1 -1
  165. package/dist/features/SegmentReviewComponents/SaveAsLearningCard.js +2 -0
  166. package/dist/features/SegmentReviewComponents/SaveAsLearningCard.js.map +1 -0
  167. package/dist/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js +1 -1
  168. package/dist/features/SegmentReviewComponents/SegmentReviewPdfWrapper.js.map +1 -1
  169. package/dist/hooks/useOnDemandCitationFetch.js +1 -1
  170. package/dist/hooks/useOnDemandCitationFetch.js.map +1 -1
  171. package/dist/service/onDemandApi.js +1 -1
  172. package/dist/service/onDemandApi.js.map +1 -1
  173. package/dist/types/features/CognitiveCompare/CitationAnchor.d.ts +2 -0
  174. package/dist/types/features/CognitiveCompare/CitationAnchor.d.ts.map +1 -1
  175. package/dist/types/features/CognitiveCompare/CitationRenderer.d.ts +8 -1
  176. package/dist/types/features/CognitiveCompare/CitationRenderer.d.ts.map +1 -1
  177. package/dist/types/features/CognitiveCompare/CitationRendererInner.d.ts +13 -0
  178. package/dist/types/features/CognitiveCompare/CitationRendererInner.d.ts.map +1 -0
  179. package/dist/types/features/CognitiveCompare/CognitiveCompare.d.ts +1 -1
  180. package/dist/types/features/CognitiveCompare/CognitiveCompare.d.ts.map +1 -1
  181. package/dist/types/features/CognitiveCompare/CognitiveCompareConstants.d.ts +1 -1
  182. package/dist/types/features/CognitiveCompare/CognitiveCompareConstants.d.ts.map +1 -1
  183. package/dist/types/features/CognitiveCompare/CognitiveCompareTypes.d.ts +14 -1
  184. package/dist/types/features/CognitiveCompare/CognitiveCompareTypes.d.ts.map +1 -1
  185. package/dist/types/features/CognitiveCompare/CognitiveComparehelpers.d.ts +12 -0
  186. package/dist/types/features/CognitiveCompare/CognitiveComparehelpers.d.ts.map +1 -1
  187. package/dist/types/features/CognitiveCompare/CognitivePopup.d.ts.map +1 -1
  188. package/dist/types/features/CognitiveCompare/CompareContext.d.ts +10 -1
  189. package/dist/types/features/CognitiveCompare/CompareContext.d.ts.map +1 -1
  190. package/dist/types/features/CognitiveCompare/GptWebCitationPanel.d.ts +7 -0
  191. package/dist/types/features/CognitiveCompare/GptWebCitationPanel.d.ts.map +1 -0
  192. package/dist/types/features/CognitiveCompare/Guidelines/components/GuidelinePanel.d.ts.map +1 -1
  193. package/dist/types/features/CognitiveCompare/Guidelines/components/WebGptPanel.d.ts.map +1 -1
  194. package/dist/types/features/CognitiveCompare/Guidelines/utils/guidelineTargets.d.ts +3 -0
  195. package/dist/types/features/CognitiveCompare/Guidelines/utils/guidelineTargets.d.ts.map +1 -0
  196. package/dist/types/features/CognitiveCompare/Guidelines/utils/hasGptCitationObjects.d.ts +3 -0
  197. package/dist/types/features/CognitiveCompare/Guidelines/utils/hasGptCitationObjects.d.ts.map +1 -0
  198. package/dist/types/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.d.ts +14 -1
  199. package/dist/types/features/CognitiveCompare/Guidelines/utils/processGuidelinesMarkdown.d.ts.map +1 -1
  200. package/dist/types/features/CognitiveCompare/Guidelines/utils/resolveGuidelineSelection.d.ts +19 -0
  201. package/dist/types/features/CognitiveCompare/Guidelines/utils/resolveGuidelineSelection.d.ts.map +1 -0
  202. package/dist/types/features/CognitiveCompare/components/GuidelineSkeletonLoader.d.ts +8 -0
  203. package/dist/types/features/CognitiveCompare/components/GuidelineSkeletonLoader.d.ts.map +1 -0
  204. package/dist/types/features/CognitiveCompare/components/LHSSectionRow.d.ts.map +1 -1
  205. package/dist/types/features/CognitiveCompare/components/RHSSectionRow.d.ts.map +1 -1
  206. package/dist/types/features/CognitiveCompare/components/SectionAccordion.d.ts.map +1 -1
  207. package/dist/types/features/CognitiveCompare/components/SubSectionAccordion.d.ts.map +1 -1
  208. package/dist/types/features/CognitiveCompare/components/SvgConnectors.d.ts +3 -2
  209. package/dist/types/features/CognitiveCompare/components/SvgConnectors.d.ts.map +1 -1
  210. package/dist/types/features/CognitiveCompare/hooks/memoizedMarkdown.d.ts +2 -1
  211. package/dist/types/features/CognitiveCompare/hooks/memoizedMarkdown.d.ts.map +1 -1
  212. package/dist/types/features/CognitiveCompare/hooks/useCompareData.d.ts +1 -1
  213. package/dist/types/features/CognitiveCompare/hooks/useCompareData.d.ts.map +1 -1
  214. package/dist/types/features/CognitiveCompare/hooks/useLinesCalculator.d.ts.map +1 -1
  215. package/dist/types/features/CognitiveCompare/hooks/useOnDemandCitationCache.d.ts +10 -0
  216. package/dist/types/features/CognitiveCompare/hooks/useOnDemandCitationCache.d.ts.map +1 -0
  217. package/dist/types/features/CognitiveCompare/hooks/useSideBySide.d.ts.map +1 -1
  218. package/dist/types/features/CognitiveCompare/onDemandCitations/cacheKey.d.ts +3 -0
  219. package/dist/types/features/CognitiveCompare/onDemandCitations/cacheKey.d.ts.map +1 -0
  220. package/dist/types/features/CognitiveCompare/onDemandCitations/contextBuilder.d.ts +16 -0
  221. package/dist/types/features/CognitiveCompare/onDemandCitations/contextBuilder.d.ts.map +1 -0
  222. package/dist/types/features/CognitiveCompare/onDemandCitations/href.d.ts +6 -0
  223. package/dist/types/features/CognitiveCompare/onDemandCitations/href.d.ts.map +1 -0
  224. package/dist/types/features/CognitiveCompare/onDemandCitations/index.d.ts +7 -0
  225. package/dist/types/features/CognitiveCompare/onDemandCitations/index.d.ts.map +1 -0
  226. package/dist/types/features/CognitiveCompare/onDemandCitations/payload.d.ts +4 -0
  227. package/dist/types/features/CognitiveCompare/onDemandCitations/payload.d.ts.map +1 -0
  228. package/dist/types/features/CognitiveCompare/onDemandCitations/response.d.ts +3 -0
  229. package/dist/types/features/CognitiveCompare/onDemandCitations/response.d.ts.map +1 -0
  230. package/dist/types/features/CognitiveCompare/onDemandCitations/types.d.ts +134 -0
  231. package/dist/types/features/CognitiveCompare/onDemandCitations/types.d.ts.map +1 -0
  232. package/dist/types/features/CognitiveCompare/utils/normalizeCompactedGfmTables.d.ts +7 -0
  233. package/dist/types/features/CognitiveCompare/utils/normalizeCompactedGfmTables.d.ts.map +1 -0
  234. package/dist/types/features/CognitiveCompare/utils/normalizeInlineMarkdown.d.ts +6 -0
  235. package/dist/types/features/CognitiveCompare/utils/normalizeInlineMarkdown.d.ts.map +1 -0
  236. package/dist/types/features/CognitiveCompare/utils/normalizeRedlineMarkdown.d.ts +6 -0
  237. package/dist/types/features/CognitiveCompare/utils/normalizeRedlineMarkdown.d.ts.map +1 -0
  238. package/dist/types/features/PdfViewer/PdfContainer.d.ts +3 -2
  239. package/dist/types/features/PdfViewer/PdfContainer.d.ts.map +1 -1
  240. package/dist/types/features/PdfViewer/PdfViewer.d.ts +3 -2
  241. package/dist/types/features/PdfViewer/PdfViewer.d.ts.map +1 -1
  242. package/dist/types/features/SegmentReviewComponents/ApprovalDescriptionBanner.d.ts +11 -0
  243. package/dist/types/features/SegmentReviewComponents/ApprovalDescriptionBanner.d.ts.map +1 -0
  244. package/dist/types/features/SegmentReviewComponents/BoundaryCard.d.ts.map +1 -1
  245. package/dist/types/features/SegmentReviewComponents/RevertCard.d.ts +9 -1
  246. package/dist/types/features/SegmentReviewComponents/RevertCard.d.ts.map +1 -1
  247. package/dist/types/features/SegmentReviewComponents/SaveAsLearningCard.d.ts +15 -0
  248. package/dist/types/features/SegmentReviewComponents/SaveAsLearningCard.d.ts.map +1 -0
  249. package/dist/types/features/SegmentReviewComponents/SegmentReviewPdfWrapper.d.ts +14 -1
  250. package/dist/types/features/SegmentReviewComponents/SegmentReviewPdfWrapper.d.ts.map +1 -1
  251. package/dist/types/hooks/useOnDemandCitationFetch.d.ts.map +1 -1
  252. package/dist/types/service/onDemandApi.d.ts.map +1 -1
  253. package/package.json +1 -1
  254. package/dist/cjs/features/Bookemon/BookemonStyles.js +0 -2
  255. package/dist/cjs/features/Bookemon/BookemonStyles.js.map +0 -1
  256. package/dist/cjs/lib/ui/icons.js +0 -2
  257. package/dist/cjs/lib/ui/icons.js.map +0 -1
  258. package/dist/cjs/lib/ui/materialCompat.js +0 -2
  259. package/dist/cjs/lib/ui/materialCompat.js.map +0 -1
  260. package/dist/features/Bookemon/BookemonStyles.js +0 -2
  261. package/dist/features/Bookemon/BookemonStyles.js.map +0 -1
  262. package/dist/lib/ui/icons.js +0 -2
  263. package/dist/lib/ui/icons.js.map +0 -1
  264. package/dist/lib/ui/materialCompat.js +0 -2
  265. package/dist/lib/ui/materialCompat.js.map +0 -1
  266. package/dist/types/features/Bookemon/BookemonStyles.d.ts +0 -6
  267. package/dist/types/features/Bookemon/BookemonStyles.d.ts.map +0 -1
  268. package/dist/types/lib/ui/icons.d.ts +0 -46
  269. package/dist/types/lib/ui/icons.d.ts.map +0 -1
  270. package/dist/types/lib/ui/materialCompat.d.ts +0 -117
  271. package/dist/types/lib/ui/materialCompat.d.ts.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("react"),e=require("@tanstack/react-query"),n=require("../service/onDemandApi.js");const i=(t,e,n)=>Array.isArray(t)?Array.isArray(e)&&0!==e.length?Number.isNaN(n)?(console.warn("[findCitation] citationNumber is NaN"),null):t.find(t=>{const i=(t=>{if(null==t)return console.warn("[getCitationType] received null or undefined citation"),"";const e=t?.customMetaData?.type??t?.customMetadata?.type??t?.type??"";return e||console.warn("[getCitationType] citation has no resolvable type field",t),e})(t);return(t=>null==t?(console.warn("[getCitationNumber] received null or undefined citation"),""):(null==t.citation_number&&console.warn("[getCitationNumber] citation is missing citation_number field",t),t?.citation_number??""))(t)?.toString()===n.toString()&&e.some(t=>i?.includes(t))})??null:(console.warn("[findCitation] citationTypes is empty or falsy",e),null):(console.warn("[findCitation] citations is not an array",t),null);exports.useOnDemandCitationFetch=({msg:a,citationType:o,citationNumber:c,enabled:s=!1,accessToken:r,baseUrl:u,orgName:d,citationAssistantProcessingName:l,citationAgentName:_})=>{const m=a?.requestId||a?.id||"",y=t.useMemo(()=>(t=>{switch(t){case"artifact_chunks":return["artifact_chunks","scanned_doc_citation","scanned_doc_citations"];case"rai_artifact_citation":return["rai_artifact_citation","rai_artifact_citations"];case"json_chunks":return["json_chunks"];case"scanned_doc_citation":return["scanned_doc_citation","scanned_doc_citations","artifact_chunks"];case"scanned_doc_citations":return["scanned_doc_citations","scanned_doc_citation","artifact_chunks"];default:return[t]}})(o),[o]),f=(()=>{switch(o){case"artifact_chunks":case"scanned_doc_citations":return"scanned_doc_citation";case"rai_artifact_citation":return"rai_artifact_citation";default:return o}})(),g=a?.isEcgPayloadActive?t.useMemo(()=>["onDemandCitationFetch",m,f,a?.customCitationId,a?.ecg_agent_name],[m,f,a?.customCitationId,a?.ecg_agent_name]):t.useMemo(()=>["onDemandCitationFetch",m,f,"gpt_citation"===o?a?.id:c],[m,f,c]),h=t.useMemo(()=>i(a?.citations,y,c),[a?.citations,y,c]),p=Boolean(s&&m&&f&&u&&d&&!Number.isNaN(c)&&!h),C=r,b=!0===a?.isStreamEnd,A=e.useQuery({queryKey:g,queryFn:async()=>{const t=await n.fetchOnDemandCitation(m,f,c,a?.content??"",C,u,l??"",d,_??"",a?.isEcgPayloadActive??!1,"boolean"==typeof a?.isReqPayloadActive&&a.isReqPayloadActive,a?.ecg_agent_name??"",a?.customCitationId??"",a?.plan_id??"",a?.ui_chat_history??void 0,a?.mmvf_list??void 0,Array.isArray(a?.files)?a.files:[],"string"==typeof a?.metadata&&a.metadata.trim()?a.metadata:"",a?.checkPossibleCitationPayload,a?.ui_request_body);if(t.error||!t.responseData)throw new Error(t.error?.errorMessage||"Failed to fetch on-demand citation");return t.responseData},enabled:p&&b&&Boolean(a?.content),staleTime:1/0,gcTime:1/0,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:!1}),N=t.useMemo(()=>{const t=A.data?.result?.citations??[];return Array.isArray(t)&&0!==t.length?a?.customCitationId?t.find(t=>{const e=t?.title??t?.display_name??"";return"string"==typeof e&&e.includes(a.customCitationId)})??t[0]??null:i(t,y,c)??t[0]??null:null},[a?.customCitationId,c,y,A.data]);return{citation:h??N,isFetching:A.isFetching,isLoading:A.isLoading,isComplete:A.isSuccess,status:A.status,refetch:A.refetch}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("react"),e=require("@tanstack/react-query"),n=require("../service/onDemandApi.js");const i=(t,e,n)=>Array.isArray(t)?Array.isArray(e)&&0!==e.length?Number.isNaN(n)?(console.warn("[findCitation] citationNumber is NaN"),null):t.find(t=>{const i=(t=>{if(null==t)return console.warn("[getCitationType] received null or undefined citation"),"";const e=t?.customMetaData?.type??t?.customMetadata?.type??t?.type??"";return e||console.warn("[getCitationType] citation has no resolvable type field",t),e})(t);return(t=>null==t?(console.warn("[getCitationNumber] received null or undefined citation"),""):(null==t.citation_number&&console.warn("[getCitationNumber] citation is missing citation_number field",t),t?.citation_number??""))(t)?.toString()===n.toString()&&e.some(t=>i?.includes(t))})??null:(console.warn("[findCitation] citationTypes is empty or falsy",e),null):(console.warn("[findCitation] citations is not an array",t),null);exports.useOnDemandCitationFetch=({msg:a,citationType:o,citationNumber:c,enabled:s=!1,accessToken:r,baseUrl:u,orgName:d,citationAssistantProcessingName:l,citationAgentName:_})=>{const m=a?.requestId||a?.id||"",y=t.useMemo(()=>(t=>{switch(t){case"artifact_chunks":return["artifact_chunks","scanned_doc_citation","scanned_doc_citations"];case"rai_artifact_citation":return["rai_artifact_citation","rai_artifact_citations"];case"json_chunks":return["json_chunks"];case"scanned_doc_citation":return["scanned_doc_citation","scanned_doc_citations","artifact_chunks"];case"scanned_doc_citations":return["scanned_doc_citations","scanned_doc_citation","artifact_chunks"];default:return[t]}})(o),[o]),f=(()=>{switch(o){case"artifact_chunks":case"scanned_doc_citations":return"scanned_doc_citation";case"rai_artifact_citation":return"rai_artifact_citation";default:return o}})(),g=a?.isEcgPayloadActive?t.useMemo(()=>["onDemandCitationFetch",m,f,a?.customCitationId,a?.ecg_agent_name],[m,f,a?.customCitationId,a?.ecg_agent_name]):t.useMemo(()=>["onDemandCitationFetch",m,f,"gpt_citation"===o?a?.id:c],[m,f,c]),h=t.useMemo(()=>i(a?.citations,y,c),[a?.citations,y,c]),p=Boolean(s&&m&&f&&u&&d&&!Number.isNaN(c)&&!h),C=r,b=!0===a?.isStreamEnd,A=e.useQuery({queryKey:g,queryFn:async()=>{C&&C.trim()||console.warn("[useOnDemandCitationFetch] no accessToken passed in props");const t=await n.fetchOnDemandCitation(m,f,c,a?.content??"",C,u,l??"",d,_??"",a?.isEcgPayloadActive??!1,"boolean"==typeof a?.isReqPayloadActive&&a.isReqPayloadActive,a?.ecg_agent_name??"",a?.customCitationId??"",a?.plan_id??"",a?.ui_chat_history??void 0,a?.mmvf_list??void 0,Array.isArray(a?.files)?a.files:[],"string"==typeof a?.metadata&&a.metadata.trim()?a.metadata:"",a?.checkPossibleCitationPayload,a?.ui_request_body);if(t.error||!t.responseData)throw new Error(t.error?.errorMessage||"Failed to fetch on-demand citation");return t.responseData},enabled:p&&b&&Boolean(a?.content),staleTime:1/0,gcTime:1/0,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:!1}),N=t.useMemo(()=>{const t=A.data?.result?.citations??[];return Array.isArray(t)&&0!==t.length?a?.customCitationId?t.find(t=>{const e=t?.title??t?.display_name??"";return"string"==typeof e&&e.includes(a.customCitationId)})??t[0]??null:i(t,y,c)??t[0]??null:null},[a?.customCitationId,c,y,A.data]);return{citation:h??N,isFetching:A.isFetching,isLoading:A.isLoading,isComplete:A.isSuccess,status:A.status,refetch:A.refetch}};
2
2
  //# sourceMappingURL=useOnDemandCitationFetch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useOnDemandCitationFetch.js","sources":["../../../src/hooks/useOnDemandCitationFetch.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { useQuery } from '@tanstack/react-query';\nimport { fetchOnDemandCitation } from '../service/onDemandApi';\nimport type {\n OnDemandCitationPayload,\n UseOnDemandCitationFetchParams,\n} from '../types/useOnDemandCitationFetch.types';\n\nexport type {\n OnDemandCitationPayload,\n ShareChatToMode,\n IntermediateStep,\n ShareChat,\n ArtifactData,\n PowerActionMetadata,\n UseOnDemandCitationFetchParams,\n} from '../types/useOnDemandCitationFetch.types';\n\nconst getCitationType = (citation: any) => {\n if (citation == null) {\n console.warn('[getCitationType] received null or undefined citation');\n return '';\n }\n const type =\n citation?.customMetaData?.type ??\n citation?.customMetadata?.type ??\n citation?.type ??\n '';\n if (!type) {\n console.warn('[getCitationType] citation has no resolvable type field', citation);\n }\n return type;\n};\n\nconst getCitationNumber = (citation: any) => {\n if (citation == null) {\n console.warn('[getCitationNumber] received null or undefined citation');\n return '';\n }\n if (citation.citation_number == null) {\n console.warn('[getCitationNumber] citation is missing citation_number field', citation);\n }\n return citation?.citation_number ?? '';\n};\n\nconst getCitationTypeCandidates = (citationType: string) => {\n switch (citationType) {\n case 'artifact_chunks':\n return ['artifact_chunks', 'scanned_doc_citation', 'scanned_doc_citations'];\n case 'rai_artifact_citation':\n return ['rai_artifact_citation', 'rai_artifact_citations'];\n case 'json_chunks':\n return ['json_chunks'];\n case 'scanned_doc_citation':\n return ['scanned_doc_citation', 'scanned_doc_citations', 'artifact_chunks'];\n case 'scanned_doc_citations':\n return ['scanned_doc_citations', 'scanned_doc_citation', 'artifact_chunks'];\n default:\n return [citationType];\n }\n};\n\nconst findCitation = (\n citations: any[] | undefined,\n citationTypes: string[],\n citationNumber: number\n) => {\n if (!Array.isArray(citations)) {\n console.warn('[findCitation] citations is not an array', citations);\n return null;\n }\n if (!Array.isArray(citationTypes) || citationTypes.length === 0) {\n console.warn('[findCitation] citationTypes is empty or falsy', citationTypes);\n return null;\n }\n if (Number.isNaN(citationNumber)) {\n console.warn('[findCitation] citationNumber is NaN');\n return null;\n }\n\n return (\n citations.find((citation: any) => {\n const type = getCitationType(citation);\n return (\n getCitationNumber(citation)?.toString() === citationNumber.toString() &&\n citationTypes.some((citationType) => type?.includes(citationType))\n );\n }) ?? null\n );\n};\n\nexport const useOnDemandCitationFetch = ({\n msg,\n citationType,\n citationNumber,\n enabled = false,\n accessToken,\n baseUrl,\n orgName,\n citationAssistantProcessingName,\n citationAgentName,\n}: UseOnDemandCitationFetchParams) => {\n const requestId = msg?.requestId || msg?.id || '';\n const citationTypesForMatching = useMemo(() => getCitationTypeCandidates(citationType), [citationType]);\n const citationTypeForRequest = (() => {\n switch (citationType) {\n case 'artifact_chunks': return 'scanned_doc_citation';\n case 'rai_artifact_citation': return 'rai_artifact_citation';\n case 'scanned_doc_citations': return 'scanned_doc_citation';\n default: return citationType;\n }\n })();\n\n\t// Each (requestId, citationType, citationNumber) triple gets its own cache entry\n\tconst queryKey =msg?.isEcgPayloadActive ? useMemo(\n\t () => ['onDemandCitationFetch', requestId, citationTypeForRequest, msg?.customCitationId, msg?.ecg_agent_name],\n\t [requestId, citationTypeForRequest, msg?.customCitationId, msg?.ecg_agent_name]) \n\t : useMemo(\n\t () => ['onDemandCitationFetch', requestId, citationTypeForRequest, citationType === 'gpt_citation' ? msg?.id : citationNumber],\n\t [requestId, citationTypeForRequest, citationNumber]\n\t);\n\n // If the citation already exists on the message, no need to fetch\n const existingCitation = useMemo(\n () => findCitation(msg?.citations, citationTypesForMatching, citationNumber),\n [msg?.citations, citationTypesForMatching, citationNumber]\n );\n\n const shouldFetch = Boolean(enabled && requestId && citationTypeForRequest && baseUrl && orgName && !Number.isNaN(citationNumber) && !existingCitation);\n const token = accessToken;\n const isMessageComplete = msg?.isStreamEnd === true;\n\n const query = useQuery<OnDemandCitationPayload>({\n queryKey,\n queryFn: async () => {\n // if(!token) {\n // console.error('[useOnDemandCitationFetch] No auth token available, cannot fetch citation');\n // throw new Error('No auth token available, cannot fetch citation');\n // }\n const response = await fetchOnDemandCitation(\n requestId,\n citationTypeForRequest,\n citationNumber,\n msg?.content ?? '',\n token,\n baseUrl,\n citationAssistantProcessingName ?? '',\n orgName,\n citationAgentName ?? '',\n msg?.isEcgPayloadActive ?? false,\n (typeof msg?.isReqPayloadActive === 'boolean' ? msg.isReqPayloadActive : false),\n msg?.ecg_agent_name ?? '',\n msg?.customCitationId ?? '',\n msg?.plan_id ?? '',\n msg?.ui_chat_history ?? undefined,\n msg?.mmvf_list ?? undefined,\n Array.isArray(msg?.files) ? msg.files : [],\n (typeof msg?.metadata === 'string' && msg.metadata.trim()) ? msg.metadata : '',\n msg?.checkPossibleCitationPayload,\n msg?.ui_request_body\n );\n\n if (response.error || !response.responseData) {\n throw new Error(response.error?.errorMessage || 'Failed to fetch on-demand citation');\n }\n\n return response.responseData;\n },\n enabled: shouldFetch && isMessageComplete && Boolean(msg?.content),\n staleTime: Infinity,\n gcTime: Infinity,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n retry: false,\n });\n const fetchedCitation = useMemo(() => {\n const citations = query.data?.result?.citations ?? [];\n if (!Array.isArray(citations) || citations.length === 0) return null;\n\n if (msg?.customCitationId) {\n return (\n citations.find((c: any) => {\n const title = c?.title ?? c?.display_name ?? '';\n return typeof title === 'string' && title.includes(msg.customCitationId);\n }) ?? citations[0] ?? null\n );\n }\n\n return (\n findCitation(citations, citationTypesForMatching, citationNumber) ??\n citations[0] ??\n null\n );\n}, [msg?.customCitationId, citationNumber, citationTypesForMatching, query.data]);\n const resolvedCitation = existingCitation ?? fetchedCitation;\n\n return {\n citation: resolvedCitation,\n isFetching: query.isFetching,\n isLoading: query.isLoading,\n isComplete: query.isSuccess,\n status: query.status,\n refetch: query.refetch,\n };\n};\n"],"names":["findCitation","citations","citationTypes","citationNumber","Array","isArray","length","Number","isNaN","console","warn","find","citation","type","customMetaData","customMetadata","getCitationType","citation_number","getCitationNumber","toString","some","citationType","includes","msg","enabled","accessToken","baseUrl","orgName","citationAssistantProcessingName","citationAgentName","requestId","id","citationTypesForMatching","useMemo","getCitationTypeCandidates","citationTypeForRequest","queryKey","isEcgPayloadActive","customCitationId","ecg_agent_name","existingCitation","shouldFetch","Boolean","token","isMessageComplete","isStreamEnd","query","useQuery","queryFn","async","response","fetchOnDemandCitation","content","isReqPayloadActive","plan_id","ui_chat_history","mmvf_list","files","metadata","trim","checkPossibleCitationPayload","ui_request_body","error","responseData","Error","errorMessage","staleTime","Infinity","gcTime","refetchOnMount","refetchOnWindowFocus","retry","fetchedCitation","data","result","c","title","display_name","isFetching","isLoading","isComplete","isSuccess","status","refetch"],"mappings":"qKAkBA,MA4CMA,EAAe,CACnBC,EACAC,EACAC,IAEKC,MAAMC,QAAQJ,GAIdG,MAAMC,QAAQH,IAA2C,IAAzBA,EAAcI,OAI/CC,OAAOC,MAAML,IACfM,QAAQC,KAAK,wCACN,MAIPT,EAAUU,KAAMC,IACR,MAAAC,EAhEY,CAACD,IACvB,GAAgB,MAAZA,EAEK,OADPH,QAAQC,KAAK,yDACN,GAEH,MAAAG,EACJD,GAAUE,gBAAgBD,MAC1BD,GAAUG,gBAAg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gB,GAC7C,MAAwB,iBAAVD,GAAsBA,EAAMtD,SAASC,EAAIe,qBACnDrC,EAAU,IAAM,KAKxBD,EAAaC,EAAW+B,EAA0B7B,IAClDF,EAAU,IACV,KAd8D,MAgB/D,CAACsB,GAAKe,iBAAkBnC,EAAgB6B,EAA0Bc,EAAM2B,OAGlE,MAAA,CACL7D,SAHuB4B,GAAoBgC,EAI3CM,WAAYhC,EAAMgC,WAClBC,UAAWjC,EAAMiC,UACjBC,WAAYlC,EAAMmC,UAClBC,OAAQpC,EAAMoC,OACdC,QAASrC,EAAMqC"}
1
+ {"version":3,"file":"useOnDemandCitationFetch.js","sources":["../../../src/hooks/useOnDemandCitationFetch.ts"],"sourcesContent":["import { useMemo } from 'react';\nimport { useQuery } from '@tanstack/react-query';\nimport { fetchOnDemandCitation } from '../service/onDemandApi';\nimport type {\n OnDemandCitationPayload,\n UseOnDemandCitationFetchParams,\n} from '../types/useOnDemandCitationFetch.types';\n\nexport type {\n OnDemandCitationPayload,\n ShareChatToMode,\n IntermediateStep,\n ShareChat,\n ArtifactData,\n PowerActionMetadata,\n UseOnDemandCitationFetchParams,\n} from '../types/useOnDemandCitationFetch.types';\n\nconst getCitationType = (citation: any) => {\n if (citation == null) {\n console.warn('[getCitationType] received null or undefined citation');\n return '';\n }\n const type =\n citation?.customMetaData?.type ??\n citation?.customMetadata?.type ??\n citation?.type ??\n '';\n if (!type) {\n console.warn('[getCitationType] citation has no resolvable type field', citation);\n }\n return type;\n};\n\nconst getCitationNumber = (citation: any) => {\n if (citation == null) {\n console.warn('[getCitationNumber] received null or undefined citation');\n return '';\n }\n if (citation.citation_number == null) {\n console.warn('[getCitationNumber] citation is missing citation_number field', citation);\n }\n return citation?.citation_number ?? '';\n};\n\nconst getCitationTypeCandidates = (citationType: string) => {\n switch (citationType) {\n case 'artifact_chunks':\n return ['artifact_chunks', 'scanned_doc_citation', 'scanned_doc_citations'];\n case 'rai_artifact_citation':\n return ['rai_artifact_citation', 'rai_artifact_citations'];\n case 'json_chunks':\n return ['json_chunks'];\n case 'scanned_doc_citation':\n return ['scanned_doc_citation', 'scanned_doc_citations', 'artifact_chunks'];\n case 'scanned_doc_citations':\n return ['scanned_doc_citations', 'scanned_doc_citation', 'artifact_chunks'];\n default:\n return [citationType];\n }\n};\n\nconst findCitation = (\n citations: any[] | undefined,\n citationTypes: string[],\n citationNumber: number\n) => {\n if (!Array.isArray(citations)) {\n console.warn('[findCitation] citations is not an array', citations);\n return null;\n }\n if (!Array.isArray(citationTypes) || citationTypes.length === 0) {\n console.warn('[findCitation] citationTypes is empty or falsy', citationTypes);\n return null;\n }\n if (Number.isNaN(citationNumber)) {\n console.warn('[findCitation] citationNumber is NaN');\n return null;\n }\n\n return (\n citations.find((citation: any) => {\n const type = getCitationType(citation);\n return (\n getCitationNumber(citation)?.toString() === citationNumber.toString() &&\n citationTypes.some((citationType) => type?.includes(citationType))\n );\n }) ?? null\n );\n};\n\nexport const useOnDemandCitationFetch = ({\n msg,\n citationType,\n citationNumber,\n enabled = false,\n accessToken,\n baseUrl,\n orgName,\n citationAssistantProcessingName,\n citationAgentName,\n}: UseOnDemandCitationFetchParams) => {\n const requestId = msg?.requestId || msg?.id || '';\n const citationTypesForMatching = useMemo(() => getCitationTypeCandidates(citationType), [citationType]);\n const citationTypeForRequest = (() => {\n switch (citationType) {\n case 'artifact_chunks': return 'scanned_doc_citation';\n case 'rai_artifact_citation': return 'rai_artifact_citation';\n case 'scanned_doc_citations': return 'scanned_doc_citation';\n default: return citationType;\n }\n })();\n\n\t// Each (requestId, citationType, citationNumber) triple gets its own cache entry\n\tconst queryKey =msg?.isEcgPayloadActive ? useMemo(\n\t () => ['onDemandCitationFetch', requestId, citationTypeForRequest, msg?.customCitationId, msg?.ecg_agent_name],\n\t [requestId, citationTypeForRequest, msg?.customCitationId, msg?.ecg_agent_name]) \n\t : useMemo(\n\t () => ['onDemandCitationFetch', requestId, citationTypeForRequest, citationType === 'gpt_citation' ? msg?.id : citationNumber],\n\t [requestId, citationTypeForRequest, citationNumber]\n\t);\n\n // If the citation already exists on the message, no need to fetch\n const existingCitation = useMemo(\n () => findCitation(msg?.citations, citationTypesForMatching, citationNumber),\n [msg?.citations, citationTypesForMatching, citationNumber]\n );\n\n const shouldFetch = Boolean(enabled && requestId && citationTypeForRequest && baseUrl && orgName && !Number.isNaN(citationNumber) && !existingCitation);\n const token = accessToken;\n const isMessageComplete = msg?.isStreamEnd === true;\n\n const query = useQuery<OnDemandCitationPayload>({\n queryKey,\n queryFn: async () => {\n if (!token || !token.trim()) {\n console.warn('[useOnDemandCitationFetch] no accessToken passed in props');\n }\n const response = await fetchOnDemandCitation(\n requestId,\n citationTypeForRequest,\n citationNumber,\n msg?.content ?? '',\n token,\n baseUrl,\n citationAssistantProcessingName ?? '',\n orgName,\n citationAgentName ?? '',\n msg?.isEcgPayloadActive ?? false,\n (typeof msg?.isReqPayloadActive === 'boolean' ? msg.isReqPayloadActive : false),\n msg?.ecg_agent_name ?? '',\n msg?.customCitationId ?? '',\n msg?.plan_id ?? '',\n msg?.ui_chat_history ?? undefined,\n msg?.mmvf_list ?? undefined,\n Array.isArray(msg?.files) ? msg.files : [],\n (typeof msg?.metadata === 'string' && msg.metadata.trim()) ? msg.metadata : '',\n msg?.checkPossibleCitationPayload,\n msg?.ui_request_body\n );\n\n if (response.error || !response.responseData) {\n throw new Error(response.error?.errorMessage || 'Failed to fetch on-demand citation');\n }\n\n return response.responseData;\n },\n enabled: shouldFetch && isMessageComplete && Boolean(msg?.content),\n staleTime: Infinity,\n gcTime: Infinity,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n retry: false,\n });\n const fetchedCitation = useMemo(() => {\n const citations = query.data?.result?.citations ?? [];\n if (!Array.isArray(citations) || citations.length === 0) return null;\n\n if (msg?.customCitationId) {\n return (\n citations.find((c: any) => {\n const title = c?.title ?? c?.display_name ?? '';\n return typeof title === 'string' && title.includes(msg.customCitationId);\n }) ?? citations[0] ?? null\n );\n }\n\n return (\n findCitation(citations, citationTypesForMatching, citationNumber) ??\n citations[0] ??\n null\n );\n}, [msg?.customCitationId, citationNumber, citationTypesForMatching, query.data]);\n const resolvedCitation = existingCitation ?? fetchedCitation;\n\n return {\n citation: resolvedCitation,\n isFetching: query.isFetching,\n isLoading: query.isLoading,\n isComplete: query.isSuccess,\n status: query.status,\n refetch: query.refetch,\n };\n};\n"],"names":["findCitation","citations","citationTypes","citationNumber","Array","isArray","length","Number","isNaN","console","warn","find","citation","type","customMetaData","customMetadata","getCitationType","citation_number","getCitationNumber","toString","some","citationType","includes","msg","enabled","accessToken","baseUrl","orgName","citationAssistantProcessingName","citationAgentName","requestId","id","citationTypesForMatching","useMemo","getCitationTypeCandidates","citationTypeForRequest","queryKey","isEcgPayloadActive","customCitationId","ecg_agent_name","existingCitation","shouldFetch","Boolean","token","isMessageComplete","isStreamEnd","query","useQuery","queryFn","async","trim","response","fetchOnDemandCitation","content","isReqPayloadActive","plan_id","ui_chat_history","mmvf_list","files","metadata","checkPossibleCitationPayload","ui_request_body","error","responseData","Error","errorMessage","staleTime","Infinity","gcTime","refetchOnMount","refetchOnWindowFocus","retry","fetchedCitation","data","result","c","title","display_name","isFetching","isLoading","isComplete","isSuccess","status","refetch"],"mappings":"qKAkBA,MA4CMA,EAAe,CACnBC,EACAC,EACAC,IAEKC,MAAMC,QAAQJ,GAIdG,MAAMC,QAAQH,IAA2C,IAAzBA,EAAcI,OAI/CC,OAAOC,MAAML,IACfM,QAAQC,KAAK,wCACN,MAIPT,EAAUU,KAAMC,IACR,MAAAC,EAhEY,CAACD,IACvB,GAAgB,MAAZA,EAEK,OADPH,QAAQC,KAAK,yDACN,GAEH,MAAAG,EACJD,GAAUE,gBAAgBD,MAC1BD,GAAUG,gBAAgBF,MAC1BD,GAAUC,MACV,GAIK,OAHFA,GACKJ,QAAAC,KAAK,0DAA2DE,GAEnEC,GAmDUG,CAAgBJ,GAC7B,MAjDoB,CAACA,GACT,MAAZA,GACFH,QAAQC,KAAK,2DACN,KAEu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ClDF,EAAU,IACV,KAd8D,MAgB/D,CAACsB,GAAKe,iBAAkBnC,EAAgB6B,EAA0Bc,EAAM2B,OAGlE,MAAA,CACL7D,SAHuB4B,GAAoBgC,EAI3CM,WAAYhC,EAAMgC,WAClBC,UAAWjC,EAAMiC,UACjBC,WAAYlC,EAAMmC,UAClBC,OAAQpC,EAAMoC,OACdC,QAASrC,EAAMqC"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios"),r=require("./apicache.service.js"),t=require("../types/onDemandApi.types.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=a(e);const o=72e5,n=e=>{if(!e||"object"!=typeof e)return;const r=e;return"string"==typeof r.message?r.message:"string"==typeof r.errorMessage?r.errorMessage:"string"==typeof r.error?r.error:r.error&&"object"==typeof r.error&&"string"==typeof r.error.message?r.error.message:"string"==typeof r.details?r.details:r},i=async e=>{if(s.default.isAxiosError(e)){const r=e;if("ECONNABORTED"===r.code)return{type:t.NetworkErrorType.TIMEOUT,message:"The request took too long to complete. Please try again.",originalError:e};if(r.message.includes("net::ERR_NETWORK_CHANGED")||r.message.includes("net::ERR_INTERNET_DISCONNECTED")||r.message.includes("net::ERR_NAME_NOT_RESOLVED"))return{type:t.NetworkErrorType.INTERNET_DISCONNECTED,message:"Internet connection issue detected. Please check your network.",originalError:e};if(r.message.includes("Network Error")||"ERR_NETWORK"===r.code||r.message.includes("net::ERR_CONNECTION_REFUSED")||r.message.includes("net::ERR_EMPTY_RESPONSE"))return{type:t.NetworkErrorType.SERVER_UNREACHABLE,message:"Unable to connect to server. The service may be down or unreachable.",originalError:e};if(r.response&&r.response.status>=500)return{type:t.NetworkErrorType.SERVER_ERROR,message:`Service Unavailable. Server error (${r.response.status}).`,status:r.response.status,originalError:e};if(r.response&&r.response.status>=400&&r.response.status<500)return{type:t.NetworkErrorType.SERVER_ERROR,message:n(r.response.data)||`Request failed with status code ${r.response.status}`,status:r.response.status,originalError:e}}return{type:t.NetworkErrorType.UNKNOWN_ERROR,message:"An unexpected error occurred. Please try again later.",originalError:e}},c=(e,r=18e4)=>{const t=s.default.create({baseURL:e,timeout:r});return t.interceptors.request.use(async e=>e,async e=>{const r=await i(e);return Promise.reject(r)}),t.interceptors.response.use(e=>e,async e=>{const r=await i(e);return console.error("API Request Failed:",r),Promise.reject(r)}),t},p=(e,r,t)=>`${e}:${r}:${JSON.stringify(t||{})}`,u=c(),l=async(e,r,a)=>{try{const t=a?.baseURL?c(a.baseURL):u,{data:s,config:o}=a||{};let n;switch(e.toLowerCase()){case"get":n=await t.get(r,o);break;case"post":n=await t.post(r,s,o);break;case"put":n=await t.put(r,s,o);break;case"patch":n=await t.patch(r,s,o);break;case"delete":const a={...o,data:s};n=await t.delete(r,a);break;default:throw new Error(`Unsupported method: ${e}`)}return{responseData:n.data,error:null}}catch(e){if(e.type&&Object.values(t.NetworkErrorType).includes(e.type))return{responseData:null,error:e};return{responseData:null,error:await i(e)}}},E=async(e,a,s)=>{const{data:n,params:i,config:c,errorMessage:u,baseURL:E,cacheOption:y,shouldCache:d}=s||{},g=y?.ttl??o,_=y?.key||p(e,a,i);if(!y?.forceRefresh&&!y?.skipCache){const e=await r.apiCache.get(_);if(e)return{responseData:e.data,error:null,cacheMeta:{isFromCache:!0,timestamp:e.timestamp,ttl:e.ttl,cacheKey:_}}}const m={...c,...i&&{params:i}},R=await l(e,a,{data:n,config:m,baseURL:E});return!y?.skipCache&&null!=R.responseData&&(!d||d(R.responseData))&&await r.apiCache.set(_,R.responseData,g),{responseData:R.responseData,error:R.error?{errorMessage:R.error.type===t.NetworkErrorType.INTERNET_DISCONNECTED||R.error.type===t.NetworkErrorType.SLOW_CONNECTION||R.error.type===t.NetworkErrorType.TIMEOUT?R.error.message:R.error.type===t.NetworkErrorType.SERVER_UNREACHABLE?"Unable to connect to server. Please try again later.":u||R.error.message,errorObjData:R.error}:null,cacheMeta:{isFromCache:!1,timestamp:Date.now(),ttl:g,cacheKey:_}}};exports.NetworkErrorType=t.NetworkErrorType,exports.DEFAULT_CACHE_TTL=o,exports.createApiInstance=c,exports.fetchOnDemandCitation=async(e,r,t,a,s,o,n,i,c,p,u,l,y,d,g,_,m,R,N,h)=>{const f="artifact_chunks"===r||"scanned_doc_citation"===r?"artifact_chunks":r,T="gpt_citation"===r?"string"==typeof h?.citationId?h.citationId:"":p?y:`${f}_${t}`,w="post",k="/api/chat/chatResponse";return E(w,k,{baseURL:o,data:{name:n||"citationsprocessing",organizationName:i,prompt:"",useAgent:{agent_name:c||"ProcessCitationsAgent",metadata:u?R:void 0,arguments:{citation_type:r,is_primary_agent_request:!1,...p&&{check_possible_citation_payload:!1},..."boolean"==typeof N&&{check_possible_citation_payload:N},ui_request_body:{llm_formatted_response:a,request_id:e,max_concurrent_citations:10,citation_id:T,...p&&l&&{ecg_agent_name:l},...p&&d&&{plan_id:d},...p&&g&&{ui_chat_history:g},...u&&_&&{mmvf_list:_},...u&&m&&{files:m},...h&&"object"==typeof h&&!Array.isArray(h)&&h}}}},config:{headers:{"Content-Type":"application/json"},withCredentials:!0},errorMessage:"Failed to fetch on-demand citation",cacheOption:{key:`${w}:${k}:onDemandCitation:${e}:${r}:${p?y:t}:${p?l:""}:${"gpt_citation"===r?T:""}`},shouldCache:e=>Array.isArray(e?.result?.citations)&&Boolean(e.result.citations[0])})},exports.generateCacheKey=p,exports.makeApiRequest=l,exports.makeApiRequestWithTTLCache=E;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios"),r=require("./apicache.service.js"),t=require("../types/onDemandApi.types.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=a(e);const o=72e5,n=e=>{if(!e||"object"!=typeof e)return;const r=e;return"string"==typeof r.message?r.message:"string"==typeof r.errorMessage?r.errorMessage:"string"==typeof r.error?r.error:r.error&&"object"==typeof r.error&&"string"==typeof r.error.message?r.error.message:"string"==typeof r.details?r.details:r},i=async e=>{if(s.default.isAxiosError(e)){const r=e;if("ECONNABORTED"===r.code)return{type:t.NetworkErrorType.TIMEOUT,message:"The request took too long to complete. Please try again.",originalError:e};if(r.message.includes("net::ERR_NETWORK_CHANGED")||r.message.includes("net::ERR_INTERNET_DISCONNECTED")||r.message.includes("net::ERR_NAME_NOT_RESOLVED"))return{type:t.NetworkErrorType.INTERNET_DISCONNECTED,message:"Internet connection issue detected. Please check your network.",originalError:e};if(r.message.includes("Network Error")||"ERR_NETWORK"===r.code||r.message.includes("net::ERR_CONNECTION_REFUSED")||r.message.includes("net::ERR_EMPTY_RESPONSE"))return{type:t.NetworkErrorType.SERVER_UNREACHABLE,message:"Unable to connect to server. The service may be down or unreachable.",originalError:e};if(r.response&&r.response.status>=500)return{type:t.NetworkErrorType.SERVER_ERROR,message:`Service Unavailable. Server error (${r.response.status}).`,status:r.response.status,originalError:e};if(r.response&&r.response.status>=400&&r.response.status<500)return{type:t.NetworkErrorType.SERVER_ERROR,message:n(r.response.data)||`Request failed with status code ${r.response.status}`,status:r.response.status,originalError:e}}return{type:t.NetworkErrorType.UNKNOWN_ERROR,message:"An unexpected error occurred. Please try again later.",originalError:e}},c=(e,r=18e4)=>{const t=s.default.create({baseURL:e,timeout:r});return t.interceptors.request.use(async e=>e,async e=>{const r=await i(e);return Promise.reject(r)}),t.interceptors.response.use(e=>e,async e=>{const r=await i(e);return console.error("API Request Failed:",r),Promise.reject(r)}),t},p=(e,r,t)=>`${e}:${r}:${JSON.stringify(t||{})}`,u=c(),l=async(e,r,a)=>{try{const t=a?.baseURL?c(a.baseURL):u,{data:s,config:o}=a||{};let n;switch(e.toLowerCase()){case"get":n=await t.get(r,o);break;case"post":n=await t.post(r,s,o);break;case"put":n=await t.put(r,s,o);break;case"patch":n=await t.patch(r,s,o);break;case"delete":const a={...o,data:s};n=await t.delete(r,a);break;default:throw new Error(`Unsupported method: ${e}`)}return{responseData:n.data,error:null}}catch(e){if(e.type&&Object.values(t.NetworkErrorType).includes(e.type))return{responseData:null,error:e};return{responseData:null,error:await i(e)}}},E=async(e,a,s)=>{const{data:n,params:i,config:c,errorMessage:u,baseURL:E,cacheOption:y,shouldCache:d}=s||{},g=y?.ttl??o,_=y?.key||p(e,a,i);if(!y?.forceRefresh&&!y?.skipCache){const e=await r.apiCache.get(_);if(e)return{responseData:e.data,error:null,cacheMeta:{isFromCache:!0,timestamp:e.timestamp,ttl:e.ttl,cacheKey:_}}}const m={...c,...i&&{params:i}},R=await l(e,a,{data:n,config:m,baseURL:E});return!y?.skipCache&&null!=R.responseData&&(!d||d(R.responseData))&&await r.apiCache.set(_,R.responseData,g),{responseData:R.responseData,error:R.error?{errorMessage:R.error.type===t.NetworkErrorType.INTERNET_DISCONNECTED||R.error.type===t.NetworkErrorType.SLOW_CONNECTION||R.error.type===t.NetworkErrorType.TIMEOUT?R.error.message:R.error.type===t.NetworkErrorType.SERVER_UNREACHABLE?"Unable to connect to server. Please try again later.":u||R.error.message,errorObjData:R.error}:null,cacheMeta:{isFromCache:!1,timestamp:Date.now(),ttl:g,cacheKey:_}}};exports.NetworkErrorType=t.NetworkErrorType,exports.DEFAULT_CACHE_TTL=o,exports.createApiInstance=c,exports.fetchOnDemandCitation=async(e,r,t,a,s,o,n,i,c,p,u,l,y,d,g,_,m,R,N,h)=>{const f="artifact_chunks"===r||"scanned_doc_citation"===r?"artifact_chunks":r,T="gpt_citation"===r?"string"==typeof h?.citationId?h.citationId:"":p?y:`${f}_${t}`,w="post",k="/api/chat/chatResponse";return E(w,k,{baseURL:o,data:{name:n||"citationsprocessing",organizationName:i,prompt:"",useAgent:{agent_name:c||"ProcessCitationsAgent",metadata:u?R:void 0,arguments:{citation_type:r,is_primary_agent_request:!1,...p&&{check_possible_citation_payload:!1},..."boolean"==typeof N&&{check_possible_citation_payload:N},ui_request_body:{llm_formatted_response:a,request_id:e,max_concurrent_citations:10,citation_id:T,...p&&l&&{ecg_agent_name:l},...p&&d&&{plan_id:d},...p&&g&&{ui_chat_history:g},...u&&_&&{mmvf_list:_},...u&&m&&{files:m},...h&&"object"==typeof h&&!Array.isArray(h)&&h}}}},config:{headers:{"Content-Type":"application/json",...s&&s.trim()&&{Authorization:`Bearer ${s}`}},withCredentials:!0},errorMessage:"Failed to fetch on-demand citation",cacheOption:{key:`${w}:${k}:onDemandCitation:${e}:${r}:${p?y:t}:${p?l:""}:${"gpt_citation"===r?T:""}`},shouldCache:e=>Array.isArray(e?.result?.citations)&&Boolean(e.result.citations[0])})},exports.generateCacheKey=p,exports.makeApiRequest=l,exports.makeApiRequestWithTTLCache=E;
2
2
  //# sourceMappingURL=onDemandApi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"onDemandApi.js","sources":["../../../src/service/onDemandApi.ts"],"sourcesContent":["\nimport axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from \"axios\";\nimport { apiCache } from \"./apicache.service\";\nimport { NetworkErrorType } from \"../types/onDemandApi.types\";\nimport type {\n NetworkError,\n CachedAPIResponse,\n CacheOptions,\n OnDemandCitationFetchApiResponse,\n UIMediaValidationFeedbackItem,\n} from \"../types/onDemandApi.types\";\n\nexport { NetworkErrorType } from \"../types/onDemandApi.types\";\nexport type {\n NetworkError,\n ApiError,\n StandardAPIResponse,\n CachedAPIResponse,\n OnDemandCitationFetchResponse,\n OnDemandCitationFetchApiResponse,\n CacheOptions,\n} from \"../types/onDemandApi.types\";\n\nexport const DEFAULT_CACHE_TTL = 1000 * 60 * 60 * 2;\n\n\n// on-demand citation fetch — single-shot request that returns the final citations directly\nexport const fetchOnDemandCitation = async (\n requestId: string,\n citationType: string,\n citationNumber: number,\n llmFormattedResponse: string,\n token: string,\n baseUrl:string,\n citationAssistantProcessingName:string,\n orgName:string,\n citationAgentName:string,\n isEcgPayloadActive:boolean,\n isReqPayloadActive:boolean,\n ecg_agent_name:string,\n customCitationId:string, \n plan_id:string,\n ui_chat_history?: any,\n mmvf_list?:UIMediaValidationFeedbackItem[],\n files?: string[],\n metadata?:string,\n checkPossibleCitationPayload?: boolean,\n uiRequestBody?: Record<string, unknown>\n): Promise<CachedAPIResponse<any>> => {\n\n // if(!token || !token.trim()) {\n // throw new Error('Authorization token is required to fetch on-demand citation');\n // }\n\n const normalizedCitationType = citationType === \"artifact_chunks\" || citationType === \"scanned_doc_citation\" ? \"artifact_chunks\" : citationType;\n const citationId =\n citationType === 'gpt_citation'\n ? (typeof uiRequestBody?.citationId === 'string' ? uiRequestBody.citationId : '')\n : isEcgPayloadActive\n ? customCitationId\n : `${normalizedCitationType}_${citationNumber}`;\n \n const method = 'post';\n const endpoint = '/api/chat/chatResponse';\n\n\n return makeApiRequestWithTTLCache<CachedAPIResponse<any>>(\n method,\n endpoint,\n {\n baseURL: baseUrl,\n data: {\n name: citationAssistantProcessingName || 'citationsprocessing',\n organizationName: orgName,\n prompt: '',\n useAgent: {\n agent_name: citationAgentName || 'ProcessCitationsAgent',\n metadata: isReqPayloadActive ? metadata : undefined,\n arguments: {\n citation_type: citationType,\n is_primary_agent_request: false,\n ...(isEcgPayloadActive && {check_possible_citation_payload : false}),\n ...(typeof checkPossibleCitationPayload === 'boolean' && {check_possible_citation_payload: checkPossibleCitationPayload,}),\n ui_request_body: {\n llm_formatted_response: llmFormattedResponse,\n request_id: requestId,\n max_concurrent_citations: 10,\n citation_id: citationId,\n ...(isEcgPayloadActive && ecg_agent_name && {ecg_agent_name}),\n ...(isEcgPayloadActive && plan_id && {plan_id}),\n ...(isEcgPayloadActive && ui_chat_history && {ui_chat_history}),\n ...(isReqPayloadActive && mmvf_list && {mmvf_list}),\n ...(isReqPayloadActive && files && {files}),\n ...(uiRequestBody && typeof uiRequestBody === 'object' && !Array.isArray(uiRequestBody) && uiRequestBody),\n },\n },\n },\n },\n config: {\n headers: {\n 'Content-Type': 'application/json',\n },\n withCredentials: true,\n },\n errorMessage: 'Failed to fetch on-demand citation',\n cacheOption: {\n key: `${method}:${endpoint}:onDemandCitation:${requestId}:${citationType}:${\n isEcgPayloadActive ? customCitationId : citationNumber\n }:${\n isEcgPayloadActive ? ecg_agent_name : ''\n }:${citationType === \"gpt_citation\" ? citationId : ''}`,\n },\n shouldCache: (responseData) => Array.isArray(responseData?.result?.citations) && Boolean(responseData.result.citations[0]),\n }\n );\n};\n\n// legacy on-demand citation fetch — kept for older polling flows that still read from Redis\nexport const getOnDemandCitation = async (\n requestId: string,\n citationType: string,\n citationNumber: number,\n token:string,\n baseUrl:string\n): Promise<OnDemandCitationFetchApiResponse> => {\n return makeApiRequestWithTTLCache<OnDemandCitationFetchApiResponse>(\n 'get',\n '/api/redis/get-single-citations-data',\n {\n baseURL:baseUrl,\n config: {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n params: { request_id: `CitationAgent_${requestId}`, citation_type: citationType, citation_number: citationNumber },\n errorMessage: 'Failed to fetch on-demand citation',\n cacheOption: { ttl: Infinity },\n shouldCache: (data) => data.status === 'ready',\n }\n );\n};\n\nconst extractErrorMessage = (data: unknown): string | undefined => {\n if (!data || typeof data !== 'object') {\n return undefined;\n }\n // Cast to any to avoid TypeScript errors while checking properties\n const errorData = data as any;\n \n // Check for common error message patterns\n if (typeof errorData.message === 'string') {\n return errorData.message;\n }\n \n if (typeof errorData.errorMessage === 'string') {\n return errorData.errorMessage;\n }\n \n if (typeof errorData.error === 'string') {\n return errorData.error;\n }\n \n if (errorData.error && typeof errorData.error === 'object' && typeof errorData.error.message === 'string') {\n return errorData.error.message;\n }\n \n if (typeof errorData.details === 'string') {\n return errorData.details;\n }\n \n return errorData;\n};\n\n\n\n// Helper function to determine error type\nconst determineNetworkErrorType = async (error: any): Promise<NetworkError> => {\n // Check if there's an internet connection first\n // commented out\n // const isConnected = await checkInternetConnection();\n \n // if (!isConnected) {\n // return {\n // type: NetworkErrorType.INTERNET_DISCONNECTED,\n // message: 'No internet connection. Please check your network.',\n // originalError: error,\n // };\n // }\n\n // Axios specific error handling\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError;\n \n // Check for timeout\n if (axiosError.code === 'ECONNABORTED') {\n return {\n type: NetworkErrorType.TIMEOUT,\n message: 'The request took too long to complete. Please try again.',\n originalError: error,\n };\n }\n \n // Client connectivity issues - internet problems detected via error message\n if (axiosError.message.includes('net::ERR_NETWORK_CHANGED') ||\n axiosError.message.includes('net::ERR_INTERNET_DISCONNECTED') ||\n axiosError.message.includes('net::ERR_NAME_NOT_RESOLVED')) {\n return {\n type: NetworkErrorType.INTERNET_DISCONNECTED,\n message: 'Internet connection issue detected. Please check your network.',\n originalError: error,\n };\n }\n \n // Server connectivity issues - server is likely down\n if (axiosError.message.includes('Network Error') || \n axiosError.code === 'ERR_NETWORK' ||\n axiosError.message.includes('net::ERR_CONNECTION_REFUSED') ||\n axiosError.message.includes('net::ERR_EMPTY_RESPONSE')) {\n return {\n type: NetworkErrorType.SERVER_UNREACHABLE,\n message: 'Unable to connect to server. The service may be down or unreachable.',\n originalError: error,\n };\n }\n \n // Server errors (500 range)\n if (axiosError.response && axiosError.response.status >= 500) {\n return {\n type: NetworkErrorType.SERVER_ERROR,\n message: `Service Unavailable. Server error (${axiosError.response.status}).`,\n status: axiosError.response.status,\n originalError: error,\n };\n }\n \n // Client errors (400 range) - these are expected errors\n if (axiosError.response && axiosError.response.status >= 400 && axiosError.response.status < 500) {\n return {\n type: NetworkErrorType.SERVER_ERROR,\n message: extractErrorMessage(axiosError.response.data) || \n `Request failed with status code ${axiosError.response.status}`,\n status: axiosError.response.status,\n originalError: error,\n };\n }\n }\n \n // Default case - unknown error\n return {\n type: NetworkErrorType.UNKNOWN_ERROR,\n message: 'An unexpected error occurred. Please try again later.',\n originalError: error,\n };\n};\n\nexport const createApiInstance = (baseURL?: string, timeout: number = 180000): AxiosInstance => { // 3 mins timeout\n // Create a custom axios instance with interceptors and timeout\n const apiInstance = axios.create({\n baseURL: baseURL,\n timeout: timeout, // Default to 3 mins timeout\n });\n\n // Set up request interceptor for adding headers, etc.\n apiInstance.interceptors.request.use(\n async (config) => {\n \n return config;\n },\n async (error) => {\n const networkError = await determineNetworkErrorType(error);\n return Promise.reject(networkError);\n }\n );\n\n // Set up response interceptor for handling errors\n apiInstance.interceptors.response.use(\n (response: AxiosResponse) => {\n return response;\n },\n async (error: any) => {\n const networkError = await determineNetworkErrorType(error);\n \n // Log errors (you might want to send them to a monitoring service)\n console.error('API Request Failed:', networkError);\n \n // You can also dispatch actions to a global state manager (Redux, etc.)\n // store.dispatch(setNetworkError(networkError));\n \n return Promise.reject(networkError);\n }\n );\n\n return apiInstance;\n};\n\nexport const generateCacheKey = (\n method: string,\n url: string,\n params?: any\n) => `${method}:${url}:${JSON.stringify(params || {})}`;\n\nconst defaultApi = createApiInstance();\n\n\nexport const makeApiRequest = async <T>(\n method: string,\n url: string,\n options?: {\n data?: any,\n config?: AxiosRequestConfig,\n baseURL?: string\n }\n): Promise<{ \n responseData: T | null;\n error: NetworkError | null;\n}> => {\n try {\n // Determine which API instance to use\n const apiInstance = options?.baseURL \n ? createApiInstance(options.baseURL)\n : defaultApi;\n \n const { data, config } = options || {};\n \n let response;\n switch (method.toLowerCase()) {\n case 'get':\n response = await apiInstance.get<T>(url, config);\n break;\n case 'post':\n response = await apiInstance.post<T>(url, data, config);\n break;\n case 'put':\n response = await apiInstance.put<T>(url, data, config);\n break;\n case 'patch':\n response = await apiInstance.patch<T>(url, data, config);\n break;\n case 'delete':\n const deleteConfig = {\n ...config,\n data: data\n };\n response = await apiInstance.delete<T>(url, deleteConfig);\n break;\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n \n return {\n responseData: response.data,\n error: null,\n };\n } catch (error: any) {\n // The error should already be processed by our interceptor\n if (error.type && Object.values(NetworkErrorType).includes(error.type)) {\n return {\n responseData: null,\n error: error as NetworkError,\n };\n }\n \n // Fallback for unhandled errors\n const networkError = await determineNetworkErrorType(error);\n return {\n responseData: null,\n error: networkError,\n };\n }\n};\n\nexport const makeApiRequestWithTTLCache = async <\n ResponseType extends CachedAPIResponse<any>\n>(\n method: string,\n url: string,\n options?: {\n data?: any;\n params?: any;\n config?: AxiosRequestConfig;\n errorMessage?: string;\n baseURL?: string;\n cacheOption?: CacheOptions;\n // return false to skip writing to cache for this response; defaults to caching all successful responses\n shouldCache?: (responseData: NonNullable<ResponseType['responseData']>) => boolean;\n }\n): Promise<ResponseType> => {\n type ExpectedDataType = NonNullable<ResponseType['responseData']>;\n\n const { data, params, config, errorMessage, baseURL, cacheOption, shouldCache } =\n options || {};\n\n const ttl = cacheOption?.ttl ?? DEFAULT_CACHE_TTL;\n const cacheKey =\n cacheOption?.key || generateCacheKey(method, url, params);\n\n // 1. Try cache\n if (!cacheOption?.forceRefresh && !cacheOption?.skipCache) {\n const cached = await apiCache.get<ExpectedDataType>(cacheKey);\n\n if (cached) {\n return {\n responseData: cached.data,\n error: null,\n cacheMeta: {\n isFromCache: true,\n timestamp: cached.timestamp,\n ttl: cached.ttl,\n cacheKey,\n },\n } as ResponseType;\n }\n }\n\n // 2. Prepare config\n const mergedConfig: AxiosRequestConfig = {\n ...config,\n ...(params && { params }),\n };\n\n // 3. Call API\n const result = await makeApiRequest<ExpectedDataType>(method, url, {\n data,\n config: mergedConfig,\n baseURL,\n });\n\n // 4. Store in cache — skipped if cacheOption.skipCache is set, or if shouldCache returns false\n const allowWrite =\n !cacheOption?.skipCache &&\n result.responseData != null &&\n (shouldCache ? shouldCache(result.responseData) : true);\n\n if (allowWrite) {\n await apiCache.set(cacheKey, result.responseData, ttl);\n }\n\n // 5. Return SAME structure as before + cacheMeta\n return {\n responseData: result.responseData,\n error: result.error\n ? {\n errorMessage:\n result.error.type === NetworkErrorType.INTERNET_DISCONNECTED ||\n result.error.type === NetworkErrorType.SLOW_CONNECTION ||\n result.error.type === NetworkErrorType.TIMEOUT\n ? result.error.message\n : result.error.type === NetworkErrorType.SERVER_UNREACHABLE\n ? \"Unable to connect to server. Please try again later.\"\n : errorMessage || result.error.message,\n errorObjData: result.error,\n }\n : null,\n cacheMeta: {\n isFromCache: false,\n timestamp: Date.now(),\n ttl,\n cacheKey,\n },\n } as ResponseType;\n};\n"],"names":["DEFAULT_CACHE_TTL","extractErrorMessage","data","errorData","message","errorMessage","error","details","determineNetworkErrorType","async","axios","isAxiosError","axiosError","code","type","NetworkErrorType","TIMEOUT","originalError","includes","INTERNET_DISCONNECTED","SERVER_UNREACHABLE","response","status","SERVER_ERROR","UNKNOWN_ERROR","createApiInstance","baseURL","timeout","apiInstance","create","interceptors","request","use","config","networkError","Promise","reject","console","generateCacheKey","method","url","params","JSON","stringify","defaultApi","makeApiRequest","options","toLowerCase","get","post","put","patch","deleteConfig","delete","Error","responseData","Object","values","makeApiRequestWithTTLCache","cacheOption","shouldCache","ttl","cacheKey","key","forceRefresh","skipCache","cached","apiCache","cacheMeta","isFromCache","timestamp","mergedConfig","result","set","SLOW_CONNECTION","errorObjData","Date","now","requestId","citationType","citationNumber","llmFormattedResponse","token","baseUrl","citationAssistantProcessingName","orgName","citationAgentName","isEcgPayloadActive","isReqPayloadActive","ecg_agent_name","customCitationId","plan_id","ui_chat_history","mmvf_list","files","metadata","checkPossibleCitationPayload","uiRequestBody","normalizedCitationType","citationId","endpoint","name","organizationName","prompt","useAgent","agent_name","arguments","citation_type","is_primary_agent_request","check_possible_citation_payload","ui_request_body","llm_formatted_response","request_id","max_concurrent_citations","citation_id","Array","isArray","headers","withCredentials","citations","Boolean"],"mappings":"4PAuBa,MAAAA,EAAoB,KAwH3BC,EAAuBC,IAC3B,IAAKA,GAAwB,iBAATA,EACX,OAGT,MAAMC,EAAYD,EAGd,MAA6B,iBAAtBC,EAAUC,QACZD,EAAUC,QAGmB,iBAA3BD,EAAUE,aACZF,EAAUE,aAGY,iBAApBF,EAAUG,MACZH,EAAUG,MAGfH,EAAUG,OAAoC,iBAApBH,EAAUG,OAAyD,iBAA5BH,EAAUG,MAAMF,QAC5ED,EAAUG,MAAMF,QAGQ,iBAAtBD,EAAUI,QACZJ,EAAUI,QAGZJ,GAMHK,EAA4BC,MAAOH,IAcnC,GAAAI,EAAA,QAAMC,aAAaL,GAAQ,CAC7B,MAAMM,EAAaN,EAGf,G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B,EACA6D,EACA,CACE1E,QAASyD,EACTjF,KAAM,CACJmG,KAAMjB,GAAmC,sBACzCkB,iBAAkBjB,EAClBkB,OAAQ,GACRC,SAAU,CACRC,WAAYnB,GAAqB,wBACjCS,SAAUP,EAAqBO,OAAW,EAC1CW,UAAW,CACTC,cAAe5B,EACf6B,0BAA0B,KACtBrB,GAAsB,CAACsB,iCAAkC,MACjB,kBAAjCb,GAA8C,CAACa,gCAAiCb,GAC3Fc,gBAAiB,CACfC,uBAAwB9B,EACxB+B,WAAYlC,EACZmC,yBAA0B,GAC1BC,YAAaf,KACTZ,GAAsBE,GAAkB,CAACA,qBACzCF,GAAsBI,GAAW,CAACA,cAClCJ,GAAsBK,GAAmB,CAACA,sBAC1CJ,GAAsBK,GAAa,CAACA,gBACpCL,GAAsBM,GAAS,CAACA,YAChCG,GAA0C,iBAAlBA,IAA+BkB,MAAMC,QAAQnB,IAAkBA,MAKnGhE,OAAQ,CACNoF,QAAS,CACP,eAAgB,oBAElBC,iBAAiB,GAEnBjH,aAAc,qCACdsD,YAAa,CACXI,IAAK,GAAGxB,KAAU6D,sBAA6BtB,KAAaC,KAC1DQ,EAAqBG,EAAmBV,KAExCO,EAAqBE,EAAiB,MACnB,iBAAjBV,EAAkCoB,EAAa,MAErDvC,YAAcL,GAAiB4D,MAAMC,QAAQ7D,GAAciB,QAAQ+C,YAAcC,QAAQjE,EAAaiB,OAAO+C,UAAU"}
1
+ {"version":3,"file":"onDemandApi.js","sources":["../../../src/service/onDemandApi.ts"],"sourcesContent":["\nimport axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from \"axios\";\nimport { apiCache } from \"./apicache.service\";\nimport { NetworkErrorType } from \"../types/onDemandApi.types\";\nimport type {\n NetworkError,\n CachedAPIResponse,\n CacheOptions,\n OnDemandCitationFetchApiResponse,\n UIMediaValidationFeedbackItem,\n} from \"../types/onDemandApi.types\";\n\nexport { NetworkErrorType } from \"../types/onDemandApi.types\";\nexport type {\n NetworkError,\n ApiError,\n StandardAPIResponse,\n CachedAPIResponse,\n OnDemandCitationFetchResponse,\n OnDemandCitationFetchApiResponse,\n CacheOptions,\n} from \"../types/onDemandApi.types\";\n\nexport const DEFAULT_CACHE_TTL = 1000 * 60 * 60 * 2;\n\n\n// on-demand citation fetch — single-shot request that returns the final citations directly\nexport const fetchOnDemandCitation = async (\n requestId: string,\n citationType: string,\n citationNumber: number,\n llmFormattedResponse: string,\n token: string,\n baseUrl:string,\n citationAssistantProcessingName:string,\n orgName:string,\n citationAgentName:string,\n isEcgPayloadActive:boolean,\n isReqPayloadActive:boolean,\n ecg_agent_name:string,\n customCitationId:string, \n plan_id:string,\n ui_chat_history?: any,\n mmvf_list?:UIMediaValidationFeedbackItem[],\n files?: string[],\n metadata?:string,\n checkPossibleCitationPayload?: boolean,\n uiRequestBody?: Record<string, unknown>\n): Promise<CachedAPIResponse<any>> => {\n\n // if(!token || !token.trim()) {\n // throw new Error('Authorization token is required to fetch on-demand citation');\n // }\n\n const normalizedCitationType = citationType === \"artifact_chunks\" || citationType === \"scanned_doc_citation\" ? \"artifact_chunks\" : citationType;\n const citationId =\n citationType === 'gpt_citation'\n ? (typeof uiRequestBody?.citationId === 'string' ? uiRequestBody.citationId : '')\n : isEcgPayloadActive\n ? customCitationId\n : `${normalizedCitationType}_${citationNumber}`;\n \n const method = 'post';\n const endpoint = '/api/chat/chatResponse';\n\n\n return makeApiRequestWithTTLCache<CachedAPIResponse<any>>(\n method,\n endpoint,\n {\n baseURL: baseUrl,\n data: {\n name: citationAssistantProcessingName || 'citationsprocessing',\n organizationName: orgName,\n prompt: '',\n useAgent: {\n agent_name: citationAgentName || 'ProcessCitationsAgent',\n metadata: isReqPayloadActive ? metadata : undefined,\n arguments: {\n citation_type: citationType,\n is_primary_agent_request: false,\n ...(isEcgPayloadActive && {check_possible_citation_payload : false}),\n ...(typeof checkPossibleCitationPayload === 'boolean' && {check_possible_citation_payload: checkPossibleCitationPayload,}),\n ui_request_body: {\n llm_formatted_response: llmFormattedResponse,\n request_id: requestId,\n max_concurrent_citations: 10,\n citation_id: citationId,\n ...(isEcgPayloadActive && ecg_agent_name && {ecg_agent_name}),\n ...(isEcgPayloadActive && plan_id && {plan_id}),\n ...(isEcgPayloadActive && ui_chat_history && {ui_chat_history}),\n ...(isReqPayloadActive && mmvf_list && {mmvf_list}),\n ...(isReqPayloadActive && files && {files}),\n ...(uiRequestBody && typeof uiRequestBody === 'object' && !Array.isArray(uiRequestBody) && uiRequestBody),\n },\n },\n },\n },\n config: {\n headers: {\n 'Content-Type': 'application/json',\n ...(token && token.trim() && { Authorization: `Bearer ${token}` }),\n },\n withCredentials: true,\n },\n errorMessage: 'Failed to fetch on-demand citation',\n cacheOption: {\n key: `${method}:${endpoint}:onDemandCitation:${requestId}:${citationType}:${\n isEcgPayloadActive ? customCitationId : citationNumber\n }:${\n isEcgPayloadActive ? ecg_agent_name : ''\n }:${citationType === \"gpt_citation\" ? citationId : ''}`,\n },\n shouldCache: (responseData) => Array.isArray(responseData?.result?.citations) && Boolean(responseData.result.citations[0]),\n }\n );\n};\n\n// legacy on-demand citation fetch — kept for older polling flows that still read from Redis\nexport const getOnDemandCitation = async (\n requestId: string,\n citationType: string,\n citationNumber: number,\n token:string,\n baseUrl:string\n): Promise<OnDemandCitationFetchApiResponse> => {\n return makeApiRequestWithTTLCache<OnDemandCitationFetchApiResponse>(\n 'get',\n '/api/redis/get-single-citations-data',\n {\n baseURL:baseUrl,\n config: {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n params: { request_id: `CitationAgent_${requestId}`, citation_type: citationType, citation_number: citationNumber },\n errorMessage: 'Failed to fetch on-demand citation',\n cacheOption: { ttl: Infinity },\n shouldCache: (data) => data.status === 'ready',\n }\n );\n};\n\nconst extractErrorMessage = (data: unknown): string | undefined => {\n if (!data || typeof data !== 'object') {\n return undefined;\n }\n // Cast to any to avoid TypeScript errors while checking properties\n const errorData = data as any;\n \n // Check for common error message patterns\n if (typeof errorData.message === 'string') {\n return errorData.message;\n }\n \n if (typeof errorData.errorMessage === 'string') {\n return errorData.errorMessage;\n }\n \n if (typeof errorData.error === 'string') {\n return errorData.error;\n }\n \n if (errorData.error && typeof errorData.error === 'object' && typeof errorData.error.message === 'string') {\n return errorData.error.message;\n }\n \n if (typeof errorData.details === 'string') {\n return errorData.details;\n }\n \n return errorData;\n};\n\n\n\n// Helper function to determine error type\nconst determineNetworkErrorType = async (error: any): Promise<NetworkError> => {\n // Check if there's an internet connection first\n // commented out\n // const isConnected = await checkInternetConnection();\n \n // if (!isConnected) {\n // return {\n // type: NetworkErrorType.INTERNET_DISCONNECTED,\n // message: 'No internet connection. Please check your network.',\n // originalError: error,\n // };\n // }\n\n // Axios specific error handling\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError;\n \n // Check for timeout\n if (axiosError.code === 'ECONNABORTED') {\n return {\n type: NetworkErrorType.TIMEOUT,\n message: 'The request took too long to complete. Please try again.',\n originalError: error,\n };\n }\n \n // Client connectivity issues - internet problems detected via error message\n if (axiosError.message.includes('net::ERR_NETWORK_CHANGED') ||\n axiosError.message.includes('net::ERR_INTERNET_DISCONNECTED') ||\n axiosError.message.includes('net::ERR_NAME_NOT_RESOLVED')) {\n return {\n type: NetworkErrorType.INTERNET_DISCONNECTED,\n message: 'Internet connection issue detected. Please check your network.',\n originalError: error,\n };\n }\n \n // Server connectivity issues - server is likely down\n if (axiosError.message.includes('Network Error') || \n axiosError.code === 'ERR_NETWORK' ||\n axiosError.message.includes('net::ERR_CONNECTION_REFUSED') ||\n axiosError.message.includes('net::ERR_EMPTY_RESPONSE')) {\n return {\n type: NetworkErrorType.SERVER_UNREACHABLE,\n message: 'Unable to connect to server. The service may be down or unreachable.',\n originalError: error,\n };\n }\n \n // Server errors (500 range)\n if (axiosError.response && axiosError.response.status >= 500) {\n return {\n type: NetworkErrorType.SERVER_ERROR,\n message: `Service Unavailable. Server error (${axiosError.response.status}).`,\n status: axiosError.response.status,\n originalError: error,\n };\n }\n \n // Client errors (400 range) - these are expected errors\n if (axiosError.response && axiosError.response.status >= 400 && axiosError.response.status < 500) {\n return {\n type: NetworkErrorType.SERVER_ERROR,\n message: extractErrorMessage(axiosError.response.data) || \n `Request failed with status code ${axiosError.response.status}`,\n status: axiosError.response.status,\n originalError: error,\n };\n }\n }\n \n // Default case - unknown error\n return {\n type: NetworkErrorType.UNKNOWN_ERROR,\n message: 'An unexpected error occurred. Please try again later.',\n originalError: error,\n };\n};\n\nexport const createApiInstance = (baseURL?: string, timeout: number = 180000): AxiosInstance => { // 3 mins timeout\n // Create a custom axios instance with interceptors and timeout\n const apiInstance = axios.create({\n baseURL: baseURL,\n timeout: timeout, // Default to 3 mins timeout\n });\n\n // Set up request interceptor for adding headers, etc.\n apiInstance.interceptors.request.use(\n async (config) => {\n \n return config;\n },\n async (error) => {\n const networkError = await determineNetworkErrorType(error);\n return Promise.reject(networkError);\n }\n );\n\n // Set up response interceptor for handling errors\n apiInstance.interceptors.response.use(\n (response: AxiosResponse) => {\n return response;\n },\n async (error: any) => {\n const networkError = await determineNetworkErrorType(error);\n \n // Log errors (you might want to send them to a monitoring service)\n console.error('API Request Failed:', networkError);\n \n // You can also dispatch actions to a global state manager (Redux, etc.)\n // store.dispatch(setNetworkError(networkError));\n \n return Promise.reject(networkError);\n }\n );\n\n return apiInstance;\n};\n\nexport const generateCacheKey = (\n method: string,\n url: string,\n params?: any\n) => `${method}:${url}:${JSON.stringify(params || {})}`;\n\nconst defaultApi = createApiInstance();\n\n\nexport const makeApiRequest = async <T>(\n method: string,\n url: string,\n options?: {\n data?: any,\n config?: AxiosRequestConfig,\n baseURL?: string\n }\n): Promise<{ \n responseData: T | null;\n error: NetworkError | null;\n}> => {\n try {\n // Determine which API instance to use\n const apiInstance = options?.baseURL \n ? createApiInstance(options.baseURL)\n : defaultApi;\n \n const { data, config } = options || {};\n \n let response;\n switch (method.toLowerCase()) {\n case 'get':\n response = await apiInstance.get<T>(url, config);\n break;\n case 'post':\n response = await apiInstance.post<T>(url, data, config);\n break;\n case 'put':\n response = await apiInstance.put<T>(url, data, config);\n break;\n case 'patch':\n response = await apiInstance.patch<T>(url, data, config);\n break;\n case 'delete':\n const deleteConfig = {\n ...config,\n data: data\n };\n response = await apiInstance.delete<T>(url, deleteConfig);\n break;\n default:\n throw new Error(`Unsupported method: ${method}`);\n }\n \n return {\n responseData: response.data,\n error: null,\n };\n } catch (error: any) {\n // The error should already be processed by our interceptor\n if (error.type && Object.values(NetworkErrorType).includes(error.type)) {\n return {\n responseData: null,\n error: error as NetworkError,\n };\n }\n \n // Fallback for unhandled errors\n const networkError = await determineNetworkErrorType(error);\n return {\n responseData: null,\n error: networkError,\n };\n }\n};\n\nexport const makeApiRequestWithTTLCache = async <\n ResponseType extends CachedAPIResponse<any>\n>(\n method: string,\n url: string,\n options?: {\n data?: any;\n params?: any;\n config?: AxiosRequestConfig;\n errorMessage?: string;\n baseURL?: string;\n cacheOption?: CacheOptions;\n // return false to skip writing to cache for this response; defaults to caching all successful responses\n shouldCache?: (responseData: NonNullable<ResponseType['responseData']>) => boolean;\n }\n): Promise<ResponseType> => {\n type ExpectedDataType = NonNullable<ResponseType['responseData']>;\n\n const { data, params, config, errorMessage, baseURL, cacheOption, shouldCache } =\n options || {};\n\n const ttl = cacheOption?.ttl ?? DEFAULT_CACHE_TTL;\n const cacheKey =\n cacheOption?.key || generateCacheKey(method, url, params);\n\n // 1. Try cache\n if (!cacheOption?.forceRefresh && !cacheOption?.skipCache) {\n const cached = await apiCache.get<ExpectedDataType>(cacheKey);\n\n if (cached) {\n return {\n responseData: cached.data,\n error: null,\n cacheMeta: {\n isFromCache: true,\n timestamp: cached.timestamp,\n ttl: cached.ttl,\n cacheKey,\n },\n } as ResponseType;\n }\n }\n\n // 2. Prepare config\n const mergedConfig: AxiosRequestConfig = {\n ...config,\n ...(params && { params }),\n };\n\n // 3. Call API\n const result = await makeApiRequest<ExpectedDataType>(method, url, {\n data,\n config: mergedConfig,\n baseURL,\n });\n\n // 4. Store in cache — skipped if cacheOption.skipCache is set, or if shouldCache returns false\n const allowWrite =\n !cacheOption?.skipCache &&\n result.responseData != null &&\n (shouldCache ? shouldCache(result.responseData) : true);\n\n if (allowWrite) {\n await apiCache.set(cacheKey, result.responseData, ttl);\n }\n\n // 5. Return SAME structure as before + cacheMeta\n return {\n responseData: result.responseData,\n error: result.error\n ? {\n errorMessage:\n result.error.type === NetworkErrorType.INTERNET_DISCONNECTED ||\n result.error.type === NetworkErrorType.SLOW_CONNECTION ||\n result.error.type === NetworkErrorType.TIMEOUT\n ? result.error.message\n : result.error.type === NetworkErrorType.SERVER_UNREACHABLE\n ? \"Unable to connect to server. Please try again later.\"\n : errorMessage || result.error.message,\n errorObjData: result.error,\n }\n : null,\n cacheMeta: {\n isFromCache: false,\n timestamp: Date.now(),\n ttl,\n cacheKey,\n },\n } as ResponseType;\n};\n"],"names":["DEFAULT_CACHE_TTL","extractErrorMessage","data","errorData","message","errorMessage","error","details","determineNetworkErrorType","async","axios","isAxiosError","axiosError","code","type","NetworkErrorType","TIMEOUT","originalError","includes","INTERNET_DISCONNECTED","SERVER_UNREACHABLE","response","status","SERVER_ERROR","UNKNOWN_ERROR","createApiInstance","baseURL","timeout","apiInstance","create","interceptors","request","use","config","networkError","Promise","reject","console","generateCacheKey","method","url","params","JSON","stringify","defaultApi","makeApiRequest","options","toLowerCase","get","post","put","patch","deleteConfig","delete","Error","responseData","Object","values","makeApiRequestWithTTLCache","cacheOption","shouldCache","ttl","cacheKey","key","forceRefresh","skipCache","cached","apiCache","cacheMeta","isFromCache","timestamp","mergedConfig","result","set","SLOW_CONNECTION","errorObjData","Date","now","requestId","citationType","citationNumber","llmFormattedResponse","token","baseUrl","citationAssistantProcessingName","orgName","citationAgentName","isEcgPayloadActive","isReqPayloadActive","ecg_agent_name","customCitationId","plan_id","ui_chat_history","mmvf_list","files","metadata","checkPossibleCitationPayload","uiRequestBody","normalizedCitationType","citationId","endpoint","name","organizationName","prompt","useAgent","agent_name","arguments","citation_type","is_primary_agent_request","check_possible_citation_payload","ui_request_body","llm_formatted_response","request_id","max_concurrent_citations","citation_id","Array","isArray","headers","trim","Authorization","withCredentials","citations","Boolean"],"mappings":"4PAuBa,MAAAA,EAAoB,KAyH3BC,EAAuBC,IAC3B,IAAKA,GAAwB,iBAATA,EACX,OAGT,MAAMC,EAAYD,EAGd,MAA6B,iBAAtBC,EAAUC,QACZD,EAAUC,QAGmB,iBAA3BD,EAAUE,aACZF,EAAUE,aAGY,iBAApBF,EAAUG,MACZH,EAAUG,MAGfH,EAAUG,OAAoC,iBAApBH,EAAUG,OAAyD,iBAA5BH,EAAUG,MAAMF,QAC5ED,EAAUG,MAAMF,QAGQ,iBAAtBD,EAAUI,QACZJ,EAAUI,QAGZJ,GAMHK,EAA4BC,MAAOH,IAcnC,GAAAI,EAAA,QAAMC,aAAaL,GAAQ,CAC7B,MAAMM,EAAaN,EAGf,GAAoB,iBAApBM,EAAWC,KACN,MAAA,CACLC,KAAMC,EAAiBA,iBAAAC,QACvBZ,QAAS,2DACTa,cAAeX,GAKnB,GAAIM,EAAWR,QAAQc,SAAS,6BAC5BN,EAAWR,QAAQc,SAAS,mCAC5BN,EAAWR,QAAQc,SAAS,8BACvB,MAAA,CACLJ,KAAMC,EAAiBA,iBAAAI,sBACvBf,QAAS,iEACTa,cAAeX,GAKnB,GAAIM,EAAWR,QAAQc,SAAS,kBACR,gBAApBN,EAAWC,MACXD,EAAWR,QAAQc,SAAS,gCAC5BN,EAAWR,QAAQc,SAAS,2BACvB,MAAA,CACLJ,KAAMC,EAAiBA,iBAAAK,mBACvBhB,QAAS,uEACTa,cAAeX,GAKnB,GAAIM,EAAWS,UAAYT,EAAWS,SAASC,QAAU,IAChD,MAAA,CACLR,KAAMC,EAAiBA,iBAAAQ,aACvBnB,QAAS,sCAAsCQ,EAAWS,SAASC,WACnEA,OAAQV,EAAWS,SAASC,OAC5BL,cAAeX,GAKf,GAAAM,EAAWS,UAAYT,EAAWS,SAASC,QAAU,KA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iBAAiB,GAEnBnH,aAAc,qCACdsD,YAAa,CACXI,IAAK,GAAGxB,KAAU6D,sBAA6BtB,KAAaC,KAC1DQ,EAAqBG,EAAmBV,KAExCO,EAAqBE,EAAiB,MACnB,iBAAjBV,EAAkCoB,EAAa,MAErDvC,YAAcL,GAAiB4D,MAAMC,QAAQ7D,GAAciB,QAAQiD,YAAcC,QAAQnE,EAAaiB,OAAOiD,UAAU"}
@@ -1,2 +1,2 @@
1
- import{jsxs as e,jsx as t,Fragment as i}from"react/jsx-runtime";import{Globe as a,ChevronUp as o,ChevronDown as n,Maximize2 as r,X as l,ExternalLink as s}from"lucide-react";import{useState as c,useEffect as d,useMemo as p,useRef as u}from"react";import m from"./ResizableSplitPane.js";import h from"../PdfViewer/PdfViewer.js";import{DefaultFullScreenCloseIcon as g,DefaultFullScreenIcon as x}from"../../assests/svg/PdfViewerIcons.js";import f from"react-markdown";import b from"rehype-raw";import{Dialog as _,Box as y}from"@mui/material";import{SHARED_MARKDOWN_STYLES as w}from"./CognitiveCompareConfig.js";import"react-dom";import{useCompareContext as C}from"./CompareContext.js";import{processGuidelinesMarkdown as F}from"./Guidelines/utils/processGuidelinesMarkdown.js";import D from"../GptWebCitation/GptWebCitation.js";import{CitationType as v}from"../GptWebCitation/types.js";import"./components/SubSectionAccordion.js";import"./components/LHSSectionRow.js";import"./components/RHSSectionRow.js";const P=e=>(e?.extraMetaData||e)?.aiReasoningCitation?.gpt_citation?.[0]||null,T="https://dev-proposals-ai.techo.camp/utility/ca-workflow-composer-agent/get_citation",S="sai.siddhartha@techolution.com",k="672e32f7a0e8fe2e8e50bcba",N="TNV Sai Siddhartha",I="90vh",j=`calc(${I} - 120px)`,R=()=>"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)}),G=(e,t)=>{const i=(e=>e?.payloadCitationId||e?.extraMetaData?.payloadCitationId||"")(e)||t||R();return((e,t)=>{e&&"object"==typeof e&&(e.payloadCitationId=t,e.extraMetaData&&"object"==typeof e.extraMetaData&&(e.extraMetaData.payloadCitationId=t))})(e,i),i},U=({metaData:e,isFullscreen:i=!1})=>{const{gptWebCitationConfig:a}=C(),m=p(()=>(e=>({endpoint:e?.endpoint||T,userEmail:e?.userEmail||S,userId:e?.userId||k,userName:e?.userName||N,headers:e?.headers}))(a),[a]),h=e?.webGpt,g=u(null);g.current||(g.current=R());const x=p(()=>((e,t,i)=>{const a=P(e),o=a?.customMetaData||{},n=o?.value||{},r=e?.webSearchAnswer||{},l=e?.extraMetaData||e||{};return{userEmail:e?.userEmail||r?.userEmail||t?.userEmail||"",userId:e?.userId||r?.userId||t?.userId||"",userName:e?.userName||r?.userName||t?.userName||"",citationId:G(e,i),citationUrl:n?.citationUrl||r?.citationUrl||"",content:l?.Reasoning||r?.enhanced_content||"",citationType:n?.citationType||"web",citatioNumber:o?.citation_number??a?.citation_number??Number(e?.reasoningId||0)}})(h,m,g.current||void 0),[h,m]),f=p(()=>P(h),[h]),b=f?.customMetaData?.value||{},_=h?.extraMetaData||h||{},[y,w]=c(),[F,I]=c("pending"),[U,E]=c(!0);d(()=>{let e=!0;return(async()=>{if(m.endpoint&&x?.citationUrl&&x?.content){I("pending");try{const t=await fetch(m.endpoint,{method:"POST",headers:{"actor-id":x.userEmail,Accept:"application/json, text/plain, */*","Content-Type":"application/json",...m.headers||{}},body:JSON.stringify(x)});if(!t.ok)throw new Error(`Failed to fetch GPT web citation (${t.status})`);const i=await t.json();if(!e)return;w(i?.responseData||i?.result||i?.data||i),I("success")}catch(t){if(!e)return;console.error("Failed to load GPT web citation",t),I("error")}}else I("error")})(),()=>{e=!1}},[x,m]);const A=p(()=>({item:{confidence_score:Number(_?.Confidence_score||0),text:b?.paraphrase||"Web citation reasoning",dataSource:b?.text||_?.Reasoning||"",paraphrase:b?.paraphrase||""},headerTitle:"GPT Web Citation",index:Number(x?.citatioNumber||1)-1,iconsConfig:{ChevronDownIcon:n,ChevronUpIcon:o,MaximizeIcon:r,CloseIcon:l}}),[b,x?.citatioNumber,_]),H=p(()=>({...A,...i?{bodyHeight:j}:{}}),[A,i]);return t(D,{gptCitation:H,defaultCitationUrl:x?.citationUrl||"",citationType:v.GPT_WEB,webCitationData:y,webCitationStatus:F,showWebCitation:U,onToggleCitationView:()=>E(e=>!e),iconsConfig:{MaximizeIcon:r,ExternalLinkIcon:s},isFixedHeight:!0})},E=({href:e,metaData:a,citationTitle:o,citationType:n,citationReason:r,isFullscreen:l})=>{const{guidelinesData:s}=C(),{citationNumber:c,phraseToHighlight:d,citationTypeFromHref:u}=(e=>{try{const{citationNumber:t,parsedUrl:i}=(e=>{const t=e.match(/^(?:pdf_citation|deviation_summary)\$(\d+)/);if(t)try{const i=e.indexOf("?"),a=i>=0?e.slice(i):"";return{citationNumber:t[1],parsedUrl:new URL(a||"./",window.location.origin)}}catch{return{citationNumber:t[1],parsedUrl:null}}try{const t=new URL(e,window.location.origin);return{citationNumber:t.searchParams.get("citationNumber")||t.searchParams.get("citation_number"),parsedUrl:t}}catch{return{citationNumber:null,parsedUrl:null}}})(e),a=i?.searchParams.get("phrase_to_highlight")||null;return{citationNumber:t,phraseToHighlight:a,citationTypeFromHref:i?.searchParams.get("citation_type")||null}}catch{return{citationNumber:null,phraseToHighlight:null,citationTypeFromHref:null}}})(e),g=n||u||void 0,x="il_rulebook_citation"===g?"rulebook_citation":g,_=c&&a?.citations?.[c]||{},D=a?.docData?.documents||{},v=a?.docData?.input_index_map||{},P=Object.keys(a?.citations||{}).length>0||Object.keys(a?.docData||{}).length>0,T=v?.[0],S=v?.[1],k=T?D[T]:null,N=S?D[S]:null,I=T?_[T]:null,j=S?_[S]:null,R=p(()=>I&&k?t(h,{defaultScale:"PageWidth",showFullScreenAction:!1,showHighlightsAction:!1,pdfName:k?.title,pdfUrl:k?.signed_url,highlightText:[I?.highlighted_text??""],highlightPages:{1:I?.custom_metadata?.pdf_start_page_number},jumpToPageValue:1,highlightCordinatePages:[],useCoordinates:!1,useRange:!0,rangeOfPages:[I?.custom_metadata?.pdf_start_page_number,I?.custom_metadata?.pdf_end_page_number]}):null,[k?.title,k?.signed_url,I?.highlighted_text,I?.custom_metadata?.pdf_start_page_number,I?.custom_metadata?.pdf_end_page_number]),G=p(()=>j&&N?t(h,{defaultScale:"PageWidth",showFullScreenAction:!1,showHighlightsAction:!1,pdfName:N?.title,pdfUrl:N?.signed_url,jumpToPageValue:1,highlightText:[j?.highlighted_text??""],highlightPages:{1:j?.custom_metadata?.pdf_start_page_number},highlightCordinatePages:[],useCoordinates:!1,useRange:!0,rangeOfPages:[j?.custom_metadata?.pdf_start_page_number,j?.custom_metadata?.pdf_end_page_number]}):null,[N?.title,N?.signed_url,j?.highlighted_text,j?.custom_metadata?.pdf_start_page_number,j?.custom_metadata?.pdf_end_page_number]),E="dual_citation"===x,A=E&&!!a?.webGpt,H=p(()=>{if(!R)return null;const e=A?t(U,{metaData:a,isFullscreen:l}):"rulebook_citation"===x?t(i,{children:t(y,{sx:{padding:"0px 20px",backgroundColor:"#FFFFFF",borderRadius:"8px",...w,overflow:"auto"},children:t(f,{rehypePlugins:[b],children:F({guidelinesData:s,targetHighlights:[d],labelColor:"#FEF08A"})})})}):G;return e?t(m,{leftComponent:R,rightComponent:e,isFullscreen:l}):R},[R,G,x,A,a,l,s,d]);return a?.webGpt&&!P?t(U,{metaData:a,isFullscreen:l}):c?"rulebook_citation"===x?t("div",I?{style:{height:"100%",display:"flex",flexDirection:"column"},children:H}:{style:{padding:"12px",fontSize:"13px",color:"#344054",lineHeight:1.5},children:r||"Rulebook citation selected."}):E?I||j?t("div",{style:{height:"100%",display:"flex",flexDirection:"column"},children:H}):a?.webGpt?t(U,{metaData:a,isFullscreen:l}):t("div",{children:"Missing PDF Citation. Please try again later"}):["contract","clause"].includes(o)?t("div",I||j?{style:{height:"100%",display:"flex",flexDirection:"column"},children:H}:{children:"Missing PDF Citation. Please try again later"}):t("div",{children:"No Citation Found. Please try again later"}):null},A=({href:i,children:r,citationType:l,citationReason:s,metaData:p,chevronUpComponent:u=null,chevronDownComponent:m=null,customStyle:h={},defaultState:f=!1,onFullscreenChange:b})=>{const[y,w]=c(f),[C,F]=c(!1),D="string"==typeof r&&r?.split("\n")?.length>1?r.split("\n").join(" "):r;d(()=>{if(b?.(C),C)return()=>{b?.(!1)}},[C,b]);const v="string"==typeof r?r:r[0],P=u??(T=h?.arrow??{},t(o,{size:T?.fontSize??16,color:T?.color??"rgb(214, 51, 132)"}));var T;const S=m??(e=>t(n,{size:e?.fontSize??16,color:e?.color??"rgb(214, 51, 132)"}))(h?.arrow??{}),k=e("div",{style:{boxSizing:"border-box",border:C?"none":"1px solid #E4E7EC",borderRadius:C?0:"8px",overflow:"hidden",marginTop:C?0:"8px",display:"flex",flexDirection:"column",width:"100%",height:C?"100%":void 0,backgroundColor:"#FAFAFA"},children:[t("div",{style:{display:"flex",justifyContent:"flex-end",padding:"6px 10px",borderBottom:"1px solid #E4E7EC",backgroundColor:"#FFFFFF",flexShrink:0},children:t("button",{onClick:()=>{F(e=>!e)},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",borderRadius:"6px",color:"#475467",marginRight:"9px"},children:t(C?g:x,{})})}),t("div",{style:{flex:1,minHeight:0,height:"100%",overflow:"hidden"},children:t(E,{href:i,children:r,metaData:p,citationTitle:v,citationType:l,citationReason:s,isFullscreen:C})})]});return e("span",{style:{display:"inline",...h.relativeWrapper||{}},children:[t("div",{style:{display:"inline",marginTop:0,...h.citationButtonWrapper||{}},children:e("button",{type:"button",onClick:()=>w(e=>!e),style:{display:p?.webGpt?"inline":"inline-flex",alignItems:p?.webGpt?void 0:"center",gap:p?.webGpt?void 0:"3px",fontFamily:'"Inter", sans-serif',backgroundColor:"transparent",padding:0,margin:0,fontSize:"13px",borderRadius:9999,cursor:"pointer",fontWeight:p?.webGpt?600:700,color:p?.webGpt?"#6D28D9":"rgb(214, 51, 132)",border:"none",textDecoration:"none",wordBreak:"break-word",whiteSpace:"normal",...h.citationButton||{}},children:[p?.webGpt&&t(a,{size:h.arrow?.fontSize??"1em",color:h.arrow?.color??"#6D28D9",style:{display:"inline-block",width:"1em",height:"1em",marginRight:"3px",verticalAlign:"-0.125em",flexShrink:0}}),t("span",{children:D}),t("span",{style:{display:"inline-flex",alignItems:"center",marginLeft:p?.webGpt?"3px":void 0,verticalAlign:p?.webGpt?"-0.125em":void 0},children:y?P:S})]})}),y&&(C?t(_,{open:C,onClose:()=>F(!1),maxWidth:!1,BackdropProps:{sx:{backgroundColor:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(4px)"}},PaperProps:{sx:{backgroundColor:"#FAFAFA",borderRadius:"16px",height:I,m:0,maxHeight:I,maxWidth:"95vw",overflow:"hidden",width:"95vw"}},children:k}):k)]})};export{A as default};
1
+ import{jsxs as e,jsx as t}from"react/jsx-runtime";import{Dialog as o}from"@mui/material";import{Globe as i,ChevronUp as n,ChevronDown as r}from"lucide-react";import{useState as a,useEffect as l,useMemo as d,useCallback as s}from"react";import{DefaultFullScreenCloseIcon as p,DefaultFullScreenIcon as c}from"../../assests/svg/PdfViewerIcons.js";import{useOptionalCompareContext as g}from"./CompareContext.js";import h from"./CitationRendererInner.js";const x="90vh",m={border:"1px solid #D0D5DD",borderRadius:"6px",background:"#FFFFFF",color:"#344054",cursor:"pointer",fontSize:"12px",fontWeight:600,padding:"3px 8px"},f=({href:f,children:u,citationType:b,citationReason:y,metaData:C,chevronUpComponent:v=null,chevronDownComponent:w=null,customStyle:F={},defaultState:D=!1,onFullscreenChange:k,onDemandCitationContext:S})=>{const z=g(),R=z?.onDemandCitationConfig,A=z?.getOnDemandCitationCacheEntry,j=z?.fetchOnDemandCitationContext,B=z?.onDemandCitationCacheVersion,[G,W]=a(D),[E,I]=a(!1),P="string"==typeof u&&u?.split("\n")?.length>1?u.split("\n").join(" "):u,T="string"==typeof u?u:u[0];l(()=>{if(k?.(E),E)return()=>{k?.(!1)}},[E,k]);const O=d(()=>S&&A?A(S):void 0,[A,B,S]),H=!!R?.enabled&&!!S,L="success"===O?.status&&O.data&&"object"==typeof O.data&&Object.keys(O.data).length>0,U=d(()=>({...C,citations:H?L?O?.data:{}:C?.citations}),[L,H,C,O?.data]),V=H&&(!O||"loading"===O.status)&&!L,q=H&&"error"===O?.status&&!L,J=H&&"success"===O?.status&&!L,K=!H||L,M=s(()=>{R?.enabled&&S&&j&&("loading"===O?.status||"success"===O?.status&&L||j(S).catch(e=>{R.debug&&console.error("[CognitiveCompare:onDemandCitations] citation fetch failed",e)}))},[j,L,O?.status,R,S]),N=v??(Q=F?.arrow??{},t(n,{size:Q?.fontSize??16,color:Q?.color??"rgb(214, 51, 132)"}));var Q;const X=w??(e=>t(r,{size:e?.fontSize??16,color:e?.color??"rgb(214, 51, 132)"}))(F?.arrow??{}),Y=e=>t("button",{type:"button",onClick:e=>{e.stopPropagation(),M()},style:{...m,...e},children:"Retry"}),Z=e("div",{style:{boxSizing:"border-box",border:E?"none":"1px solid #E4E7EC",borderRadius:E?0:"8px",overflow:"hidden",marginTop:E?0:"8px",display:"flex",flexDirection:"column",width:"100%",height:E?"100%":void 0,backgroundColor:"#FAFAFA"},children:[t("div",{style:{display:"flex",justifyContent:"flex-end",padding:"6px 10px",borderBottom:"1px solid #E4E7EC",backgroundColor:"#FFFFFF",flexShrink:0},children:t("button",{onClick:()=>{I(e=>!e)},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",borderRadius:"6px",color:"#475467",marginRight:"9px"},children:t(E?p:c,{})})}),e("div",{style:{flex:1,minHeight:0,height:"100%",overflow:"hidden"},children:[V&&t("div",{style:{padding:"12px",fontSize:"13px",color:"#475467"},children:"Loading citation details..."}),q&&e("div",{style:{padding:"12px",fontSize:"13px",color:"#B42318",display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[t("span",{children:"Unable to load citation details. Please try again later."}),Y({border:"1px solid #FDA29B",color:"#B42318"})]}),J&&e("div",{style:{padding:"12px",fontSize:"13px",color:"#475467",display:"flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[t("span",{children:"Citation details are not available for this source."}),Y()]}),K&&t(h,{href:f,children:u,metaData:U,citationTitle:T,citationType:b,citationReason:y,isFullscreen:E})]})]});return e("span",{style:{display:"inline",...F.relativeWrapper||{}},children:[t("div",{style:{display:"inline",marginTop:0,...F.citationButtonWrapper||{}},children:e("button",{type:"button",onClick:()=>{W(e=>{const t=!e;return t&&M(),t})},style:{display:C?.webGpt?"inline":"inline-flex",alignItems:C?.webGpt?void 0:"center",gap:C?.webGpt?void 0:"3px",fontFamily:'"Inter", sans-serif',backgroundColor:"transparent",padding:0,margin:0,fontSize:"13px",borderRadius:9999,cursor:"pointer",fontWeight:C?.webGpt?600:700,color:C?.webGpt?"#6D28D9":"rgb(214, 51, 132)",border:"none",textDecoration:"none",wordBreak:"break-word",whiteSpace:"normal",...F.citationButton||{}},children:[C?.webGpt&&t(i,{size:F.arrow?.fontSize??"1em",color:F.arrow?.color??"#6D28D9",style:{display:"inline-block",width:"1em",height:"1em",marginRight:"3px",verticalAlign:"-0.125em",flexShrink:0}}),t("span",{children:P}),t("span",{style:{display:"inline-flex",alignItems:"center",marginLeft:C?.webGpt?"3px":void 0,verticalAlign:C?.webGpt?"-0.125em":void 0},children:G?N:X})]})}),G&&(E?t(o,{open:E,onClose:()=>{I(!1),k?.(!1)},maxWidth:!1,BackdropProps:{sx:{backgroundColor:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(4px)"}},PaperProps:{sx:{backgroundColor:"#FAFAFA",borderRadius:"16px",height:x,m:0,maxHeight:x,maxWidth:"95vw",overflow:"hidden",width:"95vw"}},children:Z}):Z)]})};export{f as default};
2
2
  //# sourceMappingURL=CitationAnchor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CitationAnchor.js","sources":["../../../src/features/CognitiveCompare/CitationAnchor.tsx"],"sourcesContent":["// import PdfViewer from \"@e-llm-studio/citation/PdfViewer\";\nimport DOMPurify from \"dompurify\";\nimport { ChevronDown, ChevronUp, ExternalLink, Globe, Maximize2, X } from \"lucide-react\";\nimport React, {\n CSSProperties,\n useState,\n useEffect,\n useMemo,\n useRef,\n} from \"react\";\nimport ResizableSplitPane from \"./ResizableSplitPane\";\nimport PdfViewer from \"../PdfViewer/PdfViewer\";\nimport { DefaultFullScreenIcon, DefaultFullScreenCloseIcon } from \"../../assests/svg/PdfViewerIcons\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport { Box, Dialog } from '@mui/material';\nimport { SHARED_MARKDOWN_STYLES } from \"./CognitiveCompare\";\nimport { useCompareContext } from \"./CompareContext\";\nimport { processGuidelinesMarkdown } from \"./Guidelines/utils/processGuidelinesMarkdown\";\nimport GptWebCitation from \"../GptWebCitation/GptWebCitation\";\nimport { CitationType, GptWebCitationStatus, IWebCitationApiResponse } from \"../GptWebCitation/types\";\nimport { GptWebCitationConfig } from \"./CognitiveCompareTypes\";\n\ninterface CitationAnchorProps {\n href: string;\n children: any;\n citationType?: string;\n citationReason?: string;\n chevronUpComponent?: React.ReactNode;\n chevronDownComponent?: React.ReactNode;\n customStyle?: {\n citationButtonWrapper?: CSSProperties;\n arrow?: CSSProperties;\n citationButton?: CSSProperties;\n expandableContent?: CSSProperties;\n bookHeader?: CSSProperties;\n relative?: CSSProperties;\n pageColor?: CSSProperties;\n highlightedText?: CSSProperties;\n expandedWrapper?: CSSProperties;\n expandableContainer?: CSSProperties;\n bookBodyContent?: CSSProperties;\n customScrollbarClass?: CSSProperties;\n relativeWrapper?: CSSProperties;\n };\n defaultState?: boolean;\n metaData?: any;\n onFullscreenChange?: (isFullscreen: boolean) => void;\n}\ninterface CitationRendererInnerProps {\n href: string;\n children: any;\n metaData: any;\n citationTitle: string;\n citationType?: string;\n citationReason?: string;\n isFullscreen: boolean\n}\n\nconst getFirstGptCitation = (webGptMeta: any) =>\n (webGptMeta?.extraMetaData || webGptMeta)?.aiReasoningCitation?.gpt_citation?.[0] || null;\n\nconst DEFAULT_GPT_WEB_CITATION_CONFIG: GptWebCitationConfig = {\n endpoint: \"https://dev-proposals-ai.techo.camp/utility/ca-workflow-composer-agent/get_citation\",\n userEmail: \"sai.siddhartha@techolution.com\",\n userId: \"672e32f7a0e8fe2e8e50bcba\",\n userName: \"TNV Sai Siddhartha\",\n};\n\nconst CITATION_FULLSCREEN_DIALOG_HEIGHT = \"90vh\";\nconst CITATION_FULLSCREEN_GPT_BODY_HEIGHT = `calc(${CITATION_FULLSCREEN_DIALOG_HEIGHT} - 120px)`;\n\nconst resolveGptWebCitationConfig = (\n gptWebCitationConfig?: GptWebCitationConfig,\n): GptWebCitationConfig => ({\n endpoint: gptWebCitationConfig?.endpoint || DEFAULT_GPT_WEB_CITATION_CONFIG.endpoint,\n userEmail: gptWebCitationConfig?.userEmail || DEFAULT_GPT_WEB_CITATION_CONFIG.userEmail,\n userId: gptWebCitationConfig?.userId || DEFAULT_GPT_WEB_CITATION_CONFIG.userId,\n userName: gptWebCitationConfig?.userName || DEFAULT_GPT_WEB_CITATION_CONFIG.userName,\n headers: gptWebCitationConfig?.headers,\n});\n\nconst createCitationUuid = () => {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (char) => {\n const random = Math.floor(Math.random() * 16);\n const value = char === \"x\" ? random : (random % 4) + 8;\n return value.toString(16);\n });\n};\n\nconst getStoredPayloadCitationId = (webGptMeta: any) =>\n webGptMeta?.payloadCitationId ||\n webGptMeta?.extraMetaData?.payloadCitationId ||\n \"\";\n\nconst attachPayloadCitationId = (webGptMeta: any, payloadCitationId: string) => {\n if (!webGptMeta || typeof webGptMeta !== \"object\") return;\n\n webGptMeta.payloadCitationId = payloadCitationId;\n\n if (webGptMeta.extraMetaData && typeof webGptMeta.extraMetaData === \"object\") {\n webGptMeta.extraMetaData.payloadCitationId = payloadCitationId;\n }\n};\n\nconst getOrCreatePayloadCitationId = (webGptMeta: any, generatedCitationId?: string) => {\n const payloadCitationId =\n getStoredPayloadCitationId(webGptMeta) ||\n generatedCitationId ||\n createCitationUuid();\n\n attachPayloadCitationId(webGptMeta, payloadCitationId);\n return payloadCitationId;\n};\n\nconst buildGptWebCitationPayload = (\n webGptMeta: any,\n gptWebCitationConfig?: GptWebCitationConfig,\n generatedCitationId?: string,\n) => {\n const gptCitation = getFirstGptCitation(webGptMeta);\n const customMetaData = gptCitation?.customMetaData || {};\n const citationValue = customMetaData?.value || {};\n const webSearchAnswer = webGptMeta?.webSearchAnswer || {};\n const extraMetaData = webGptMeta?.extraMetaData || webGptMeta || {};\n\n return {\n userEmail:\n webGptMeta?.userEmail ||\n webSearchAnswer?.userEmail ||\n gptWebCitationConfig?.userEmail ||\n \"\",\n userId:\n webGptMeta?.userId ||\n webSearchAnswer?.userId ||\n gptWebCitationConfig?.userId ||\n \"\",\n userName:\n webGptMeta?.userName ||\n webSearchAnswer?.userName ||\n gptWebCitationConfig?.userName ||\n \"\",\n citationId:\n getOrCreatePayloadCitationId(webGptMeta, generatedCitationId),\n citationUrl: citationValue?.citationUrl || webSearchAnswer?.citationUrl || \"\",\n content: extraMetaData?.Reasoning || webSearchAnswer?.enhanced_content || \"\",\n citationType: citationValue?.citationType || \"web\",\n citatioNumber:\n customMetaData?.citation_number ??\n gptCitation?.citation_number ??\n Number(webGptMeta?.reasoningId || 0),\n };\n};\n\nconst GptWebCitationPanel = ({\n metaData,\n isFullscreen = false,\n}: {\n metaData: any;\n isFullscreen?: boolean;\n}) => {\n const { gptWebCitationConfig } = useCompareContext();\n const resolvedGptWebCitationConfig = useMemo(\n () => resolveGptWebCitationConfig(gptWebCitationConfig),\n [gptWebCitationConfig],\n );\n const webGptMeta = metaData?.webGpt;\n const generatedCitationIdRef = useRef<string | null>(null);\n if (!generatedCitationIdRef.current) {\n generatedCitationIdRef.current = createCitationUuid();\n }\n\n const payload = useMemo(\n () => buildGptWebCitationPayload(\n webGptMeta,\n resolvedGptWebCitationConfig,\n generatedCitationIdRef.current || undefined,\n ),\n [webGptMeta, resolvedGptWebCitationConfig],\n );\n const firstGptCitation = useMemo(() => getFirstGptCitation(webGptMeta), [webGptMeta]);\n const citationValue = firstGptCitation?.customMetaData?.value || {};\n const extraMetaData = webGptMeta?.extraMetaData || webGptMeta || {};\n const [webCitationData, setWebCitationData] = useState<IWebCitationApiResponse | undefined>();\n const [webCitationStatus, setWebCitationStatus] = useState<GptWebCitationStatus>(\"pending\");\n const [showWebCitation, setShowWebCitation] = useState(true);\n\n useEffect(() => {\n let isMounted = true;\n\n const fetchGptWebCitation = async () => {\n if (!resolvedGptWebCitationConfig.endpoint || !payload?.citationUrl || !payload?.content) {\n setWebCitationStatus(\"error\");\n return;\n }\n\n setWebCitationStatus(\"pending\");\n\n try {\n const response = await fetch(resolvedGptWebCitationConfig.endpoint, {\n method: \"POST\",\n headers: {\n \"actor-id\": payload.userEmail,\n \"Accept\": \"application/json, text/plain, */*\",\n \"Content-Type\": \"application/json\",\n ...(resolvedGptWebCitationConfig.headers || {}),\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch GPT web citation (${response.status})`);\n }\n\n const rawData = await response.json();\n const data =\n rawData?.responseData ||\n rawData?.result ||\n rawData?.data ||\n rawData;\n if (!isMounted) return;\n\n setWebCitationData(data);\n setWebCitationStatus(\"success\");\n } catch (error) {\n if (!isMounted) return;\n console.error(\"Failed to load GPT web citation\", error);\n setWebCitationStatus(\"error\");\n }\n };\n\n fetchGptWebCitation();\n\n return () => {\n isMounted = false;\n };\n }, [payload, resolvedGptWebCitationConfig]);\n\n const gptCitation = useMemo(\n () => ({\n item: {\n confidence_score: Number(extraMetaData?.Confidence_score || 0),\n text: citationValue?.paraphrase || \"Web citation reasoning\",\n dataSource: citationValue?.text || extraMetaData?.Reasoning || \"\",\n paraphrase: citationValue?.paraphrase || \"\",\n },\n headerTitle: \"GPT Web Citation\",\n index: Number(payload?.citatioNumber || 1) - 1,\n iconsConfig: {\n ChevronDownIcon: ChevronDown,\n ChevronUpIcon: ChevronUp,\n MaximizeIcon: Maximize2,\n CloseIcon: X,\n },\n }),\n [citationValue, payload?.citatioNumber, extraMetaData],\n );\n\n const resolvedGptCitation = useMemo(\n () => ({\n ...gptCitation,\n ...(isFullscreen ? { bodyHeight: CITATION_FULLSCREEN_GPT_BODY_HEIGHT } : {}),\n }),\n [gptCitation, isFullscreen],\n );\n\n return (\n <GptWebCitation\n gptCitation={resolvedGptCitation}\n defaultCitationUrl={payload?.citationUrl || \"\"}\n citationType={CitationType.GPT_WEB}\n webCitationData={webCitationData}\n webCitationStatus={webCitationStatus}\n showWebCitation={showWebCitation}\n onToggleCitationView={() => setShowWebCitation((current) => !current)}\n iconsConfig={{\n MaximizeIcon: Maximize2,\n ExternalLinkIcon: ExternalLink,\n }}\n isFixedHeight\n />\n );\n};\n\nconst CitationRendererInner: React.FC<CitationRendererInnerProps> = ({\n href,\n metaData,\n citationTitle,\n citationType,\n citationReason,\n isFullscreen\n}) => {\n const { guidelinesData } = useCompareContext();\n const pdfCitationTypes = [\"contract\", \"clause\"];\n\n const getCitationUrl = (url: string) => {\n const prefixedCitationMatch = url.match(/^(?:pdf_citation|deviation_summary)\\$(\\d+)/);\n if (prefixedCitationMatch) {\n try {\n const queryStartIndex = url.indexOf(\"?\");\n const search = queryStartIndex >= 0 ? url.slice(queryStartIndex) : \"\";\n return {\n citationNumber: prefixedCitationMatch[1],\n parsedUrl: new URL(search || \"./\", window.location.origin),\n };\n } catch {\n return {\n citationNumber: prefixedCitationMatch[1],\n parsedUrl: null,\n };\n }\n }\n\n try {\n const parsedUrl = new URL(url, window.location.origin);\n const citationNumber =\n parsedUrl.searchParams.get(\"citationNumber\") ||\n parsedUrl.searchParams.get(\"citation_number\");\n return {citationNumber, parsedUrl};\n } catch {\n return {citationNumber: null, parsedUrl: null};\n }\n };\n\n const getCitationDetailsFromHref = (url: string): { citationNumber: string | null; phraseToHighlight: string | null; citationTypeFromHref: string | null } => {\n try {\n const { citationNumber, parsedUrl } = getCitationUrl(url);\n const phraseToHighlight = parsedUrl?.searchParams.get(\"phrase_to_highlight\") || null;\n const citationTypeFromHref = parsedUrl?.searchParams.get(\"citation_type\") || null;\n return {citationNumber, phraseToHighlight, citationTypeFromHref};\n } catch {\n return {citationNumber: null, phraseToHighlight: null, citationTypeFromHref: null};\n }\n };\n\n const {citationNumber, phraseToHighlight, citationTypeFromHref} = getCitationDetailsFromHref(href);\n const resolvedCitationType = citationType || citationTypeFromHref || undefined;\n const normalizedCitationType =\n resolvedCitationType === \"il_rulebook_citation\" ? \"rulebook_citation\" : resolvedCitationType;\n const citationGroup = citationNumber ? (metaData?.citations?.[citationNumber] || {}) : {};\n const documents = metaData?.docData?.documents || {};\n const inputIndexMap = metaData?.docData?.input_index_map || {};\n const hasRegularCitationData =\n Object.keys(metaData?.citations || {}).length > 0 ||\n Object.keys(metaData?.docData || {}).length > 0;\n\n const leftUuid = inputIndexMap?.[\"0\"];\n const rightUuid = inputIndexMap?.[\"1\"];\n\n const leftDocument = leftUuid ? documents[leftUuid] : null;\n const rightDocument = rightUuid ? documents[rightUuid] : null;\n const leftCitation = leftUuid ? citationGroup[leftUuid] : null;\n const rightCitation = rightUuid ? citationGroup[rightUuid] : null;\n\n const leftComponent = useMemo(() => {\n if (!leftCitation || !leftDocument) return null;\n return (\n <PdfViewer\n defaultScale={'PageWidth'}\n showFullScreenAction={false}\n showHighlightsAction={false}\n pdfName={leftDocument?.title}\n pdfUrl={leftDocument?.signed_url}\n highlightText={[leftCitation?.highlighted_text ?? '']}\n highlightPages={{ 1: leftCitation?.custom_metadata?.pdf_start_page_number }}\n jumpToPageValue={1}\n highlightCordinatePages={[]}\n useCoordinates={false}\n useRange={true}\n rangeOfPages={[leftCitation?.custom_metadata?.pdf_start_page_number, leftCitation?.custom_metadata?.pdf_end_page_number]}\n />\n );\n }, [\n leftDocument?.title,\n leftDocument?.signed_url,\n leftCitation?.highlighted_text,\n leftCitation?.custom_metadata?.pdf_start_page_number,\n leftCitation?.custom_metadata?.pdf_end_page_number\n ]);\n\n const rightComponent = useMemo(() => {\n if (!rightCitation || !rightDocument) return null;\n return (\n <PdfViewer\n defaultScale={'PageWidth'}\n showFullScreenAction={false}\n showHighlightsAction={false}\n pdfName={rightDocument?.title}\n pdfUrl={rightDocument?.signed_url}\n jumpToPageValue={1}\n highlightText={[rightCitation?.highlighted_text ?? '']}\n highlightPages={{ 1: rightCitation?.custom_metadata?.pdf_start_page_number }}\n highlightCordinatePages={[]}\n useCoordinates={false}\n useRange={true}\n rangeOfPages={[rightCitation?.custom_metadata?.pdf_start_page_number, rightCitation?.custom_metadata?.pdf_end_page_number]}\n />\n );\n }, [\n rightDocument?.title,\n rightDocument?.signed_url,\n rightCitation?.highlighted_text,\n rightCitation?.custom_metadata?.pdf_start_page_number,\n rightCitation?.custom_metadata?.pdf_end_page_number\n ]);\n\n const isDualCitationType = normalizedCitationType === \"dual_citation\";\n const isDualWebGptCitation = isDualCitationType && !!metaData?.webGpt;\n\n const splitPaneComponent = useMemo(() => {\n if (!leftComponent) return null;\n\n const rightPane =\n isDualWebGptCitation ? (\n <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />\n ) : normalizedCitationType === \"rulebook_citation\" ? (\n <>\n <Box sx={{\n padding: '0px 20px',\n backgroundColor: '#FFFFFF',\n borderRadius: '8px',\n ...SHARED_MARKDOWN_STYLES,\n overflow: 'auto'\n }}>\n <ReactMarkdown rehypePlugins={[rehypeRaw as any]}>\n {processGuidelinesMarkdown({\n guidelinesData, targetHighlights: [phraseToHighlight!], labelColor: \"#FEF08A\"})}\n </ReactMarkdown>\n </Box>\n </>\n ) : (\n rightComponent\n );\n\n if (!rightPane) return leftComponent;\n\n return (\n <ResizableSplitPane\n leftComponent={leftComponent}\n rightComponent={rightPane}\n isFullscreen={isFullscreen}\n />\n );\n}, [leftComponent, rightComponent, normalizedCitationType, isDualWebGptCitation, metaData, isFullscreen, guidelinesData, phraseToHighlight]);\n\n if (metaData?.webGpt && !hasRegularCitationData) {\n return <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />;\n }\n\n if (!citationNumber) return null;\n\n if (normalizedCitationType === \"rulebook_citation\") {\n if (leftCitation) {\n return (\n <div style={{ height: \"100%\", display: \"flex\", flexDirection: \"column\" }}>\n {splitPaneComponent}\n </div>\n );\n }\n\n return (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#344054\", lineHeight: 1.5 }}>\n {citationReason || \"Rulebook citation selected.\"}\n </div>\n );\n }\n\n if (isDualCitationType) {\n if (leftCitation || rightCitation) {\n return (\n <div style={{ height: \"100%\", display: \"flex\", flexDirection: \"column\" }}>\n {splitPaneComponent}\n </div>\n );\n }\n\n if (metaData?.webGpt) {\n return <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />;\n }\n\n return <div>Missing PDF Citation. Please try again later</div>;\n }\n\n if (pdfCitationTypes.includes(citationTitle)) {\n if (leftCitation || rightCitation) {\n return (\n <div style={{ height: \"100%\", display: \"flex\", flexDirection: \"column\" }}>\n {splitPaneComponent}\n </div>\n );\n }\n\n return <div>Missing PDF Citation. Please try again later</div>;\n }\n\n return <div>No Citation Found. Please try again later</div>;\n};\n\n\nconst CitationAnchor: React.FC<CitationAnchorProps> = ({\n href,\n children,\n citationType,\n citationReason,\n metaData,\n chevronUpComponent = null,\n chevronDownComponent = null,\n customStyle = {},\n defaultState = false,\n onFullscreenChange,\n}) => {\n const ChevronUpComponentDefault = (arrow: CSSProperties) => {\n return (\n <ChevronUp\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n };\n\n const ChevronDownComponentDefault = (arrow: CSSProperties) => {\n return (\n <ChevronDown\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n };\n const [isExpanded, setIsExpanded] = useState(defaultState);\n const [isFullscreen, setIsFullscreen] = useState(false);\n const citationDisplayTitle =\n typeof children === \"string\" && children?.split(\"\\n\")?.length > 1\n ? children.split(\"\\n\").join(\" \")\n : children;\n\n useEffect(() => {\n onFullscreenChange?.(isFullscreen);\n\n if (!isFullscreen) return;\n\n return () => {\n onFullscreenChange?.(false);\n };\n }, [isFullscreen, onFullscreenChange]);\n \n const citationTitle = typeof children === \"string\" ? children : children[0]\n\n const toggleCitation = () => setIsExpanded((prev) => !prev);\n const chevronUpComponentResolved =\n chevronUpComponent ??\n ChevronUpComponentDefault(customStyle?.arrow ?? {});\n const chevronDownComponentResolved =\n chevronDownComponent ??\n ChevronDownComponentDefault(customStyle?.arrow ?? {});\n\n const pdfCitationTypes = [\"contract\", \"clause\"];\n \nconst handleFullscreen = () => {\n setIsFullscreen((prev) => !prev);\n};\n // const jumpToPageRef = useRef<number>(item.pdf_highlight_details.pdf_page_number);\n // const highlightPagesIndexArray = {1: citationMetaData.pdf_highlight_details.pdf_page_number}\n // // const highlightTextArray = citationMetaData.pdf_highlight_details.pdf_highlight_text?.split('\\n')\n // const highlightTextArray = (() => {\n // const text = [citationMetaData.pdf_highlight_details.pdf_highlight_text ?? ''];\n // // console.log('textchecking old', text, processPdfHighlightText_Old(text[0]))\n // // console.log('textchecking new', text, processPdfHighlightText(\"payment in full for undisputed invoices shall be due within\\n**fourty-five (45) days** from invoice date unless stated otherwise in the respective SOW\"))\n // return text\n // })();\n\n const citationPanel = (\n <div\n style={{\n boxSizing: \"border-box\",\n border: isFullscreen ? \"none\" : \"1px solid #E4E7EC\",\n borderRadius: isFullscreen ? 0 : \"8px\",\n overflow: \"hidden\",\n marginTop: isFullscreen ? 0 : \"8px\",\n display: \"flex\",\n flexDirection: \"column\",\n width: \"100%\",\n height: isFullscreen ? \"100%\" : undefined,\n backgroundColor: \"#FAFAFA\",\n }}\n >\n <div style={{\n display: \"flex\",\n justifyContent: \"flex-end\",\n padding: \"6px 10px\",\n borderBottom: \"1px solid #E4E7EC\",\n backgroundColor: \"#FFFFFF\",\n flexShrink: 0,\n }}>\n <button onClick={handleFullscreen}\n style={{ background: \"none\", border: \"none\", cursor: \"pointer\", padding: \"4px\", borderRadius: \"6px\", color: \"#475467\", marginRight: \"9px\" }}>\n {isFullscreen ? <DefaultFullScreenCloseIcon /> : <DefaultFullScreenIcon />}\n </button>\n </div>\n <div style={{ flex: 1, minHeight: 0, height: \"100%\", overflow: \"hidden\" }}>\n <CitationRendererInner\n href={href}\n children={children}\n metaData={metaData}\n citationTitle={citationTitle}\n citationType={citationType}\n citationReason={citationReason}\n isFullscreen={isFullscreen}\n />\n </div>\n </div>\n );\n\n return (\n <span\n style={{\n display: \"inline\",\n ...(customStyle.relativeWrapper || {}),\n }}\n >\n <div\n style={{\n display: \"inline\",\n marginTop: 0,\n ...(customStyle.citationButtonWrapper || {}),\n }}\n >\n <button\n type=\"button\"\n onClick={toggleCitation}\n style={{\n display: metaData?.webGpt ? \"inline\" : \"inline-flex\",\n alignItems: metaData?.webGpt ? undefined : \"center\",\n gap: metaData?.webGpt ? undefined : \"3px\",\n fontFamily: '\"Inter\", sans-serif',\n backgroundColor: \"transparent\",\n padding: 0,\n margin: 0,\n fontSize: \"13px\",\n borderRadius: 9999,\n cursor: \"pointer\",\n fontWeight: (metaData?.webGpt) ? 600 : 700,\n color: (metaData?.webGpt) ? \"#6D28D9\" : \"rgb(214, 51, 132)\",\n border: \"none\",\n textDecoration: \"none\",\n wordBreak: \"break-word\",\n whiteSpace: \"normal\",\n ...(customStyle.citationButton || {}),\n }}\n >\n {metaData?.webGpt && (\n <Globe\n size={customStyle.arrow?.fontSize ?? \"1em\"}\n color={customStyle.arrow?.color ?? \"#6D28D9\"}\n style={{\n display: \"inline-block\",\n width: \"1em\",\n height: \"1em\",\n marginRight: \"3px\",\n verticalAlign: \"-0.125em\",\n flexShrink: 0,\n }}\n />\n )}\n <span>{citationDisplayTitle}</span>\n\n <span\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n marginLeft: metaData?.webGpt ? \"3px\" : undefined,\n verticalAlign: metaData?.webGpt ? \"-0.125em\" : undefined,\n }}\n >\n {isExpanded\n ? chevronUpComponentResolved\n : chevronDownComponentResolved}\n </span>\n {/* <span>\n <ChevronDownComponentDefault />\n </span> */}\n </button>\n </div>\n {isExpanded && (\n isFullscreen ? (\n <Dialog\n open={isFullscreen}\n onClose={() => setIsFullscreen(false)}\n maxWidth={false}\n BackdropProps={{\n sx: {\n backgroundColor: \"rgba(0, 0, 0, 0.6)\",\n backdropFilter: \"blur(4px)\",\n },\n }}\n PaperProps={{\n sx: {\n backgroundColor: \"#FAFAFA\",\n borderRadius: \"16px\",\n height: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n m: 0,\n maxHeight: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n maxWidth: \"95vw\",\n overflow: \"hidden\",\n width: \"95vw\",\n },\n }}\n >\n {citationPanel}\n </Dialog>\n ) : (\n citationPanel\n )\n )}\n </span>\n );\n};\n\nexport default CitationAnchor;\n"],"names":["getFirstGptCitation","webGptMeta","extraMetaData","aiReasoningCitation","gpt_citation","DEFAULT_GPT_WEB_CITATION_CONFIG","CITATION_FULLSCREEN_DIALOG_HEIGHT","CITATION_FULLSCREEN_GPT_BODY_HEIGHT","createCitationUuid","globalThis","crypto","randomUUID","replace","char","random","Math","floor","toString","getOrCreatePayloadCitationId","generatedCitationId","payloadCitationId","getStoredPayloadCitationId","attachPayloadCitationId","GptWebCitationPanel","metaData","isFullscreen","gptWebCitationConfig","useCompareContext","resolvedGptWebCitationConfig","useMemo","endpoint","userEmail","userId","userName","headers","resolveGptWebCitationConfig","webGpt","generatedCitationIdRef","useRef","current","payload","gptCitation","customMetaData","citationValue","value","webSearchAnswer","citationId","citationUrl","content","Reasoning","enhanced_content","citationType","citatioNumber","citation_number","Number","reasoningId","buildGptWebCitationPayload","firstGptCitation","webCitationData","setWebCitationData","useState","webCitationStatus","setWebCitationStatus","showWebCitation","setShowWebCitation","useEffect","isMounted","async","response","fetch","method","Accept","body","JSON","stringify","ok","Error","status","rawData","json","responseData","result","data","error","console","fetchGptWebCitation","item","confidence_score","Confidence_score","text","paraphrase","dataSource","headerTitle","index","iconsConfig","ChevronDownIcon","ChevronDown","ChevronUpIcon","ChevronUp","MaximizeIcon","Maximize2","CloseIcon","X","resolvedGptCitation","bodyHeight","jsx","GptWebCitation","defaultCitationUrl","CitationType","GPT_WEB","onToggleCitationView","ExternalLinkIcon","ExternalLink","isFixedHeight","CitationRendererInner","href","citationTitle","citationReason","guidelinesData","citationNumber","phraseToHighlight","citationTypeFromHref","url","parsedUrl","prefixedCitationMatch","match","queryStartIndex","indexOf","search","slice","URL","window","location","origin","searchParams","get","getCitationUrl","getCitationDetailsFromHref","resolvedCitationType","normalizedCitationType","citationGroup","citations","documents","docData","inputIndexMap","input_index_map","hasRegularCitationData","Object","keys","length","leftUuid","rightUuid","leftDocument","rightDocument","leftCitation","rightCitation","leftComponent","PdfViewer","defaultScale","showFullScreenAction","showHighlightsAction","pdfName","title","pdfUrl","signed_url","highlightText","highlighted_text","highlightPages","custom_metadata","pdf_start_page_number","jumpToPageValue","highlightCordinatePages","useCoordinates","useRange","rangeOfPages","pdf_end_page_number","rightComponent","isDualCitationType","isDualWebGptCitation","splitPaneComponent","rightPane","Fragment","children","Box","sx","padding","backgroundColor","borderRadius","SHARED_MARKDOWN_STYLES","overflow","ReactMarkdown","rehypePlugins","rehypeRaw","processGuidelinesMarkdown","targetHighlights","labelColor","ResizableSplitPane","style","height","display","flexDirection","fontSize","color","lineHeight","includes","CitationAnchor","chevronUpComponent","chevronDownComponent","customStyle","defaultState","onFullscreenChange","isExpanded","setIsExpanded","setIsFullscreen","citationDisplayTitle","split","join","chevronUpComponentResolved","arrow","size","chevronDownComponentResolved","ChevronDownComponentDefault","citationPanel","jsxs","boxSizing","border","marginTop","width","justifyContent","borderBottom","flexShrink","onClick","prev","background","cursor","marginRight","DefaultFullScreenCloseIcon","DefaultFullScreenIcon","flex","minHeight","relativeWrapper","citationButtonWrapper","type","alignItems","gap","fontFamily","margin","fontWeight","textDecoration","wordBreak","whiteSpace","citationButton","Globe","verticalAlign","marginLeft","Dialog","open","onClose","maxWidth","BackdropProps","backdropFilter","PaperProps","m","maxHeight"],"mappings":"0+BA2DA,MAAMA,EAAuBC,IACxBA,GAAYC,eAAiBD,IAAaE,qBAAqBC,eAAe,IAAM,KAEnFC,EACQ,sFADRA,EAES,iCAFTA,EAGM,2BAHNA,EAIQ,qBAGRC,EAAoC,OACpCC,EAAsC,QAAQD,aAY9CE,EAAqB,IACsB,mBAAlCC,WAAWC,QAAQC,WACnBF,WAAWC,OAAOC,aAGtB,uCAAuCC,QAAQ,QAAUC,IAC5D,MAAMC,EAASC,KAAKC,MAAsB,GAAhBD,KAAKD,UAExB,OADgB,MAATD,EAAeC,EAAUA,EAAS,EAAK,GACxCG,SAAS,MAmBxBC,EAA+B,CAACjB,EAAiBkB,KACnD,MAAMC,EAhByB,CAACnB,GAChCA,GAAYmB,mBACZnB,GAAYC,eAAekB,mBAC3B,GAcIC,CAA2BpB,IAC3BkB,GACAX,IAGG,MAjBqB,EAACP,EAAiBmB,KACzCnB,GAAoC,iBAAfA,IAE1BA,EAAWmB,kBAAoBA,EAE3BnB,EAAWC,eAAqD,iBAA7BD,EAAWC,gBAC9CD,EAAWC,cAAckB,kBAAoBA,KAUjDE,CAAwBrB,EAAYmB,GAC7BA,GA0CLG,EAAsB,EACxBC,WACAC,gBAAe,MAKT,MAAAC,qBAAEA,GAAyBC,IAC3BC,EAA+BC,EACjC,IA/F4B,CAChCH,IACwB,CACxBI,SAAUJ,GAAsBI,UAAYzB,EAC5C0B,UAAWL,GAAsBK,WAAa1B,EAC9C2B,OAAQN,GAAsBM,QAAU3B,EACxC4B,SAAUP,GAAsBO,UAAY5B,EAC5C6B,QAASR,GAAsBQ,UAwFrBC,CAA4BT,GAClC,CAACA,IAECzB,EAAauB,GAAUY,O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J,WACKmC,EACAG,SAOjBT,IACG1L,EACIgF,EAACsJ,EAAA,CACGC,KAAMvO,EACNwO,QAAS,IAAM5C,GAAgB,GAC/B6C,UAAU,EACVC,cAAe,CACX3E,GAAI,CACAE,gBAAiB,qBACjB0E,eAAgB,cAGxBC,WAAY,CACR7E,GAAI,CACAE,gBAAiB,UACjBC,aAAc,OACdW,OAAQhM,EACRgQ,EAAG,EACHC,UAAWjQ,EACX4P,SAAU,OACVrE,SAAU,SACVsC,MAAO,SAId7C,SAAAwC,IAGLA"}
1
+ {"version":3,"file":"CitationAnchor.js","sources":["../../../src/features/CognitiveCompare/CitationAnchor.tsx"],"sourcesContent":["import { Dialog } from \"@mui/material\";\nimport { ChevronDown, ChevronUp, Globe } from \"lucide-react\";\nimport React, {\n CSSProperties,\n useCallback,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport { DefaultFullScreenIcon, DefaultFullScreenCloseIcon } from \"../../assests/svg/PdfViewerIcons\";\nimport type { OnDemandCitationContext } from \"./CognitiveCompareTypes\";\nimport { useOptionalCompareContext } from \"./CompareContext\";\nimport CitationRendererInner from \"./CitationRendererInner\";\n\ninterface CitationAnchorProps {\n href: string;\n children: any;\n citationType?: string;\n citationReason?: string;\n chevronUpComponent?: React.ReactNode;\n chevronDownComponent?: React.ReactNode;\n customStyle?: {\n citationButtonWrapper?: CSSProperties;\n arrow?: CSSProperties;\n citationButton?: CSSProperties;\n expandableContent?: CSSProperties;\n bookHeader?: CSSProperties;\n relative?: CSSProperties;\n pageColor?: CSSProperties;\n highlightedText?: CSSProperties;\n expandedWrapper?: CSSProperties;\n expandableContainer?: CSSProperties;\n bookBodyContent?: CSSProperties;\n customScrollbarClass?: CSSProperties;\n relativeWrapper?: CSSProperties;\n };\n defaultState?: boolean;\n metaData?: any;\n onFullscreenChange?: (isFullscreen: boolean) => void;\n onDemandCitationContext?: OnDemandCitationContext;\n}\n\nconst CITATION_FULLSCREEN_DIALOG_HEIGHT = \"90vh\";\n\nconst retryButtonStyle: React.CSSProperties = {\n border: \"1px solid #D0D5DD\",\n borderRadius: \"6px\",\n background: \"#FFFFFF\",\n color: \"#344054\",\n cursor: \"pointer\",\n fontSize: \"12px\",\n fontWeight: 600,\n padding: \"3px 8px\",\n};\n\nconst CitationAnchor: React.FC<CitationAnchorProps> = ({\n href,\n children,\n citationType,\n citationReason,\n metaData,\n chevronUpComponent = null,\n chevronDownComponent = null,\n customStyle = {},\n defaultState = false,\n onFullscreenChange,\n onDemandCitationContext,\n}) => {\n const compareContext = useOptionalCompareContext();\n const onDemandCitationConfig = compareContext?.onDemandCitationConfig;\n const getOnDemandCitationCacheEntry = compareContext?.getOnDemandCitationCacheEntry;\n const fetchOnDemandCitationContext = compareContext?.fetchOnDemandCitationContext;\n const onDemandCitationCacheVersion = compareContext?.onDemandCitationCacheVersion;\n const [isExpanded, setIsExpanded] = useState(defaultState);\n const [isFullscreen, setIsFullscreen] = useState(false);\n\n const ChevronUpComponentDefault = (arrow: CSSProperties) => (\n <ChevronUp\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n\n const ChevronDownComponentDefault = (arrow: CSSProperties) => (\n <ChevronDown\n size={arrow?.fontSize ?? 16}\n color={arrow?.color ?? \"rgb(214, 51, 132)\"}\n />\n );\n\n const citationDisplayTitle =\n typeof children === \"string\" && children?.split(\"\\n\")?.length > 1\n ? children.split(\"\\n\").join(\" \")\n : children;\n const citationTitle = typeof children === \"string\" ? children : children[0];\n\n useEffect(() => {\n onFullscreenChange?.(isFullscreen);\n\n if (!isFullscreen) return;\n\n return () => {\n onFullscreenChange?.(false);\n };\n }, [isFullscreen, onFullscreenChange]);\n\n const onDemandCacheEntry = useMemo(\n () => onDemandCitationContext && getOnDemandCitationCacheEntry\n ? getOnDemandCitationCacheEntry(onDemandCitationContext)\n : undefined,\n [\n getOnDemandCitationCacheEntry,\n onDemandCitationCacheVersion,\n onDemandCitationContext,\n ],\n );\n const isOnDemandCitationEnabled =\n !!onDemandCitationConfig?.enabled &&\n !!onDemandCitationContext;\n const hasOnDemandCitationData =\n onDemandCacheEntry?.status === \"success\" &&\n onDemandCacheEntry.data &&\n typeof onDemandCacheEntry.data === \"object\" &&\n Object.keys(onDemandCacheEntry.data).length > 0;\n const effectiveMetaData = useMemo(\n () => ({\n ...metaData,\n citations: isOnDemandCitationEnabled\n ? (hasOnDemandCitationData ? onDemandCacheEntry?.data : {})\n : metaData?.citations,\n }),\n [\n hasOnDemandCitationData,\n isOnDemandCitationEnabled,\n metaData,\n onDemandCacheEntry?.data,\n ],\n );\n const shouldShowLoading =\n isOnDemandCitationEnabled &&\n (!onDemandCacheEntry || onDemandCacheEntry.status === \"loading\") &&\n !hasOnDemandCitationData;\n const shouldShowError =\n isOnDemandCitationEnabled &&\n onDemandCacheEntry?.status === \"error\" &&\n !hasOnDemandCitationData;\n const shouldShowMissing =\n isOnDemandCitationEnabled &&\n onDemandCacheEntry?.status === \"success\" &&\n !hasOnDemandCitationData;\n const shouldRenderCitationContent =\n !isOnDemandCitationEnabled || hasOnDemandCitationData;\n\n const requestOnDemandCitation = useCallback(() => {\n if (\n !onDemandCitationConfig?.enabled ||\n !onDemandCitationContext ||\n !fetchOnDemandCitationContext\n ) {\n return;\n }\n\n if (\n onDemandCacheEntry?.status === \"loading\" ||\n (onDemandCacheEntry?.status === \"success\" && hasOnDemandCitationData)\n ) {\n return;\n }\n\n fetchOnDemandCitationContext(onDemandCitationContext).catch((error) => {\n if (onDemandCitationConfig.debug) {\n console.error(\"[CognitiveCompare:onDemandCitations] citation fetch failed\", error);\n }\n });\n }, [\n fetchOnDemandCitationContext,\n hasOnDemandCitationData,\n onDemandCacheEntry?.status,\n onDemandCitationConfig,\n onDemandCitationContext,\n ]);\n\n const toggleCitation = () => {\n setIsExpanded((prev) => {\n const next = !prev;\n if (next) {\n requestOnDemandCitation();\n }\n return next;\n });\n };\n const chevronUpComponentResolved =\n chevronUpComponent ??\n ChevronUpComponentDefault(customStyle?.arrow ?? {});\n const chevronDownComponentResolved =\n chevronDownComponent ??\n ChevronDownComponentDefault(customStyle?.arrow ?? {});\n\n const handleFullscreen = () => {\n setIsFullscreen((prev) => !prev);\n };\n\n const renderRetryButton = (style?: React.CSSProperties) => (\n <button\n type=\"button\"\n onClick={(event) => {\n event.stopPropagation();\n requestOnDemandCitation();\n }}\n style={{ ...retryButtonStyle, ...style }}\n >\n Retry\n </button>\n );\n\n const citationPanel = (\n <div\n style={{\n boxSizing: \"border-box\",\n border: isFullscreen ? \"none\" : \"1px solid #E4E7EC\",\n borderRadius: isFullscreen ? 0 : \"8px\",\n overflow: \"hidden\",\n marginTop: isFullscreen ? 0 : \"8px\",\n display: \"flex\",\n flexDirection: \"column\",\n width: \"100%\",\n height: isFullscreen ? \"100%\" : undefined,\n backgroundColor: \"#FAFAFA\",\n }}\n >\n <div style={{\n display: \"flex\",\n justifyContent: \"flex-end\",\n padding: \"6px 10px\",\n borderBottom: \"1px solid #E4E7EC\",\n backgroundColor: \"#FFFFFF\",\n flexShrink: 0,\n }}>\n <button onClick={handleFullscreen}\n style={{ background: \"none\", border: \"none\", cursor: \"pointer\", padding: \"4px\", borderRadius: \"6px\", color: \"#475467\", marginRight: \"9px\" }}>\n {isFullscreen ? <DefaultFullScreenCloseIcon /> : <DefaultFullScreenIcon />}\n </button>\n </div>\n <div style={{ flex: 1, minHeight: 0, height: \"100%\", overflow: \"hidden\" }}>\n {shouldShowLoading && (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#475467\" }}>\n Loading citation details...\n </div>\n )}\n {shouldShowError && (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#B42318\", display: \"flex\", alignItems: \"center\", gap: \"8px\", flexWrap: \"wrap\" }}>\n <span>\n Unable to load citation details. Please try again later.\n </span>\n {renderRetryButton({\n border: \"1px solid #FDA29B\",\n color: \"#B42318\",\n })}\n </div>\n )}\n {shouldShowMissing && (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#475467\", display: \"flex\", alignItems: \"center\", gap: \"8px\", flexWrap: \"wrap\" }}>\n <span>Citation details are not available for this source.</span>\n {renderRetryButton()}\n </div>\n )}\n {shouldRenderCitationContent && (\n <CitationRendererInner\n href={href}\n children={children}\n metaData={effectiveMetaData}\n citationTitle={citationTitle}\n citationType={citationType}\n citationReason={citationReason}\n isFullscreen={isFullscreen}\n />\n )}\n </div>\n </div>\n );\n\n return (\n <span\n style={{\n display: \"inline\",\n ...(customStyle.relativeWrapper || {}),\n }}\n >\n <div\n style={{\n display: \"inline\",\n marginTop: 0,\n ...(customStyle.citationButtonWrapper || {}),\n }}\n >\n <button\n type=\"button\"\n onClick={toggleCitation}\n style={{\n display: metaData?.webGpt ? \"inline\" : \"inline-flex\",\n alignItems: metaData?.webGpt ? undefined : \"center\",\n gap: metaData?.webGpt ? undefined : \"3px\",\n fontFamily: '\"Inter\", sans-serif',\n backgroundColor: \"transparent\",\n padding: 0,\n margin: 0,\n fontSize: \"13px\",\n borderRadius: 9999,\n cursor: \"pointer\",\n fontWeight: (metaData?.webGpt) ? 600 : 700,\n color: (metaData?.webGpt) ? \"#6D28D9\" : \"rgb(214, 51, 132)\",\n border: \"none\",\n textDecoration: \"none\",\n wordBreak: \"break-word\",\n whiteSpace: \"normal\",\n ...(customStyle.citationButton || {}),\n }}\n >\n {metaData?.webGpt && (\n <Globe\n size={customStyle.arrow?.fontSize ?? \"1em\"}\n color={customStyle.arrow?.color ?? \"#6D28D9\"}\n style={{\n display: \"inline-block\",\n width: \"1em\",\n height: \"1em\",\n marginRight: \"3px\",\n verticalAlign: \"-0.125em\",\n flexShrink: 0,\n }}\n />\n )}\n <span>{citationDisplayTitle}</span>\n\n <span\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n marginLeft: metaData?.webGpt ? \"3px\" : undefined,\n verticalAlign: metaData?.webGpt ? \"-0.125em\" : undefined,\n }}\n >\n {isExpanded\n ? chevronUpComponentResolved\n : chevronDownComponentResolved}\n </span>\n </button>\n </div>\n {isExpanded && (\n isFullscreen ? (\n <Dialog\n open={isFullscreen}\n onClose={() => {\n setIsFullscreen(false);\n onFullscreenChange?.(false);\n }}\n maxWidth={false}\n BackdropProps={{\n sx: {\n backgroundColor: \"rgba(0, 0, 0, 0.6)\",\n backdropFilter: \"blur(4px)\",\n },\n }}\n PaperProps={{\n sx: {\n backgroundColor: \"#FAFAFA\",\n borderRadius: \"16px\",\n height: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n m: 0,\n maxHeight: CITATION_FULLSCREEN_DIALOG_HEIGHT,\n maxWidth: \"95vw\",\n overflow: \"hidden\",\n width: \"95vw\",\n },\n }}\n >\n {citationPanel}\n </Dialog>\n ) : (\n citationPanel\n )\n )}\n </span>\n );\n};\n\nexport default CitationAnchor;\n"],"names":["CITATION_FULLSCREEN_DIALOG_HEIGHT","retryButtonStyle","border","borderRadius","background","color","cursor","fontSize","fontWeight","padding","CitationAnchor","href","children","citationType","citationReason","metaData","chevronUpComponent","chevronDownComponent","customStyle","defaultState","onFullscreenChange","onDemandCitationContext","compareContext","useOptionalCompareContext","onDemandCitationConfig","getOnDemandCitationCacheEntry","fetchOnDemandCitationContext","onDemandCitationCacheVersion","isExpanded","setIsExpanded","useState","isFullscreen","setIsFullscreen","citationDisplayTitle","split","length","join","citationTitle","useEffect","onDemandCacheEntry","useMemo","isOnDemandCitationEnabled","enabled","hasOnDemandCitationData","status","data","Object","keys","effectiveMetaData","citations","shouldShowLoading","shouldShowError","shouldShowMissing","shouldRenderCitationContent","requestOnDemandCitation","useCallback","catch","error","debug","console","chevronUpComponentResolved","arrow","jsx","ChevronUp","size","chevronDownComponentResolved","ChevronDown","ChevronDownComponentDefault","renderRetryButton","style","type","onClick","event","stopPropagation","citationPanel","jsxs","boxSizing","overflow","marginTop","display","flexDirection","width","height","backgroundColor","justifyContent","borderBottom","flexShrink","prev","marginRight","DefaultFullScreenCloseIcon","DefaultFullScreenIcon","flex","minHeight","alignItems","gap","flexWrap","CitationRendererInner","relativeWrapper","citationButtonWrapper","next","webGpt","fontFamily","margin","textDecoration","wordBreak","whiteSpace","citationButton","Globe","verticalAlign","marginLeft","Dialog","open","onClose","maxWidth","BackdropProps","sx","backdropFilter","PaperProps","m","maxHeight"],"mappings":"kcA0CA,MAAMA,EAAoC,OAEpCC,EAAwC,CAC1CC,OAAQ,oBACRC,aAAc,MACdC,WAAY,UACZC,MAAO,UACPC,OAAQ,UACRC,SAAU,OACVC,WAAY,IACZC,QAAS,WAGPC,EAAgD,EAClDC,OACAC,WACAC,eACAC,iBACAC,WACAC,qBAAqB,KACrBC,uBAAuB,KACvBC,cAAc,CAAC,EACfC,gBAAe,EACfC,qBACAC,8BAEA,MAAMC,EAAiBC,IACjBC,EAAyBF,GAAgBE,uBACzCC,EAAgCH,GAAgBG,8BAChDC,EAA+BJ,GAAgBI,6BAC/CC,EAA+BL,GAAgBK,8BAC9CC,EAAYC,GAAiBC,EAASX,IACtCY,EAAcC,GAAmBF,GAAS,GAgB3CG,EACkB,iBAAbrB,GAAyBA,GAAUsB,MAAM,OAAOC,OAAS,EAC1DvB,EAASsB,MAAM,MAAME,KAAK,KAC1BxB,EACJyB,EAAoC,iBAAbzB,EAAwBA,EAAWA,EAAS,GAEzE0B,EAAU,KAGN,GAFAlB,IAAqBW,GAEhBA,EAEL,MAAO,KACHX,KAAqB,KAE1B,CAACW,EAAcX,IAElB,MAAMmB,EAAqBC,EACvB,IAAMnB,GAA2BI,EAC3BA,EAA8BJ,QAC9B,EACN,CACII,EACAE,EACAN,IAGFoB,IACAjB,GAAwBkB,WACxBrB,EACAsB,EAC6B,YAA/BJ,GAAoBK,QACpBL,EAAmBM,MACgB,iBAA5BN,EAAmBM,MAC1BC,OAAOC,KAAKR,EAAmBM,MAAMV,OAAS,EAC5Ca,EAAoBR,EACtB,KAAO,IACAzB,EACHkC,UAAWR,EACJE,EAA0BJ,GAAoBM,KAAO,CAAA,EACtD9B,GAAUkC,YAEpB,CACIN,EACAF,EACA1B,EACAwB,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,CACHU,QAAShE,GAAUqF,OAAS,SAAW,cACvCP,WAAY9E,GAAUqF,YAAqB,EAAA,SAC3CN,IAAK/E,GAAUqF,YAAqB,EAAA,MACpCC,WAAY,sBACZlB,gBAAiB,cACjB1E,QAAS,EACT6F,OAAQ,EACR/F,SAAU,OACVJ,aAAc,KACdG,OAAQ,UACRE,WAAaO,GAAUqF,OAAU,IAAM,IACvC/F,MAAQU,GAAUqF,OAAU,UAAY,oBACxClG,OAAQ,OACRqG,eAAgB,OAChBC,UAAW,aACXC,WAAY,YACRvF,EAAYwF,gBAAkB,CAAC,GAGtC9F,SAAA,CAAAG,GAAUqF,QACPtC,EAAC6C,EAAA,CACG3C,KAAM9C,EAAY2C,OAAOtD,UAAY,MACrCF,MAAOa,EAAY2C,OAAOxD,OAAS,UACnCgE,MAAO,CACHU,QAAS,eACTE,MAAO,MACPC,OAAQ,MACRM,YAAa,MACboB,cAAe,WACftB,WAAY,KAIxBxB,EAAC,QAAMlD,SAAqBqB,IAE5B6B,EAAC,OAAA,CACGO,MAAO,CACHU,QAAS,cACTc,WAAY,SACZgB,WAAY9F,GAAUqF,OAAS,WAAQ,EACvCQ,cAAe7F,GAAUqF,OAAS,gBAAa,GAGlDxF,WACKgD,EACAK,SAIjBrC,IACGG,EACI+B,EAACgD,EAAA,CACGC,KAAMhF,EACNiF,QAAS,KACLhF,GAAgB,GAChBZ,KAAqB,IAEzB6F,UAAU,EACVC,cAAe,CACXC,GAAI,CACAhC,gBAAiB,qBACjBiC,eAAgB,cAGxBC,WAAY,CACRF,GAAI,CACAhC,gBAAiB,UACjBhF,aAAc,OACd+E,OAAQlF,EACRsH,EAAG,EACHC,UAAWvH,EACXiH,SAAU,OACVpC,SAAU,SACVI,MAAO,SAIdrE,SAAA8D,IAGLA"}
@@ -1,2 +1,2 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import{useMemo as r}from"react";import{Box as n,Typography as o}from"@mui/material";import i from"react-markdown";import a from"rehype-raw";import c from"./CitationAnchor.js";import{mergeRulebookCitationsIntoMatchingLinks as l}from"./Guidelines/utils/helper.js";const s=e=>e?`./dual-citation?citationNumber=${encodeURIComponent(e)}`:"";function d({content:d="",title:u="",citations:p={},styles:m={},docData:h={},deviationData:x=null,open:f,onCitationFullscreenChange:g}){const y=r(()=>JSON.stringify(p||{}),[p]),D=r(()=>p,[y]),b=r(()=>JSON.stringify(h||{}),[h]),w=r(()=>h,[b]),C=r(()=>({citations:D,docData:w}),[D,w]),S=r(()=>{const e=x?.web_search_answer,t=e?.extraMetaData||{};return Object.keys(t).reduce((e,t)=>{const r=((e,t)=>{if(!e||!t)return null;const r=e?.web_search_answer,n=r?.extraMetaData?.[t];return r&&n?{reasoningId:t,evaluation:e,webSearchAnswer:r,extraMetaData:n}:null})(x,t);return r&&(e[t]=r),e},{})},[x]),F=r(()=>l(d),[d]),v=r(()=>({a:({href:t="",children:r,type:n,reason:o,...i})=>{const a=i?.["data-cognitive-reasoning"],l=(d=i?.["dual-citation"],!0===d||"true"===d);var d;const u=l&&a?S[String(a)]:null;return e(c,{href:l?s(String(a||"")):t,children:r,citationType:l?"dual_citation":n,citationReason:o,metaData:{...C,...u?{webGpt:u}:{}},customStyle:u?{arrow:{color:"#6D28D9"}}:{},onFullscreenChange:g})}}),[C,S,g]);return t(n,{sx:{borderRadius:"8px",border:"1px solid #E4E7EC",bgcolor:"#FCFCFD"},children:[e(n,{sx:{px:1.5,py:.75,borderBottom:"1px solid #EAECF0"},children:e(o,{sx:{fontSize:"15px",fontWeight:600,color:"#344054",lineHeight:1.25},children:u})}),e(n,{sx:{px:1.5,py:1.1,display:"flex",flexDirection:"column",gap:.95},children:e(n,{sx:{display:"flex",flexDirection:"column"},children:e(o,{component:"div",sx:{...m},children:e(i,{components:v,rehypePlugins:[a],children:F})})})})]})}export{d as default};
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import{useMemo as n}from"react";import{Box as o,Typography as r}from"@mui/material";import i from"react-markdown";import a from"rehype-raw";import c from"./CitationAnchor.js";import{mergeRulebookCitationsIntoMatchingLinks as s}from"./Guidelines/utils/helper.js";import{useOptionalCompareContext as l}from"./CompareContext.js";import{buildOnDemandCitationContexts as d}from"./onDemandCitations/contextBuilder.js";import{getOnDemandCitationLinkKey as m}from"./onDemandCitations/href.js";const p=e=>e?`./dual-citation?citationNumber=${encodeURIComponent(e)}`:"";function u({content:u="",title:f="",citations:h={},styles:x={},docData:C={},deviationData:D=null,open:g,onCitationFullscreenChange:y,tabKey:b,sectionTitle:w,referenceSectionTitle:I,sourceNodeId:v,deviationKey:S,baseContentId:j,compareContentIds:F}){const E=l(),M=E?.treeData,N=E?.onDemandCitationConfig,T=n(()=>JSON.stringify(h||{}),[h]),_=n(()=>h,[T]),K=n(()=>JSON.stringify(C||{}),[C]),A=n(()=>C,[K]),O=n(()=>({citations:_,docData:A}),[_,A]),R=n(()=>{if(!N?.enabled)return new Map;return d({treeData:M,content:u,requestId:N.requestId,tabKey:b,popupNodeId:v||D?.nodeId,deviationKey:S,sectionTitle:w,referenceSectionTitle:I,docData:A,staticCitations:_,deviationData:D,cognitiveData:null,baseContentId:j,compareContentIds:F}).reduce((e,t)=>(e.set(m(t.href),t),e),new Map)},[j,F,u,D,S,N,I,w,v,_,A,b,M]),k=n(()=>{const e=D?.web_search_answer,t=e?.extraMetaData||{};return Object.keys(t).reduce((e,t)=>{const n=((e,t)=>{if(!e||!t)return null;const n=e?.web_search_answer,o=n?.extraMetaData?.[t];return n&&o?{reasoningId:t,evaluation:e,webSearchAnswer:n,extraMetaData:o}:null})(D,t);return n&&(e[t]=n),e},{})},[D]),q=n(()=>s(u),[u]),B=n(()=>({a:({href:t="",children:n,type:o,reason:r,...i})=>{const a=i?.["data-cognitive-reasoning"],s=(l=i?.["dual-citation"],!0===l||"true"===l);var l;const d=s&&a?k[String(a)]:null;return e(c,{href:s?p(String(a||"")):t,children:n,citationType:s?"dual_citation":o,citationReason:r,onDemandCitationContext:s?void 0:R.get(m(t)),metaData:{...O,...d?{webGpt:d}:{}},customStyle:d?{arrow:{color:"#6D28D9"}}:{},onFullscreenChange:y})}}),[R,O,k,y]);return t(o,{sx:{borderRadius:"8px",border:"1px solid #E4E7EC",bgcolor:"#FCFCFD"},children:[e(o,{sx:{px:1.5,py:.75,borderBottom:"1px solid #EAECF0"},children:e(r,{sx:{fontSize:"15px",fontWeight:600,color:"#344054",lineHeight:1.25},children:f})}),e(o,{sx:{px:1.5,py:1.1,display:"flex",flexDirection:"column",gap:.95},children:e(o,{sx:{display:"flex",flexDirection:"column"},children:e(r,{component:"div",sx:{...x},children:e(i,{components:B,rehypePlugins:[a],children:q})})})})]})}export{u as default};
2
2
  //# sourceMappingURL=CitationRenderer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CitationRenderer.js","sources":["../../../src/features/CognitiveCompare/CitationRenderer.tsx"],"sourcesContent":["import React, { useMemo } from 'react'\nimport { Box, Typography, IconButton } from \"@mui/material\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport CitationAnchor from './CitationAnchor';\nimport { mergeRulebookCitationsIntoMatchingLinks } from './Guidelines/utils/helper';\n\ntype Props = {\n title?: string,\n content?: string,\n citations?: Record<string, any>,\n styles?: Record<string, any>\n docData?: Record<string, any> | null,\n deviationData?: Record<string, any> | null,\n open: boolean,\n onCitationFullscreenChange?: (isFullscreen: boolean) => void,\n}\n\nconst parseHref = (href: string) => {\n try {\n const baseUrl = typeof window !== \"undefined\" ? window.location.origin : \"http://localhost\";\n return new URL(href, baseUrl);\n } catch {\n return null;\n }\n};\n\nconst isDualCitation = (value: unknown) => value === true || value === \"true\";\n\nconst buildDualCitationHref = (reasoningId: string) =>\n reasoningId ? `./dual-citation?citationNumber=${encodeURIComponent(reasoningId)}` : \"\";\n\nconst buildWebGptMetaForReasoning = (\n deviationData: Record<string, any> | null | undefined,\n reasoningId: string,\n) => {\n if (!deviationData || !reasoningId) return null;\n\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData?.[reasoningId];\n if (!webSearchAnswer || !extraMetaData) return null;\n\n return {\n reasoningId,\n evaluation: deviationData,\n webSearchAnswer,\n extraMetaData,\n };\n};\n\nfunction CitationRenderer({\n content = \"\",\n title = \"\",\n citations = {},\n styles = {},\n docData = {} as Record<string, any>,\n deviationData = null,\n open,\n onCitationFullscreenChange,\n}: Props) {\n // Stabilize citations and docData — they arrive as new object references\n // on every stream tick even when content hasn't changed, which would\n // remount CitationAnchor and reset its expanded state.\n const stableCitationsStr = useMemo(() => JSON.stringify(citations || {}), [citations]);\n const stableCitations = useMemo(\n () => citations,\n [stableCitationsStr]\n );\n\n const stableDocDataStr = useMemo(() => JSON.stringify(docData || {}), [docData]);\n const stableDocData = useMemo(\n () => docData,\n [stableDocDataStr]\n );\n\n const stableMetaData = useMemo(\n () => ({ citations: stableCitations, docData: stableDocData }),\n [stableCitations, stableDocData]\n );\n\n const webGptMetaByReasoningId = useMemo(() => {\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData || {};\n\n return Object.keys(extraMetaData).reduce((acc: Record<string, any>, reasoningId) => {\n const matchedExtraMetaData = buildWebGptMetaForReasoning(deviationData, reasoningId);\n if (matchedExtraMetaData) acc[reasoningId] = matchedExtraMetaData;\n return acc;\n }, {});\n }, [deviationData]);\n\n const processedContent = useMemo(\n () => mergeRulebookCitationsIntoMatchingLinks(content),\n [content]\n );\n\n const components = useMemo(() => {\n return {\n a: ({ href = \"\", children, type, reason, ...props }: any) => {\n const reasoningId = props?.[\"data-cognitive-reasoning\"];\n const shouldUseDualCitation = isDualCitation(props?.[\"dual-citation\"]);\n const matchedExtraMetaData =\n shouldUseDualCitation && reasoningId\n ? webGptMetaByReasoningId[String(reasoningId)]\n : null;\n return (\n <CitationAnchor\n href={shouldUseDualCitation ? buildDualCitationHref(String(reasoningId || \"\")) : href}\n children={children}\n citationType={shouldUseDualCitation ? \"dual_citation\" : type}\n citationReason={reason}\n metaData={{\n ...stableMetaData,\n ...(matchedExtraMetaData ? { webGpt: matchedExtraMetaData } : {}),\n }}\n customStyle={\n matchedExtraMetaData ? \n {\n arrow: {\n color: \"#6D28D9\"\n }\n } : {}\n }\n onFullscreenChange={onCitationFullscreenChange}\n />\n );\n },\n };\n }, [stableMetaData, webGptMetaByReasoningId, onCitationFullscreenChange]);\n\n return (\n <Box\n sx={{\n borderRadius: \"8px\",\n border: \"1px solid #E4E7EC\",\n bgcolor: \"#FCFCFD\",\n }}\n >\n <Box\n sx={{ px: 1.5, py: 0.75, borderBottom: \"1px solid #EAECF0\" }}\n >\n <Typography\n sx={{\n fontSize: \"15px\",\n fontWeight: 600,\n color: \"#344054\",\n lineHeight: 1.25,\n }}\n >\n {title}\n </Typography>\n </Box>\n <Box\n sx={{\n px: 1.5,\n py: 1.1,\n display: \"flex\",\n flexDirection: \"column\",\n gap: 0.95,\n }}\n >\n <Box sx={{ display: \"flex\", flexDirection: \"column\" }}>\n <Typography\n component=\"div\"\n sx={{ ...styles }}\n >\n <ReactMarkdown components={components} rehypePlugins={[rehypeRaw as any]}>\n {processedContent}\n </ReactMarkdown>\n </Typography>\n </Box>\n </Box>\n </Box>\n )\n}\n\nexport default CitationRenderer\n"],"names":["buildDualCitationHref","reasoningId","encodeURIComponent","CitationRenderer","content","title","citations","styles","docData","deviationData","open","onCitationFullscreenChange","stableCitationsStr","useMemo","JSON","stringify","stableCitations","stableDocDataStr","stableDocData","stableMetaData","webGptMetaByReasoningId","webSearchAnswer","web_search_answer","extraMetaData","Object","keys","reduce","acc","matchedExtraMetaData","evaluation","buildWebGptMetaForReasoning","processedContent","mergeRulebookCitationsIntoMatchingLinks","components","a","href","children","type","reason","props","shouldUseDualCitation","value","String","jsx","CitationAnchor","citationType","citationReason","metaData","webGpt","customStyle","arrow","color","onFullscreenChange","jsxs","Box","sx","borderRadius","border","bgcolor","px","py","borderBottom","Typography","fontSize","fontWeight","lineHeight","display","flexDirection","gap","component","ReactMarkd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AVE,GAA4B,SAAVA,GAAtC,IAACA,EA0ER,MAAMb,EACFY,GAAyBvC,EACnBmB,EAAwBsB,OAAOzC,IAC/B,KAEN,OAAA0C,EAACC,EAAA,CACGT,KAAMK,EAAwBxC,EAAsB0C,OAAOzC,GAAe,KAAOkC,EACjFC,WACAS,aAAcL,EAAwB,gBAAkBH,EACxDS,eAAgBR,EAChBS,SAAU,IACH5B,KACCS,EAAuB,CAAEoB,OAAQpB,GAAyB,CAAC,GAEnEqB,YACIrB,EACA,CACIsB,MAAO,CACHC,MAAO,YAEX,CAAC,EAETC,mBAAoBzC,OAKrC,CAACQ,EAAgBC,EAAyBT,IAGzC,OAAA0C,EAACC,EAAA,CACGC,GAAI,CACAC,aAAc,MACdC,OAAQ,oBACRC,QAAS,WAGbtB,SAAA,CAAAO,EAACW,EAAA,CACGC,GAAI,CAAEI,GAAI,IAAKC,GAAI,IAAMC,aAAc,qBAEvCzB,SAAAO,EAACmB,EAAA,CACGP,GAAI,CACAQ,SAAU,OACVC,WAAY,IACZb,MAAO,UACPc,WAAY,MAGf7B,SAAA/B,MAGTsC,EAACW,EAAA,CACGC,GAAI,CACAI,GAAI,IACJC,GAAI,IACJM,QAAS,OACTC,cAAe,SACfC,IAAK,KAGThC,SAAAO,EAACW,GAAIC,GAAI,CAAEW,QAAS,OAAQC,cAAe,UACvC/B,SAAAO,EAACmB,EAAA,CACGO,UAAU,MACVd,GAAI,IAAKhD,GAET6B,WAACkC,EAAc,CAAArC,aAAwBsC,cAAe,CAACC,GAClDpC,SACLL,YAMxB"}
1
+ {"version":3,"file":"CitationRenderer.js","sources":["../../../src/features/CognitiveCompare/CitationRenderer.tsx"],"sourcesContent":["import React, { useMemo } from 'react'\nimport { Box, Typography, IconButton } from \"@mui/material\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport CitationAnchor from './CitationAnchor';\nimport { mergeRulebookCitationsIntoMatchingLinks } from './Guidelines/utils/helper';\nimport { useOptionalCompareContext } from './CompareContext';\nimport {\n buildOnDemandCitationContexts,\n getOnDemandCitationLinkKey,\n} from './onDemandCitations';\n\ntype Props = {\n title?: string,\n content?: string,\n citations?: Record<string, any>,\n styles?: Record<string, any>\n docData?: Record<string, any> | null,\n deviationData?: Record<string, any> | null,\n open: boolean,\n onCitationFullscreenChange?: (isFullscreen: boolean) => void,\n tabKey?: \"deviation\" | \"association\",\n sectionTitle?: string,\n referenceSectionTitle?: string,\n sourceNodeId?: string,\n deviationKey?: string,\n baseContentId?: string,\n compareContentIds?: string[],\n}\n\nconst parseHref = (href: string) => {\n try {\n const baseUrl = typeof window !== \"undefined\" ? window.location.origin : \"http://localhost\";\n return new URL(href, baseUrl);\n } catch {\n return null;\n }\n};\n\nconst isDualCitation = (value: unknown) => value === true || value === \"true\";\n\nconst buildDualCitationHref = (reasoningId: string) =>\n reasoningId ? `./dual-citation?citationNumber=${encodeURIComponent(reasoningId)}` : \"\";\n\nconst buildWebGptMetaForReasoning = (\n deviationData: Record<string, any> | null | undefined,\n reasoningId: string,\n) => {\n if (!deviationData || !reasoningId) return null;\n\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData?.[reasoningId];\n if (!webSearchAnswer || !extraMetaData) return null;\n\n return {\n reasoningId,\n evaluation: deviationData,\n webSearchAnswer,\n extraMetaData,\n };\n};\n\nfunction CitationRenderer({\n content = \"\",\n title = \"\",\n citations = {},\n styles = {},\n docData = {} as Record<string, any>,\n deviationData = null,\n open,\n onCitationFullscreenChange,\n tabKey,\n sectionTitle,\n referenceSectionTitle,\n sourceNodeId,\n deviationKey,\n baseContentId,\n compareContentIds,\n}: Props) {\n const compareContext = useOptionalCompareContext();\n const treeData = compareContext?.treeData;\n const onDemandCitationConfig = compareContext?.onDemandCitationConfig;\n // Stabilize citations and docData — they arrive as new object references\n // on every stream tick even when content hasn't changed, which would\n // remount CitationAnchor and reset its expanded state.\n const stableCitationsStr = useMemo(() => JSON.stringify(citations || {}), [citations]);\n const stableCitations = useMemo(\n () => citations,\n [stableCitationsStr]\n );\n\n const stableDocDataStr = useMemo(() => JSON.stringify(docData || {}), [docData]);\n const stableDocData = useMemo(\n () => docData,\n [stableDocDataStr]\n );\n\n const stableMetaData = useMemo(\n () => ({ citations: stableCitations, docData: stableDocData }),\n [stableCitations, stableDocData]\n );\n\n const onDemandContextByLinkKey = useMemo(() => {\n if (!onDemandCitationConfig?.enabled) return new Map<string, any>();\n\n const contexts = buildOnDemandCitationContexts({\n treeData,\n content,\n requestId: onDemandCitationConfig.requestId,\n tabKey,\n popupNodeId: sourceNodeId || (deviationData as any)?.nodeId,\n deviationKey,\n sectionTitle,\n referenceSectionTitle,\n docData: stableDocData,\n staticCitations: stableCitations,\n deviationData,\n cognitiveData: null,\n baseContentId,\n compareContentIds,\n });\n\n return contexts.reduce((acc, context) => {\n acc.set(getOnDemandCitationLinkKey(context.href), context);\n return acc;\n }, new Map<string, any>());\n }, [\n baseContentId,\n compareContentIds,\n content,\n deviationData,\n deviationKey,\n onDemandCitationConfig,\n referenceSectionTitle,\n sectionTitle,\n sourceNodeId,\n stableCitations,\n stableDocData,\n tabKey,\n treeData,\n ]);\n\n const webGptMetaByReasoningId = useMemo(() => {\n const webSearchAnswer = deviationData?.web_search_answer;\n const extraMetaData = webSearchAnswer?.extraMetaData || {};\n\n return Object.keys(extraMetaData).reduce((acc: Record<string, any>, reasoningId) => {\n const matchedExtraMetaData = buildWebGptMetaForReasoning(deviationData, reasoningId);\n if (matchedExtraMetaData) acc[reasoningId] = matchedExtraMetaData;\n return acc;\n }, {});\n }, [deviationData]);\n\n const processedContent = useMemo(\n () => mergeRulebookCitationsIntoMatchingLinks(content),\n [content]\n );\n\n const components = useMemo(() => {\n return {\n a: ({ href = \"\", children, type, reason, ...props }: any) => {\n const reasoningId = props?.[\"data-cognitive-reasoning\"];\n const shouldUseDualCitation = isDualCitation(props?.[\"dual-citation\"]);\n const matchedExtraMetaData =\n shouldUseDualCitation && reasoningId\n ? webGptMetaByReasoningId[String(reasoningId)]\n : null;\n return (\n <CitationAnchor\n href={shouldUseDualCitation ? buildDualCitationHref(String(reasoningId || \"\")) : href}\n children={children}\n citationType={shouldUseDualCitation ? \"dual_citation\" : type}\n citationReason={reason}\n onDemandCitationContext={\n shouldUseDualCitation\n ? undefined\n : onDemandContextByLinkKey.get(getOnDemandCitationLinkKey(href))\n }\n metaData={{\n ...stableMetaData,\n ...(matchedExtraMetaData ? { webGpt: matchedExtraMetaData } : {}),\n }}\n customStyle={\n matchedExtraMetaData ? \n {\n arrow: {\n color: \"#6D28D9\"\n }\n } : {}\n }\n onFullscreenChange={onCitationFullscreenChange}\n />\n );\n },\n };\n }, [onDemandContextByLinkKey, stableMetaData, webGptMetaByReasoningId, onCitationFullscreenChange]);\n\n return (\n <Box\n sx={{\n borderRadius: \"8px\",\n border: \"1px solid #E4E7EC\",\n bgcolor: \"#FCFCFD\",\n }}\n >\n <Box\n sx={{ px: 1.5, py: 0.75, borderBottom: \"1px solid #EAECF0\" }}\n >\n <Typography\n sx={{\n fontSize: \"15px\",\n fontWeight: 600,\n color: \"#344054\",\n lineHeight: 1.25,\n }}\n >\n {title}\n </Typography>\n </Box>\n <Box\n sx={{\n px: 1.5,\n py: 1.1,\n display: \"flex\",\n flexDirection: \"column\",\n gap: 0.95,\n }}\n >\n <Box sx={{ display: \"flex\", flexDirection: \"column\" }}>\n <Typography\n component=\"div\"\n sx={{ ...styles }}\n >\n <ReactMarkdown components={components} rehypePlugins={[rehypeRaw as any]}>\n {processedContent}\n </ReactMarkdown>\n </Typography>\n </Box>\n </Box>\n </Box>\n )\n}\n\nexport default CitationRenderer\n"],"names":["buildDualCitationHref","reasoningId","encodeURIComponent","CitationRenderer","content","title","citations","styles","docData","deviationData","open","onCitationFullscreenChange","tabKey","sectionTitle","referenceSectionTitle","sourceNodeId","deviationKey","baseContentId","compareContentIds","compareContext","useOptionalCompareContext","treeData","onDemandCitationConfig","stableCitationsStr","useMemo","JSON","stringify","stableCitations","stableDocDataStr","stableDocData","stableMetaData","onDemandContextByLinkKey","enabled","Map","buildOnDemandCitationContexts","requestId","popupNodeId","nodeId","staticCitations","cognitiveData","reduce","acc","context","set","getOnDemandCitationLinkKey","href","webGptMetaByReasoningId","webSearchAnswer","web_search_answer","extraMetaData","Object","keys","matchedExtraMetaData","evaluation","buildWebGptMetaForReasoning","processedContent","mergeRulebookCitationsIntoMatchingLinks","components","a","children","type","reason","props","shouldUseDualCitation","value","String","jsx","CitationAnchor","citationType","citationReason","onDemandCitationContext","get","metaData","webGpt","customStyle","arrow","color","onFullscreenChange","jsxs","Box","sx","borderRadius","border","bgcolor","px","py","borderBottom","Typography","fontSize","fontWeight","lineHeight","display","flexDirection","gap","component","ReactMarkdown","rehypePlugins","rehypeRaw"],"mappings":"uhBAuCA,MAEMA,EAAyBC,GAC3BA,EAAc,kCAAkCC,mBAAmBD,KAAiB,GAoBxF,SAASE,GAAiBC,QACtBA,EAAU,GAAAC,MACVA,EAAQ,GAAAC,UACRA,EAAY,CAAC,EAAAC,OACbA,EAAS,CAAC,EAAAC,QACVA,EAAU,CAAC,EAAAC,cACXA,EAAgB,KAAAC,KAChBA,EAAAC,2BACAA,EAAAC,OACAA,EAAAC,aACAA,EAAAC,sBACAA,EAAAC,aACAA,EAAAC,aACAA,EAAAC,cACAA,EAAAC,kBACAA,IAEA,MAAMC,EAAiBC,IACjBC,EAAWF,GAAgBE,SAC3BC,EAAyBH,GAAgBG,uBAIzCC,EAAqBC,EAAQ,IAAMC,KAAKC,UAAUpB,GAAa,IAAK,CAACA,IACrEqB,EAAkBH,EACpB,IAAMlB,EACN,CAACiB,IAGCK,EAAmBJ,EAAQ,IAAMC,KAAKC,UAAUlB,GAAW,IAAK,CAACA,IACjEqB,EAAgBL,EAClB,IAAMhB,EACN,CAACoB,IAGCE,EAAiBN,EACnB,KAAA,CAASlB,UAAWqB,EAAiBnB,QAASqB,IAC9C,CAACF,EAAiBE,IAGhBE,EAA2BP,EAAQ,KAC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sBiE,OAAOhE,GAAe,KAAO4C,EACjFc,WACAS,aAAcL,EAAwB,gBAAkBH,EACxDS,eAAgBR,EAChBS,wBACIP,OACM,EACAhC,EAAyBwC,IAAI3B,EAA2BC,IAElE2B,SAAU,IACH1C,KACCsB,EAAuB,CAAEqB,OAAQrB,GAAyB,CAAC,GAEnEsB,YACItB,EACA,CACIuB,MAAO,CACHC,MAAO,YAEX,CAAC,EAETC,mBAAoBlE,OAKrC,CAACoB,EAA0BD,EAAgBgB,EAAyBnC,IAGnE,OAAAmE,EAACC,EAAA,CACGC,GAAI,CACAC,aAAc,MACdC,OAAQ,oBACRC,QAAS,WAGbxB,SAAA,CAAAO,EAACa,EAAA,CACGC,GAAI,CAAEI,GAAI,IAAKC,GAAI,IAAMC,aAAc,qBAEvC3B,SAAAO,EAACqB,EAAA,CACGP,GAAI,CACAQ,SAAU,OACVC,WAAY,IACZb,MAAO,UACPc,WAAY,MAGf/B,SAAAtD,MAGT6D,EAACa,EAAA,CACGC,GAAI,CACAI,GAAI,IACJC,GAAI,IACJM,QAAS,OACTC,cAAe,SACfC,IAAK,KAGTlC,SAAAO,EAACa,GAAIC,GAAI,CAAEW,QAAS,OAAQC,cAAe,UACvCjC,SAAAO,EAACqB,EAAA,CACGO,UAAU,MACVd,GAAI,IAAKzE,GAEToD,WAACoC,EAAc,CAAAtC,aAAwBuC,cAAe,CAACC,GAClDtC,SACLJ,YAMxB"}
@@ -0,0 +1,2 @@
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import{Box as i}from"@mui/material";import{useMemo as a}from"react";import r from"react-markdown";import n from"rehype-raw";import l from"../PdfViewer/PdfViewer.js";import{useCompareContext as o}from"./CompareContext.js";import{SHARED_MARKDOWN_STYLES as s}from"./CognitiveCompareConfig.js";import c from"./GptWebCitationPanel.js";import{processGuidelinesMarkdown as u}from"./Guidelines/utils/processGuidelinesMarkdown.js";import d from"./ResizableSplitPane.js";const g=({label:e})=>t("div",{style:{padding:"12px",fontSize:"13px",color:"#475467",lineHeight:1.5},children:["Citation text was returned for ",e,", but a signed PDF URL is not available."]}),h=e=>({...e?.customMetaData||{},...e?.custom_metadata||{}}),m=(e,t)=>{const i=h(e);return i.signed_url||i.signedUrl||t?.signed_url||t?.signedUrl||t?.metadata?.signed_url||t?.metadata?.signedUrl||""},p=e=>{try{const{citationNumber:t,parsedUrl:i}=(e=>{const t=e.match(/^(?:pdf_citation|deviation_summary)\$(\d+)/);if(t)try{const i=e.indexOf("?"),a=i>=0?e.slice(i):"";return{citationNumber:t[1],parsedUrl:new URL(a||"./",window.location.origin)}}catch{return{citationNumber:t[1],parsedUrl:null}}try{const t=new URL(e,window.location.origin);return{citationNumber:t.searchParams.get("citationNumber")||t.searchParams.get("citation_number"),parsedUrl:t}}catch{return{citationNumber:null,parsedUrl:null}}})(e),a=i?.searchParams.get("phrase_to_highlight")||null;return{citationNumber:t,phraseToHighlight:a,citationTypeFromHref:i?.searchParams.get("citation_type")||null}}catch{return{citationNumber:null,phraseToHighlight:null,citationTypeFromHref:null}}},f=t=>e("div",{style:{height:"100%",display:"flex",flexDirection:"column"},children:t}),_=({href:t,metaData:_,citationTitle:b,citationType:P,citationReason:F,isFullscreen:w})=>{const{guidelinesData:x}=o(),{citationNumber:y,phraseToHighlight:C,citationTypeFromHref:D}=p(t),U=P||D||void 0,N="il_rulebook_citation"===U?"rulebook_citation":U,T=y&&_?.citations?.[y]||{},j=_?.docData?.documents||{},v=_?.docData?.input_index_map||{},H=Object.keys(_?.citations||{}).length>0||Object.keys(_?.docData||{}).length>0,k=v?.[0],R=v?.[1],S=k?j[k]:null,G=R?j[R]:null,A=k?T[k]:null,O=R?T[R]:null,M=h(A),V=h(O),z=m(A,S),L=m(O,G),W=a(()=>A&&S?z?e(l,{defaultScale:"PageWidth",showFullScreenAction:!1,showHighlightsAction:!1,pdfName:S?.title,pdfUrl:z,highlightText:[A?.highlighted_text??""],highlightPages:{1:M?.pdf_start_page_number},jumpToPageValue:1,highlightCordinatePages:[],useCoordinates:!1,useRange:!0,rangeOfPages:[M?.pdf_start_page_number,M?.pdf_end_page_number]}):e(g,{label:"the uploaded contract"}):null,[A,M,S,z]),E=a(()=>O&&G?L?e(l,{defaultScale:"PageWidth",showFullScreenAction:!1,showHighlightsAction:!1,pdfName:G?.title,pdfUrl:L,jumpToPageValue:1,highlightText:[O?.highlighted_text??""],highlightPages:{1:V?.pdf_start_page_number},highlightCordinatePages:[],useCoordinates:!1,useRange:!0,rangeOfPages:[V?.pdf_start_page_number,V?.pdf_end_page_number]}):e(g,{label:"the reference contract"}):null,[O,V,G,L]),$="dual_citation"===N,q=$&&!!_?.webGpt,B=a(()=>{const t=q?e(c,{metaData:_,isFullscreen:w}):"rulebook_citation"===N?e(i,{sx:{padding:"0px 20px",backgroundColor:"#FFFFFF",borderRadius:"8px",...s,overflow:"auto"},children:e(r,{rehypePlugins:[n],children:u({guidelinesData:x,targetHighlights:[C],labelColor:"#FEF08A"})})}):E;return W||t?e(d,!W&&t?{rightComponent:t,isFullscreen:w}:W&&!t?{leftComponent:W,isFullscreen:w}:{leftComponent:W,rightComponent:t,isFullscreen:w}):null},[W,E,N,q,_,w,x,C]);return _?.webGpt&&!H?e(c,{metaData:_,isFullscreen:w}):y?"rulebook_citation"===N?B?f(B):e("div",{style:{padding:"12px",fontSize:"13px",color:"#344054",lineHeight:1.5},children:F||"Rulebook citation selected."}):$?B?f(B):_?.webGpt?e(c,{metaData:_,isFullscreen:w}):e("div",{children:"Missing PDF Citation. Please try again later"}):["contract","clause"].includes(b)?B?f(B):e("div",{children:"Missing PDF Citation. Please try again later"}):e("div",{children:"No Citation Found. Please try again later"}):null};export{_ as default};
2
+ //# sourceMappingURL=CitationRendererInner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CitationRendererInner.js","sources":["../../../src/features/CognitiveCompare/CitationRendererInner.tsx"],"sourcesContent":["import { Box } from \"@mui/material\";\nimport React, { useMemo } from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport rehypeRaw from \"rehype-raw\";\nimport PdfViewer from \"../PdfViewer/PdfViewer\";\nimport { useCompareContext } from \"./CompareContext\";\nimport { SHARED_MARKDOWN_STYLES } from \"./CognitiveCompareConfig\";\nimport GptWebCitationPanel from \"./GptWebCitationPanel\";\nimport { processGuidelinesMarkdown } from \"./Guidelines/utils/processGuidelinesMarkdown\";\nimport ResizableSplitPane from \"./ResizableSplitPane\";\n\nexport interface CitationRendererInnerProps {\n href: string;\n children: any;\n metaData: any;\n citationTitle: string;\n citationType?: string;\n citationReason?: string;\n isFullscreen: boolean\n}\n\nconst MissingPdfUrlNotice = ({ label }: { label: string }) => (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#475467\", lineHeight: 1.5 }}>\n Citation text was returned for {label}, but a signed PDF URL is not available.\n </div>\n);\n\nconst getCitationCustomMetadata = (citation: any) => ({\n ...(citation?.customMetaData || {}),\n ...(citation?.custom_metadata || {}),\n});\n\nconst getSignedPdfUrl = (citation: any, document: any) => {\n const customMetadata = getCitationCustomMetadata(citation);\n return (\n customMetadata.signed_url ||\n customMetadata.signedUrl ||\n document?.signed_url ||\n document?.signedUrl ||\n document?.metadata?.signed_url ||\n document?.metadata?.signedUrl ||\n \"\"\n );\n};\n\nconst getCitationDetailsFromHref = (\n url: string,\n): {\n citationNumber: string | null;\n phraseToHighlight: string | null;\n citationTypeFromHref: string | null;\n} => {\n const getCitationUrl = (value: string) => {\n const prefixedCitationMatch = value.match(/^(?:pdf_citation|deviation_summary)\\$(\\d+)/);\n if (prefixedCitationMatch) {\n try {\n const queryStartIndex = value.indexOf(\"?\");\n const search = queryStartIndex >= 0 ? value.slice(queryStartIndex) : \"\";\n return {\n citationNumber: prefixedCitationMatch[1],\n parsedUrl: new URL(search || \"./\", window.location.origin),\n };\n } catch {\n return {\n citationNumber: prefixedCitationMatch[1],\n parsedUrl: null,\n };\n }\n }\n\n try {\n const parsedUrl = new URL(value, window.location.origin);\n const citationNumber =\n parsedUrl.searchParams.get(\"citationNumber\") ||\n parsedUrl.searchParams.get(\"citation_number\");\n return {citationNumber, parsedUrl};\n } catch {\n return {citationNumber: null, parsedUrl: null};\n }\n };\n\n try {\n const { citationNumber, parsedUrl } = getCitationUrl(url);\n const phraseToHighlight = parsedUrl?.searchParams.get(\"phrase_to_highlight\") || null;\n const citationTypeFromHref = parsedUrl?.searchParams.get(\"citation_type\") || null;\n return {citationNumber, phraseToHighlight, citationTypeFromHref};\n } catch {\n return {citationNumber: null, phraseToHighlight: null, citationTypeFromHref: null};\n }\n};\n\nconst renderCitationShell = (content: React.ReactNode) => (\n <div style={{ height: \"100%\", display: \"flex\", flexDirection: \"column\" }}>\n {content}\n </div>\n);\n\nconst CitationRendererInner: React.FC<CitationRendererInnerProps> = ({\n href,\n metaData,\n citationTitle,\n citationType,\n citationReason,\n isFullscreen\n}) => {\n const { guidelinesData } = useCompareContext();\n const pdfCitationTypes = [\"contract\", \"clause\"];\n const {citationNumber, phraseToHighlight, citationTypeFromHref} = getCitationDetailsFromHref(href);\n const resolvedCitationType = citationType || citationTypeFromHref || undefined;\n const normalizedCitationType =\n resolvedCitationType === \"il_rulebook_citation\" ? \"rulebook_citation\" : resolvedCitationType;\n const citationGroup = citationNumber ? (metaData?.citations?.[citationNumber] || {}) : {};\n const documents = metaData?.docData?.documents || {};\n const inputIndexMap = metaData?.docData?.input_index_map || {};\n const hasRegularCitationData =\n Object.keys(metaData?.citations || {}).length > 0 ||\n Object.keys(metaData?.docData || {}).length > 0;\n\n const leftUuid = inputIndexMap?.[\"0\"];\n const rightUuid = inputIndexMap?.[\"1\"];\n const leftDocument = leftUuid ? documents[leftUuid] : null;\n const rightDocument = rightUuid ? documents[rightUuid] : null;\n const leftCitation = leftUuid ? citationGroup[leftUuid] : null;\n const rightCitation = rightUuid ? citationGroup[rightUuid] : null;\n const leftCitationMetadata = getCitationCustomMetadata(leftCitation);\n const rightCitationMetadata = getCitationCustomMetadata(rightCitation);\n const leftPdfUrl = getSignedPdfUrl(leftCitation, leftDocument);\n const rightPdfUrl = getSignedPdfUrl(rightCitation, rightDocument);\n\n const leftComponent = useMemo(() => {\n if (!leftCitation || !leftDocument) return null;\n if (!leftPdfUrl) return <MissingPdfUrlNotice label=\"the uploaded contract\" />;\n return (\n <PdfViewer\n defaultScale={'PageWidth'}\n showFullScreenAction={false}\n showHighlightsAction={false}\n pdfName={leftDocument?.title}\n pdfUrl={leftPdfUrl}\n highlightText={[leftCitation?.highlighted_text ?? '']}\n highlightPages={{ 1: leftCitationMetadata?.pdf_start_page_number }}\n jumpToPageValue={1}\n highlightCordinatePages={[]}\n useCoordinates={false}\n useRange={true}\n rangeOfPages={[leftCitationMetadata?.pdf_start_page_number, leftCitationMetadata?.pdf_end_page_number]}\n />\n );\n }, [\n leftCitation,\n leftCitationMetadata,\n leftDocument,\n leftPdfUrl,\n ]);\n\n const rightComponent = useMemo(() => {\n if (!rightCitation || !rightDocument) return null;\n if (!rightPdfUrl) return <MissingPdfUrlNotice label=\"the reference contract\" />;\n return (\n <PdfViewer\n defaultScale={'PageWidth'}\n showFullScreenAction={false}\n showHighlightsAction={false}\n pdfName={rightDocument?.title}\n pdfUrl={rightPdfUrl}\n jumpToPageValue={1}\n highlightText={[rightCitation?.highlighted_text ?? '']}\n highlightPages={{ 1: rightCitationMetadata?.pdf_start_page_number }}\n highlightCordinatePages={[]}\n useCoordinates={false}\n useRange={true}\n rangeOfPages={[rightCitationMetadata?.pdf_start_page_number, rightCitationMetadata?.pdf_end_page_number]}\n />\n );\n }, [\n rightCitation,\n rightCitationMetadata,\n rightDocument,\n rightPdfUrl,\n ]);\n\n const isDualCitationType = normalizedCitationType === \"dual_citation\";\n const isDualWebGptCitation = isDualCitationType && !!metaData?.webGpt;\n\n const splitPaneComponent = useMemo(() => {\n const rightPane =\n isDualWebGptCitation ? (\n <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />\n ) : normalizedCitationType === \"rulebook_citation\" ? (\n <Box sx={{\n padding: '0px 20px',\n backgroundColor: '#FFFFFF',\n borderRadius: '8px',\n ...SHARED_MARKDOWN_STYLES,\n overflow: 'auto'\n }}>\n <ReactMarkdown rehypePlugins={[rehypeRaw as any]}>\n {processGuidelinesMarkdown({\n guidelinesData, targetHighlights: [phraseToHighlight!], labelColor: \"#FEF08A\"})}\n </ReactMarkdown>\n </Box>\n ) : (\n rightComponent\n );\n\n if (!leftComponent && !rightPane) return null;\n\n if (!leftComponent && rightPane) {\n return (\n <ResizableSplitPane\n rightComponent={rightPane}\n isFullscreen={isFullscreen}\n />\n );\n }\n\n if (leftComponent && !rightPane) {\n return (\n <ResizableSplitPane\n leftComponent={leftComponent}\n isFullscreen={isFullscreen}\n />\n );\n }\n\n return (\n <ResizableSplitPane\n leftComponent={leftComponent}\n rightComponent={rightPane}\n isFullscreen={isFullscreen}\n />\n );\n }, [leftComponent, rightComponent, normalizedCitationType, isDualWebGptCitation, metaData, isFullscreen, guidelinesData, phraseToHighlight]);\n\n if (metaData?.webGpt && !hasRegularCitationData) {\n return <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />;\n }\n\n if (!citationNumber) return null;\n\n if (normalizedCitationType === \"rulebook_citation\") {\n if (splitPaneComponent) return renderCitationShell(splitPaneComponent);\n\n return (\n <div style={{ padding: \"12px\", fontSize: \"13px\", color: \"#344054\", lineHeight: 1.5 }}>\n {citationReason || \"Rulebook citation selected.\"}\n </div>\n );\n }\n\n if (isDualCitationType) {\n if (splitPaneComponent) return renderCitationShell(splitPaneComponent);\n if (metaData?.webGpt) return <GptWebCitationPanel metaData={metaData} isFullscreen={isFullscreen} />;\n return <div>Missing PDF Citation. Please try again later</div>;\n }\n\n if (pdfCitationTypes.includes(citationTitle)) {\n if (splitPaneComponent) return renderCitationShell(splitPaneComponent);\n return <div>Missing PDF Citation. Please try again later</div>;\n }\n\n return <div>No Citation Found. Please try again later</div>;\n};\n\nexport default CitationRendererInner;\n"],"names":["MissingPdfUrlNotice","label","style","padding","fontSize","color","lineHeight","children","getCitationCustomMetadata","citation","customMetaData","custom_metadata","getSignedPdfUrl","document","customMetadata","signed_url","signedUrl","metadata","getCitationDetailsFromHref","url","citationNumber","parsedUrl","value","prefixedCitationMatch","match","queryStartIndex","indexOf","search","slice","URL","window","location","origin","searchParams","get","getCitationUrl","phraseToHighlight","citationTypeFromHref","renderCitationShell","content","jsx","height","display","flexDirection","CitationRendererInner","href","metaData","citationTitle","citationType","citationReason","isFullscreen","guidelinesData","useCompareContext","resolvedCitationType","normalizedCitationType","citationGroup","citations","documents","docData","inputIndexMap","input_index_map","hasRegularCitationData","Object","keys","length","leftUuid","rightUuid","leftDocument","rightDocument","leftCitation","rightCitation","leftCitationMetadata","rightCitationMetadata","leftPdfUrl","rightPdfUrl","leftComponent","useMemo","PdfViewer","defaultScale","showFullScreenAction","showHighlightsAction","pdfName","title","pdfUrl","highlightText","highlighted_text","highlightPages","pdf_start_page_number","jumpToPageValue","highlightCordinatePages","useCoordinates","useRange","rangeOfPages","pdf_end_page_number","rightComponent","isDualCitationType","isDualWebGptCitation","webGpt","splitPaneComponent","rightPane","GptWebCitationPanel","Box","sx","backgroundColor","borderRadius","SHARED_MARKDOWN_STYLES","overflow","ReactMarkdown","rehypePlugins","rehypeRaw","processGuidelinesMarkdown","targetHighlights","labelColor","ResizableSplitPane","includes"],"mappings":"+fAqBA,MAAMA,EAAsB,EAAGC,aAC1B,MAAI,CAAAC,MAAO,CAAEC,QAAS,OAAQC,SAAU,OAAQC,MAAO,UAAWC,WAAY,KAAOC,SAAA,CAAA,kCAClDN,EAAM,8CAIxCO,EAA6BC,IAAmB,IAC9CA,GAAUC,gBAAkB,CAAC,KAC7BD,GAAUE,iBAAmB,CAAC,IAGhCC,EAAkB,CAACH,EAAeI,KAC9B,MAAAC,EAAiBN,EAA0BC,GACjD,OACIK,EAAeC,YACfD,EAAeE,WACfH,GAAUE,YACVF,GAAUG,WACVH,GAAUI,UAAUF,YACpBF,GAAUI,UAAUD,WACpB,IAIFE,EACFC,IAmCI,IACA,MAAMC,eA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