"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    AutopilotChatMarkdownRenderer: ()=>AutopilotChatMarkdownRenderer
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
require("katex/dist/katex.min.css");
const react_namespaceObject = require("@lingui/react");
const material_namespaceObject = require("@mui/material");
const apollo_core_namespaceObject = require("@uipath/apollo-core");
var apollo_core_default = /*#__PURE__*/ __webpack_require__.n(apollo_core_namespaceObject);
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const external_react_markdown_namespaceObject = require("react-markdown");
var external_react_markdown_default = /*#__PURE__*/ __webpack_require__.n(external_react_markdown_namespaceObject);
const external_rehype_katex_namespaceObject = require("rehype-katex");
var external_rehype_katex_default = /*#__PURE__*/ __webpack_require__.n(external_rehype_katex_namespaceObject);
const external_remark_gfm_namespaceObject = require("remark-gfm");
var external_remark_gfm_default = /*#__PURE__*/ __webpack_require__.n(external_remark_gfm_namespaceObject);
const external_remark_math_namespaceObject = require("remark-math");
var external_remark_math_default = /*#__PURE__*/ __webpack_require__.n(external_remark_math_namespaceObject);
const use_is_streaming_message_cjs_namespaceObject = require("../../../hooks/use-is-streaming-message.cjs");
const chat_service_provider_cjs_namespaceObject = require("../../../providers/chat-service.provider.cjs");
const chat_state_provider_cjs_namespaceObject = require("../../../providers/chat-state-provider.cjs");
const streaming_provider_cjs_namespaceObject = require("../../../providers/streaming-provider.cjs");
const index_cjs_namespaceObject = require("../../../service/index.cjs");
const external_citation_cjs_namespaceObject = require("./citation.cjs");
const external_code_cjs_namespaceObject = require("./code.cjs");
const external_lists_cjs_namespaceObject = require("./lists.cjs");
const citation_parser_cjs_namespaceObject = require("./parsers/citation-parser.cjs");
const resource_token_parser_cjs_namespaceObject = require("./parsers/resource-token-parser.cjs");
const external_resource_chip_cjs_namespaceObject = require("./resource-chip.cjs");
const external_table_cjs_namespaceObject = require("./table.cjs");
const external_text_cjs_namespaceObject = require("./text.cjs");
const MarkdownContainer = (0, material_namespaceObject.styled)('div')(()=>({
        '&, & .katex': {
            color: 'var(--color-foreground)'
        },
        display: 'flex',
        flexDirection: 'column',
        gap: apollo_core_default().Spacing.SpacingL
    }));
const FAKE_STREAM_CHARS_COUNT = 10;
const FAKE_STREAM_INTERVAL = 50;
const CHUNK_QUEUE_PROCESS_INTERVAL = 50;
const INCOMPLETE_TOKEN_PATTERNS = [
    /\[\[resource-token:(?!.*\]\])/
];
function extractRenderableContent(content) {
    let earliestIndex = -1;
    for (const pattern of INCOMPLETE_TOKEN_PATTERNS){
        const match = content.match(pattern);
        if (match?.index !== void 0) {
            if (-1 === earliestIndex || match.index < earliestIndex) earliestIndex = match.index;
        }
    }
    if (-1 === earliestIndex) return {
        renderable: content,
        buffered: ''
    };
    return {
        renderable: content.slice(0, earliestIndex),
        buffered: content.slice(earliestIndex)
    };
}
function AutopilotChatMarkdownRendererComponent({ message }) {
    const { _ } = (0, react_namespaceObject.useLingui)();
    const messageId = external_react_default().useRef(message.id);
    const getInitialContent = external_react_default().useCallback(()=>{
        if (message.contentParts && message.contentParts.length > 0) return (0, citation_parser_cjs_namespaceObject.contentPartsToMarkdown)(messageId.current, message.contentParts);
        return message.content || '';
    }, [
        message.contentParts,
        message.content
    ]);
    const [content, setContent] = external_react_default().useState(message.fakeStream ? '' : getInitialContent());
    const chatService = (0, chat_service_provider_cjs_namespaceObject.useChatService)();
    const { spacing } = (0, chat_state_provider_cjs_namespaceObject.useChatState)();
    const { setStreaming } = (0, streaming_provider_cjs_namespaceObject.useStreaming)();
    const { isStreaming } = (0, use_is_streaming_message_cjs_namespaceObject.useIsStreamingMessage)(message);
    const chunkQueue = external_react_default().useRef([]);
    const lastChunkQueueProcessedTime = external_react_default().useRef(0);
    const incompleteTokenBuffer = external_react_default().useRef('');
    external_react_default().useEffect(()=>{
        let unsubscribeStopResponse;
        let fakeStreamInterval;
        if (message.id !== messageId.current || !message.stream) {
            messageId.current = message.id;
            setContent(message.fakeStream ? '' : getInitialContent());
        }
        if (message.fakeStream) {
            unsubscribeStopResponse = chatService.on(index_cjs_namespaceObject.AutopilotChatEvent.StopResponse, ()=>{
                clearInterval(fakeStreamInterval);
                setStreaming(false);
                setContent(getInitialContent());
                chunkQueue.current = [];
                incompleteTokenBuffer.current = '';
                lastChunkQueueProcessedTime.current = 0;
            });
            const characters = getInitialContent().split('');
            let charIndex = 0;
            setStreaming(true);
            fakeStreamInterval = setInterval(()=>{
                if (charIndex < characters.length) {
                    const chunkSize = FAKE_STREAM_CHARS_COUNT;
                    const endIndex = Math.min(charIndex + chunkSize, characters.length);
                    const chunk = characters.slice(charIndex, endIndex).join('');
                    setContent((prevContent)=>`${prevContent}${chunk}`);
                    charIndex = endIndex;
                } else {
                    clearInterval(fakeStreamInterval);
                    setStreaming(false);
                }
            }, FAKE_STREAM_INTERVAL);
        }
        return ()=>{
            unsubscribeStopResponse?.();
            if (fakeStreamInterval) clearInterval(fakeStreamInterval);
        };
    }, [
        message,
        chatService,
        setStreaming,
        getInitialContent
    ]);
    const handleSendChunk = external_react_default().useCallback((msg)=>{
        if (msg.id !== messageId.current) return;
        chunkQueue.current.push(msg.content);
        if (Date.now() - lastChunkQueueProcessedTime.current > CHUNK_QUEUE_PROCESS_INTERVAL) {
            lastChunkQueueProcessedTime.current = Date.now();
            if (msg.contentParts) {
                const fullContent = (0, citation_parser_cjs_namespaceObject.contentPartsToMarkdown)(messageId.current, msg.contentParts);
                const { renderable } = extractRenderableContent(fullContent);
                setContent(renderable);
                return;
            }
            const accumulated = incompleteTokenBuffer.current + chunkQueue.current.join('');
            const { renderable, buffered } = extractRenderableContent(accumulated);
            incompleteTokenBuffer.current = buffered;
            chunkQueue.current = [];
            if (renderable) setContent((prevContent)=>`${prevContent}${renderable}`);
        } else if (msg.done) {
            lastChunkQueueProcessedTime.current = 0;
            if (msg.contentParts) return void setContent((0, citation_parser_cjs_namespaceObject.contentPartsToMarkdown)(messageId.current, msg.contentParts));
            const remaining = incompleteTokenBuffer.current + chunkQueue.current.join('');
            incompleteTokenBuffer.current = '';
            chunkQueue.current = [];
            setContent((prevContent)=>`${prevContent}${remaining}`);
        }
    }, []);
    external_react_default().useEffect(()=>{
        if (!chatService) return;
        const unsubscribe = chatService.on(index_cjs_namespaceObject.AutopilotChatEvent.SendChunk, handleSendChunk);
        return ()=>{
            unsubscribe();
        };
    }, [
        chatService,
        handleSendChunk
    ]);
    const components = external_react_default().useMemo(()=>({
            ul: external_lists_cjs_namespaceObject.Ul,
            ol: external_lists_cjs_namespaceObject.Ol,
            li: external_lists_cjs_namespaceObject.Li,
            p: /*#__PURE__*/ external_react_default().memo((0, external_text_cjs_namespaceObject.getTextForVariant)(spacing.markdownTokens.p)),
            h1: /*#__PURE__*/ external_react_default().memo((0, external_text_cjs_namespaceObject.getTextForVariant)(spacing.markdownTokens.h1, 1)),
            h2: /*#__PURE__*/ external_react_default().memo((0, external_text_cjs_namespaceObject.getTextForVariant)(spacing.markdownTokens.h2, 2)),
            h3: /*#__PURE__*/ external_react_default().memo((0, external_text_cjs_namespaceObject.getTextForVariant)(spacing.markdownTokens.h3, 3)),
            h4: /*#__PURE__*/ external_react_default().memo((0, external_text_cjs_namespaceObject.getTextForVariant)(spacing.markdownTokens.h4, 4)),
            h5: /*#__PURE__*/ external_react_default().memo((0, external_text_cjs_namespaceObject.getTextForVariant)(spacing.markdownTokens.h5, 5)),
            h6: /*#__PURE__*/ external_react_default().memo((0, external_text_cjs_namespaceObject.getTextForVariant)(spacing.markdownTokens.h6, 6)),
            br: external_text_cjs_namespaceObject.Break,
            table: external_table_cjs_namespaceObject.Table,
            thead: external_table_cjs_namespaceObject.TableHeader,
            tr: external_table_cjs_namespaceObject.Row,
            th: external_table_cjs_namespaceObject.HeaderCell,
            td: external_table_cjs_namespaceObject.Cell,
            img: ({ src })=>src || '',
            code: (props)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_code_cjs_namespaceObject.Code, {
                    ...props,
                    isStreaming: isStreaming ?? false
                }),
            blockquote: external_text_cjs_namespaceObject.Blockquote,
            em: external_text_cjs_namespaceObject.Emphazised,
            del: external_text_cjs_namespaceObject.Del,
            strong: external_text_cjs_namespaceObject.Strong,
            hr: external_text_cjs_namespaceObject.Hr,
            pre: external_text_cjs_namespaceObject.Pre,
            a: external_text_cjs_namespaceObject.Link,
            citation: external_citation_cjs_namespaceObject.Citation,
            'resource-chip': external_resource_chip_cjs_namespaceObject.ResourceChip
        }), [
        spacing,
        isStreaming
    ]);
    return external_react_default().useMemo(()=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(MarkdownContainer, {
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_react_markdown_default(), {
                remarkPlugins: [
                    citation_parser_cjs_namespaceObject.citationPlugin,
                    resource_token_parser_cjs_namespaceObject.resourceTokenPlugin,
                    external_remark_gfm_default(),
                    [
                        external_remark_math_default(),
                        {
                            singleDollarTextMath: false
                        }
                    ]
                ],
                rehypePlugins: [
                    [
                        external_rehype_katex_default(),
                        {
                            output: 'mathml',
                            trust: false,
                            strict: true,
                            throwOnError: false
                        }
                    ]
                ],
                remarkRehypeOptions: {
                    footnoteLabel: _({
                        id: 'autopilot-chat.message.footnote-label'
                    })
                },
                components: components,
                children: content
            })
        }), [
        content,
        components,
        _
    ]);
}
const AutopilotChatMarkdownRenderer = /*#__PURE__*/ external_react_default().memo(AutopilotChatMarkdownRendererComponent);
exports.AutopilotChatMarkdownRenderer = __webpack_exports__.AutopilotChatMarkdownRenderer;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AutopilotChatMarkdownRenderer"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
