UNPKG

@nlux/react

Version:

nlux React is a library for building conversational AI interfaces, with support for OpenAI, HuggingFace, and more.

1 lines 97.3 kB
import{useEffect as e,useRef as t,useMemo as n,useState as r,useImperativeHandle as s,useCallback as o,Component as i,isValidElement as a,forwardRef as c,createRef as l,createContext as u,useContext as d,lazy as p,Suspense as m}from"react";import{jsx as h,jsxs as g,Fragment as f}from"react/jsx-runtime";import{createAiContext as k,predefinedContextSize as x}from"@nlux/core";var w=Object.prototype.hasOwnProperty;function b(e,t){for(let n of e.keys())if(v(n,t))return n}function v(e,t){var n,r,s;if(e===t)return!0;if(e&&t&&(n=e.constructor)===t.constructor){if(n===Date)return e.getTime()===t.getTime();if(n===RegExp)return e.toString()===t.toString();if(n===Array){if((r=e.length)===t.length)for(;r--&&v(e[r],t[r]););return-1===r}if(n===Set){if(e.size!==t.size)return!1;for(r of e){if((s=r)&&"object"==typeof s&&!(s=b(t,s)))return!1;if(!t.has(s))return!1}return!0}if(n===Map){if(e.size!==t.size)return!1;for(r of e){if((s=r[0])&&"object"==typeof s&&!(s=b(t,s)))return!1;if(!v(r[1],t.get(s)))return!1}return!0}if(n===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(n===DataView){if((r=e.byteLength)===t.byteLength)for(;r--&&e.getInt8(r)===t.getInt8(r););return-1===r}if(ArrayBuffer.isView(e)){if((r=e.byteLength)===t.byteLength)for(;r--&&e[r]===t[r];);return-1===r}if(!n||"object"==typeof e){for(n in r=0,e){if(w.call(e,n)&&++r&&!w.call(t,n))return!1;if(!(n in t)||!v(e[n],t[n]))return!1}return Object.keys(t).length===r}}return e!=e&&t!=t}const y=e=>{const t=new Set;let n=!1,r=null,s=null;const o=()=>{if(n)return;if(0===t.size)return;n=!0;const o=t.values().next().value;t.delete(o),r=(({message:e})=>{const t=document.createElement("div");t.classList.add("nlux-comp-exceptionItem");const n=document.createElement("span");return n.classList.add("nlux-comp-exp_itm_msg"),n.append(document.createTextNode(e)),t.append(n),t})(o),e.append(r),s=setTimeout(i,3e3)},i=()=>{r?.classList.add("nlux-comp-exceptionItem--hiding"),s=setTimeout((()=>{n=!1,r?.remove(),r=null,o()}),500)};return{displayException:e=>{t.add({message:e}),n||o()},destroy:()=>{t.clear(),r?.remove(),s&&clearTimeout(s)}}},S=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),A=e=>{"string"!=typeof e?e&&"function"==typeof e.toString?console.warn(`[nlux] ${e.toString()}`):console.warn("[nlux]"):console.warn(`[nlux] ${e}`)},C=[],T=e=>{C.includes(e)||(C.push(e),A(e))},R={typing:"nlux-composer--typing","submitting-prompt":"nlux-composer--submitting","submitting-conversation-starter":"nlux-composer--submitting",waiting:"nlux-composer--waiting"},I=(e,t)=>{if(!t||"Enter"===t){const t="Enter"===e.key&&!e.nativeEvent.isComposing,n=e.altKey||e.ctrlKey||e.metaKey||e.shiftKey;return t&&!n}if("CommandEnter"===t){if("Enter"===e.key&&(e.getModifierState("Control")||e.getModifierState("Meta")))return!0}return!1},E=()=>h("div",{className:"nlux-comp-cancelIcon",children:h("div",{className:"nlux-comp-cancelIcon-container"})}),M=()=>h("div",{className:"nlux-comp-sendIcon",children:h("div",{className:"nlux-comp-sendIcon-container"})}),B=["submitting-prompt","submitting-edit","submitting-conversation-starter","submitting-external-message"],O=r=>{const s=`nlux-comp-composer ${R[r.status]||""}`,o=B.includes(r.status),i=!r.hasValidInput||"waiting"===r.status||B.includes(r.status),a="typing"===r.status||"waiting"===r.status,c=!(!0===r.hideStopButton)&&(B.includes(r.status)||"waiting"===r.status),l=t(null);e((()=>{"typing"===r.status&&r.autoFocus&&l.current&&l.current.focus()}),[r.status,r.autoFocus,l.current]);const u=n((()=>e=>{r.onChange?.(e.target.value)}),[r.onChange]),d=n((()=>()=>{r.onSubmit?.()}),[r.onSubmit]),p=n((()=>e=>{I(e,r.submitShortcut)&&(e.preventDefault(),d())}),[d,r.submitShortcut]);return e((()=>{if(!l.current)return;const e=()=>{const e=l.current;e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)};return l.current.addEventListener("input",e),()=>{l.current?.removeEventListener("input",e)}}),[l.current]),g("div",{className:s,children:[h("textarea",{tabIndex:0,ref:l,disabled:o,placeholder:r.placeholder,value:r.prompt,onChange:u,onKeyDown:p,"aria-label":r.placeholder}),!c&&g("button",{tabIndex:0,disabled:i,onClick:()=>r.onSubmit(),"aria-label":"Send",children:[a&&h(M,{}),!a&&r.Loader]}),c&&h("button",{tabIndex:0,onClick:r.onCancel,"aria-label":"Cancel",children:h(E,{})})]})},L=(e,t)=>"assistant"===e?t?.assistant?.name??"Assistant":"user"===e?t?.user?.name??"User":"",z=e=>{const t="nlux-chatSegment";return"complete"===e?`${t} nlux-chatSegment--complete`:"error"===e?`${t} nlux-chatSegment--error`:`${t} nlux-chatSegment--active`},P={received:"nlux_msg_received",sent:"nlux_msg_sent"},H={streaming:"nlux_msg_streaming",complete:"nlux_msg_complete"},D=e=>{if(!(e instanceof HTMLButtonElement))return;if("true"===e.dataset.clickListenerSet)return;let t=!1;const n=e.nextElementSibling;e.addEventListener("click",(()=>{if(t||!n)return;const r=n.innerText;navigator.clipboard.writeText(r??""),t=!0,e.classList.add("clicked"),setTimeout((()=>{t=!1,e.classList.remove("clicked")}),1e3)})),e.dataset.clickListenerSet="true"},N=e=>{const t="nlux-comp-copyButton";e instanceof HTMLButtonElement&&e.classList.contains(t)?D(e):e.querySelectorAll(`.${t}`).forEach(D)};function q(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let Q={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function U(e){Q=e}var Y=Object.defineProperty,X=(e,t,n)=>((e,t,n)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class Z{constructor(e){X(this,"options"),this.options=e||Q}postprocess(e){return e}preprocess(e){return e}processAllTokens(e){return e}}X(Z,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));const F=/[&<>"']/,K=new RegExp(F.source,"g"),W=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,j=new RegExp(W.source,"g"),J={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},G=e=>J[e];function V(e,t){if(t){if(F.test(e))return e.replace(K,G)}else if(W.test(e))return e.replace(j,G);return e}const $=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function _(e){return e.replace($,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const ee=/(^|[^\[])\^/g;function te(e,t){let n="string"==typeof e?e:e.source;t=t||"";const r={replace:(e,t)=>{let s="string"==typeof t?t:t.source;return s=s.replace(ee,"$1"),n=n.replace(e,s),r},getRegex:()=>new RegExp(n,t)};return r}function ne(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return null}return e}const re={exec:()=>null};function se(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let r=!1,s=t;for(;--s>=0&&"\\"===n[s];)r=!r;return r?"|":" |"})).split(/ \|/);let r=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(/\\\|/g,"|");return n}function oe(e,t,n){const r=e.length;if(0===r)return"";let s=0;for(;s<r;){const o=e.charAt(r-s-1);if(o!==t||n){if(o===t||!n)break;s++}else s++}return e.slice(0,r-s)}const ie=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ae=/(?:[*+-]|\d{1,9}[.)])/,ce=te(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,ae).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),le=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ue=/(?!\s*\])(?:\\.|[^\[\]\\])+/,de=te(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",ue).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),pe=te(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ae).getRegex(),me="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",he=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ge=te("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",he).replace("tag",me).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),fe=te(le).replace("hr",ie).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",me).getRegex(),ke={blockquote:te(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",fe).getRegex(),code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,def:de,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:ie,html:ge,lheading:ce,list:pe,newline:/^(?: *(?:\n|$))+/,paragraph:fe,table:re,text:/^[^\n]+/},xe=te("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ie).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",me).getRegex(),we={...ke,table:xe,paragraph:te(le).replace("hr",ie).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",xe).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",me).getRegex()},be={...ke,html:te("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",he).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:re,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:te(le).replace("hr",ie).replace("heading"," *#{1,6} *[^\n]").replace("lheading",ce).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ve=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ye=/^( {2,}|\\)\n(?!\s*$)/,Se="\\p{P}\\p{S}",Ae=te(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,Se).getRegex(),Ce=te(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Se).getRegex(),Te=te("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Se).getRegex(),Re=te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Se).getRegex(),Ie=te(/\\([punct])/,"gu").replace(/punct/g,Se).getRegex(),Ee=te(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Me=te(he).replace("(?:--\x3e|$)","--\x3e").getRegex(),Be=te("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Me).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Oe=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Le=te(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",Oe).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ze=te(/^!?\[(label)\]\[(ref)\]/).replace("label",Oe).replace("ref",ue).getRegex(),Pe=te(/^!?\[(ref)\](?:\[\])?/).replace("ref",ue).getRegex(),He={_backpedal:re,anyPunctuation:Ie,autolink:Ee,blockSkip:/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,br:ye,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:re,emStrongLDelim:Ce,emStrongRDelimAst:Te,emStrongRDelimUnd:Re,escape:ve,link:Le,nolink:Pe,punctuation:Ae,reflink:ze,reflinkSearch:te("reflink|nolink(?!\\()","g").replace("reflink",ze).replace("nolink",Pe).getRegex(),tag:Be,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:re},De={...He,link:te(/^!?\[(label)\]\((.*?)\)/).replace("label",Oe).getRegex(),reflink:te(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Oe).getRegex()},Ne={...He,escape:te(ve).replace("])","~|])").getRegex(),url:te(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},qe={...Ne,br:te(ye).replace("{2,}","*").getRegex(),text:te(Ne.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Qe={normal:ke,gfm:we,pedantic:be},Ue={normal:He,gfm:Ne,breaks:qe,pedantic:De};var Ye=Object.defineProperty,Xe=(e,t,n)=>((e,t,n)=>t in e?Ye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);function Ze(e,t,n,r){const s=t.href,o=t.title?V(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if("!"!==e[0].charAt(0)){r.state.inLink=!0;const e={type:"link",raw:n,href:s,title:o,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,e}return{type:"image",raw:n,href:s,title:o,text:V(i)}}class Fe{constructor(e){Xe(this,"lexer"),Xe(this,"options"),Xe(this,"rules"),this.options=e||Q}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=V(t[1]),n="mailto:"+e):(e=V(t[1]),n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,"\n $1");e=oe(e.replace(/^ *>[ \t]?/gm,""),"\n");const n=this.lexer.state.top;this.lexer.state.top=!0;const r=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:r,text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:oe(e,"\n")}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),r=/^ /.test(e)&&/ $/.test(e);return n&&r&&(e=e.substring(1,e.length-1)),e=V(e,!0),{type:"codespan",raw:t[0],text:e}}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:r}}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r)return;if(r[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(r[1]||r[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const n=[...r[0]].length-1;let s,o,i=n,a=0;const c="*"===r[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);null!=(r=c.exec(t));){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(o=[...s].length,r[3]||r[4]){i+=o;continue}if((r[5]||r[6])&&n%3&&!((n+o)%3)){a+=o;continue}if(i-=o,i>0)continue;o=Math.min(o,o+i+a);const t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+o);if(Math.min(n,o)%2){const e=c.slice(1,-1);return{type:"em",raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}const l=c.slice(2,-2);return{type:"strong",raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:V(t[1])}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const r=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=r.length?e.slice(r.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=oe(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}html(e){const t=this.rules.block.html.exec(e);if(t){return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){let e;return e=this.lexer.state.inRawBlock?t[0]:V(t[0]),{type:"text",raw:t[0],text:e}}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^</.test(e)){if(!/>$/.test(e))return;const t=oe(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let r=0;r<e.length;r++)if("\\"===e[r])r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return-1}(t[2],"()");if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],r="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(e)?n.slice(1):n.slice(1,-1)),Ze(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:r?r.replace(this.rules.inline.anyPunctuation,"$1"):r},t[0],this.lexer)}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const r=n.length>1,s={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");const o=new RegExp(`^( {0,3}${n})((?:[\t ][^\\n]*)?(?:\\n|$))`);let i="",a="",c=!1;for(;e;){let n=!1;if(!(t=o.exec(e)))break;if(this.rules.block.hr.test(e))break;i=t[0],e=e.substring(i.length);let r=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),l=e.split("\n",1)[0],u=0;this.options.pedantic?(u=2,a=r.trimStart()):(u=t[2].search(/[^ ]/),u=u>4?1:u,a=r.slice(u),u+=t[1].length);let d=!1;if(!r&&/^ *$/.test(l)&&(i+=l+"\n",e=e.substring(l.length+1),n=!0),!n){const t=new RegExp(`^ {0,${Math.min(3,u-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),n=new RegExp(`^ {0,${Math.min(3,u-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),s=new RegExp(`^ {0,${Math.min(3,u-1)}}(?:\`\`\`|~~~)`),o=new RegExp(`^ {0,${Math.min(3,u-1)}}#`);for(;e;){const c=e.split("\n",1)[0];if(l=c,this.options.pedantic&&(l=l.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),s.test(l))break;if(o.test(l))break;if(t.test(l))break;if(n.test(e))break;if(l.search(/[^ ]/)>=u||!l.trim())a+="\n"+l.slice(u);else{if(d)break;if(r.search(/[^ ]/)>=4)break;if(s.test(r))break;if(o.test(r))break;if(n.test(r))break;a+="\n"+l}d||l.trim()||(d=!0),i+=c+"\n",e=e.substring(c.length+1),r=l.slice(u)}}s.loose||(c?s.loose=!0:/\n *\n *$/.test(i)&&(c=!0));let p,m=null;this.options.gfm&&(m=/^\[[ xX]\] /.exec(a),m&&(p="[ ] "!==m[0],a=a.replace(/^\[[ xX]\] +/,""))),s.items.push({type:"list_item",raw:i,task:!!m,checked:p,loose:!1,text:a,tokens:[]}),s.raw+=i}s.items[s.items.length-1].raw=i.trimEnd(),s.items[s.items.length-1].text=a.trimEnd(),s.raw=s.raw.trimEnd();for(let e=0;e<s.items.length;e++)if(this.lexer.state.top=!1,s.items[e].tokens=this.lexer.blockTokens(s.items[e].text,[]),!s.loose){const t=s.items[e].tokens.filter((e=>"space"===e.type)),n=t.length>0&&t.some((e=>/\n.*\n/.test(e.raw)));s.loose=n}if(s.loose)for(let e=0;e<s.items.length;e++)s.items[e].loose=!0;return s}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(/\s+/g," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return Ze(n,e,n[0],this.lexer)}}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!/[:|]/.test(t[2]))return;const n=se(t[1]),r=t[2].replace(/^\||\| *$/g,"").split("|"),s=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[],o={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(const e of r)/^ *-+: *$/.test(e)?o.align.push("right"):/^ *:-+: *$/.test(e)?o.align.push("center"):/^ *:-+ *$/.test(e)?o.align.push("left"):o.align.push(null);for(const e of n)o.header.push({text:e,tokens:this.lexer.inline(e)});for(const e of s)o.rows.push(se(e,o.header.length).map((e=>({text:e,tokens:this.lexer.inline(e)}))));return o}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=V(t[0]),n="mailto:"+e;else{let r;do{r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(r!==t[0]);e=V(t[0]),n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}}var Ke=Object.defineProperty,We=(e,t,n)=>((e,t,n)=>t in e?Ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class je{constructor(e){We(this,"options"),We(this,"state"),We(this,"tokens"),We(this,"inlineQueue"),We(this,"tokenizer"),this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Q,this.options.tokenizer=this.options.tokenizer||new Fe,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const t={block:Qe.normal,inline:Ue.normal};this.options.pedantic?(t.block=Qe.pedantic,t.inline=Ue.pedantic):this.options.gfm&&(t.block=Qe.gfm,this.options.breaks?t.inline=Ue.breaks:t.inline=Ue.gfm),this.tokenizer.rules=t}static get rules(){return{block:Qe,inline:Ue}}static lex(e,t){return new je(t).lex(e)}static lexInline(e,t){return new je(t).inlineTokens(e)}blockTokens(e,t=[]){let n,r,s,o;for(e=this.options.pedantic?e.replace(/\t/g," ").replace(/^ +$/gm,""):e.replace(/^( *)(\t+)/gm,((e,t,n)=>t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((r=>!!(n=r.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),r=t[t.length-1],!r||"paragraph"!==r.type&&"text"!==r.type?t.push(n):(r.raw+="\n"+n.raw,r.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=r.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),r=t[t.length-1],!r||"paragraph"!==r.type&&"text"!==r.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(r.raw+="\n"+n.raw,r.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=r.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(s=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let r;this.options.extensions.startBlock.forEach((e=>{r=e.call({lexer:this},n),"number"==typeof r&&r>=0&&(t=Math.min(t,r))})),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(s)))r=t[t.length-1],o&&"paragraph"===r.type?(r.raw+="\n"+n.raw,r.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=r.text):t.push(n),o=s.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),r=t[t.length-1],r&&"text"===r.type?(r.raw+="\n"+n.raw,r.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=r.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,r,s,o,i,a,c=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(o=this.tokenizer.rules.inline.reflinkSearch.exec(c));)e.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(c=c.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+c.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(o=this.tokenizer.rules.inline.blockSkip.exec(c));)c=c.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+c.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(o=this.tokenizer.rules.inline.anyPunctuation.exec(c));)c=c.slice(0,o.index)+"++"+c.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(i||(a=""),i=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((r=>!!(n=r.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),r=t[t.length-1],r&&"text"===n.type&&"text"===r.type?(r.raw+=n.raw,r.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),r=t[t.length-1],r&&"text"===n.type&&"text"===r.type?(r.raw+=n.raw,r.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,c,a))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e))){if(s=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let r;this.options.extensions.startInline.forEach((e=>{r=e.call({lexer:this},n),"number"==typeof r&&r>=0&&(t=Math.min(t,r))})),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(s))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(a=n.raw.slice(-1)),i=!0,r=t[t.length-1],r&&"text"===r.type?(r.raw+=n.raw,r.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}lex(e){e=e.replace(/\r\n|\r/g,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}}var Je=Object.defineProperty,Ge=(e,t,n)=>((e,t,n)=>t in e?Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);class Ve{constructor(e){Ge(this,"options"),this.options=e||Q}blockquote(e){return`<blockquote>\n${e}</blockquote>\n`}br(){return"<br>"}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}code(e,t,n){const r=(t||"").match(/^\S*/)?.[0];return e=e.replace(/\n$/,"")+"\n",r?'<pre><code class="language-'+V(r)+'">'+(n?e:V(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:V(e,!0))+"</code></pre>\n"}codespan(e){return`<code>${e}</code>`}del(e){return`<del>${e}</del>`}em(e){return`<em>${e}</em>`}heading(e,t,n){return`<h${t}>${e}</h${t}>\n`}hr(){return"<hr>\n"}html(e,t){return e}image(e,t,n){const r=ne(e);if(null===r)return n;let s=`<img src="${e=r}" alt="${n}"`;return t&&(s+=` title="${t}"`),s+=">",s}link(e,t,n){const r=ne(e);if(null===r)return n;let s='<a href="'+(e=r)+'"';return t&&(s+=' title="'+t+'"'),s+=">"+n+"</a>",s}list(e,t,n){const r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+r+">\n"}listitem(e,t,n){return`<li>${e}</li>\n`}paragraph(e){return`<p>${e}</p>\n`}strong(e){return`<strong>${e}</strong>`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>\n`}tablerow(e){return`<tr>\n${e}</tr>\n`}text(e){return e}}class $e{br(){return""}codespan(e){return e}del(e){return e}em(e){return e}html(e){return e}image(e,t,n){return""+n}link(e,t,n){return""+n}strong(e){return e}text(e){return e}}var _e=Object.defineProperty,et=(e,t,n)=>((e,t,n)=>t in e?_e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class tt{constructor(e){et(this,"options"),et(this,"renderer"),et(this,"textRenderer"),this.options=e||Q,this.options.renderer=this.options.renderer||new Ve,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new $e}static parse(e,t){return new tt(t).parse(e)}static parseInline(e,t){return new tt(t).parseInline(e)}parse(e,t=!0){let n="";for(let r=0;r<e.length;r++){const s=e[r];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){const e=s,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){n+=t||"";continue}}switch(s.type){case"space":continue;case"hr":n+=this.renderer.hr();continue;case"heading":{const e=s;n+=this.renderer.heading(this.parseInline(e.tokens),e.depth,_(this.parseInline(e.tokens,this.textRenderer)));continue}case"code":{const e=s;n+=this.renderer.code(e.text,e.lang,!!e.escaped);continue}case"table":{const e=s;let t="",r="";for(let t=0;t<e.header.length;t++)r+=this.renderer.tablecell(this.parseInline(e.header[t].tokens),{header:!0,align:e.align[t]});t+=this.renderer.tablerow(r);let o="";for(let t=0;t<e.rows.length;t++){const n=e.rows[t];r="";for(let t=0;t<n.length;t++)r+=this.renderer.tablecell(this.parseInline(n[t].tokens),{header:!1,align:e.align[t]});o+=this.renderer.tablerow(r)}n+=this.renderer.table(t,o);continue}case"blockquote":{const e=s,t=this.parse(e.tokens);n+=this.renderer.blockquote(t);continue}case"list":{const e=s,t=e.ordered,r=e.start,o=e.loose;let i="";for(let t=0;t<e.items.length;t++){const n=e.items[t],r=n.checked,s=n.task;let a="";if(n.task){const e=this.renderer.checkbox(!!r);o?n.tokens.length>0&&"paragraph"===n.tokens[0].type?(n.tokens[0].text=e+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&"text"===n.tokens[0].tokens[0].type&&(n.tokens[0].tokens[0].text=e+" "+n.tokens[0].tokens[0].text)):n.tokens.unshift({type:"text",text:e+" "}):a+=e+" "}a+=this.parse(n.tokens,o),i+=this.renderer.listitem(a,s,!!r)}n+=this.renderer.list(i,t,r);continue}case"html":{const e=s;n+=this.renderer.html(e.text,e.block);continue}case"paragraph":{const e=s;n+=this.renderer.paragraph(this.parseInline(e.tokens));continue}case"text":{let o=s,i=o.tokens?this.parseInline(o.tokens):o.text;for(;r+1<e.length&&"text"===e[r+1].type;)o=e[++r],i+="\n"+(o.tokens?this.parseInline(o.tokens):o.text);n+=t?this.renderer.paragraph(i):i;continue}default:{const e='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}parseInline(e,t){t=t||this.renderer;let n="";for(let r=0;r<e.length;r++){const s=e[r];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]){const e=this.options.extensions.renderers[s.type].call({parser:this},s);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){n+=e||"";continue}}switch(s.type){case"escape":{const e=s;n+=t.text(e.text);break}case"html":{const e=s;n+=t.html(e.text);break}case"link":{const e=s;n+=t.link(e.href,e.title,this.parseInline(e.tokens,t));break}case"image":{const e=s;n+=t.image(e.href,e.title,e.text);break}case"strong":{const e=s;n+=t.strong(this.parseInline(e.tokens,t));break}case"em":{const e=s;n+=t.em(this.parseInline(e.tokens,t));break}case"codespan":{const e=s;n+=t.codespan(e.text);break}case"br":n+=t.br();break;case"del":{const e=s;n+=t.del(this.parseInline(e.tokens,t));break}case"text":{const e=s;n+=t.text(e.text);break}default:{const e='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}}var nt,rt,st,ot=Object.defineProperty,it=e=>{throw TypeError(e)},at=(e,t,n)=>((e,t,n)=>t in e?ot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n),ct=(e,t,n)=>(((e,t,n)=>{t.has(e)||it("Cannot "+n)})(e,t,"access private method"),n);nt=new WeakSet,rt=function(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+V(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}},st=function(e,t){return(n,r)=>{const s={...r},o={...this.defaults,...s};!0===this.defaults.async&&!1===s.async&&(o.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),o.async=!0);const i=ct(this,nt,rt).call(this,!!o.silent,!!o.async);if(null==n)return i(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof n)return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o),o.async)return Promise.resolve(o.hooks?o.hooks.preprocess(n):n).then((t=>e(t,o))).then((e=>o.hooks?o.hooks.processAllTokens(e):e)).then((e=>o.walkTokens?Promise.all(this.walkTokens(e,o.walkTokens)).then((()=>e)):e)).then((e=>t(e,o))).then((e=>o.hooks?o.hooks.postprocess(e):e)).catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let r=e(n,o);o.hooks&&(r=o.hooks.processAllTokens(r)),o.walkTokens&&this.walkTokens(r,o.walkTokens);let s=t(r,o);return o.hooks&&(s=o.hooks.postprocess(s)),s}catch(e){return i(e)}}};const lt=new class{constructor(...e){var t,n,r;t=this,(n=nt).has(t)?it("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(t):n.set(t,r),at(this,"Hooks",Z),at(this,"Lexer",je),at(this,"Parser",tt),at(this,"Renderer",Ve),at(this,"TextRenderer",$e),at(this,"Tokenizer",Fe),at(this,"defaults",{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}),at(this,"options",this.setOptions),at(this,"parse",ct(this,nt,st).call(this,je.lex,tt.parse)),at(this,"parseInline",ct(this,nt,st).call(this,je.lexInline,tt.parseInline)),this.use(...e)}lexer(e,t){return je.lex(e,t??this.defaults)}parser(e,t){return tt.parse(e,t??this.defaults)}setOptions(e){return this.defaults={...this.defaults,...e},this}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let r=e.renderer.apply(this,t);return!1===r&&(r=n.apply(this,t)),r}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new Ve(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if("options"===n)continue;const r=n,s=e.renderer[r],o=t[r];t[r]=(...e)=>{let n=s.apply(t,e);return!1===n&&(n=o.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new Fe(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const r=n,s=e.tokenizer[r],o=t[r];t[r]=(...e)=>{let n=s.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new Z;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if("options"===n)continue;const r=n,s=e.hooks[r],o=t[r];Z.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async)return Promise.resolve(s.call(t,e)).then((e=>o.call(t,e)));const n=s.call(t,e);return o.call(t,n)}:t[r]=(...e)=>{let n=s.apply(t,e);return!1===n&&(n=o.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}walkTokens(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{const e=r;for(const r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(const r of e.rows)for(const e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{const e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((r=>{const s=e[r].flat(1/0);n=n.concat(this.walkTokens(s,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}};function ut(e,t){return lt.parse(e,t)}ut.options=ut.setOptions=function(e){return lt.setOptions(e),ut.defaults=lt.defaults,U(ut.defaults),ut},ut.getDefaults=q,ut.defaults=Q,ut.use=function(...e){return lt.use(...e),ut.defaults=lt.defaults,U(ut.defaults),ut},ut.walkTokens=function(e,t){return lt.walkTokens(e,t)},ut.parseInline=lt.parseInline,ut.Parser=tt,ut.parser=tt.parse,ut.Renderer=Ve,ut.TextRenderer=$e,ut.Lexer=je,ut.lexer=je.lex,ut.Tokenizer=Fe,ut.Hooks=Z,ut.parse=ut;const dt=(e,t)=>{const{showCodeBlockCopyButton:n,markdownLinkTarget:r,syntaxHighlighter:s,htmlSanitizer:o}=t||{},i=ut(e,{async:!1,breaks:!0});if("string"!=typeof i)throw new Error("Markdown parsing failed");const a=document.createElement("div");return a.innerHTML=o?o(i):i,a.querySelectorAll("pre").forEach((e=>{const n=document.createElement("div");n.className="code-block";const r=e.querySelector("code");if(!r){const t=e.innerHTML;return n.innerHTML=o?o(t):t,void e.replaceWith(n)}let i;for(let e=0;e<r.classList.length;e++){const t=r.classList[e];if(t.startsWith("language-")){i=t.slice(9);break}}const a=document.createElement("pre"),c="<div>"+r.innerHTML+"</div>";if(a.innerHTML=t?.htmlSanitizer?t.htmlSanitizer(c):c,i&&(a.setAttribute("data-language",i),s)){const e="<div>"+s.createHighlighter()(r.textContent||"",i)+"</div>";a.innerHTML=o?o(e):e,a.className="highlighter-dark"}(e=>{e.replaceChildren()})(n),n.appendChild(a),e.replaceWith(n)})),!1!==n&&a.querySelectorAll(".code-block").forEach((e=>{if(!e.querySelector("pre"))return;if(e.previousElementSibling?.classList.contains("nlux-comp-copyButton"))return;const t="Copy code block to clipboard",n=document.createElement("button");n.classList.add("nlux-comp-copyButton"),n.setAttribute("aria-label",t),n.setAttribute("title",t);const r=document.createElement("span");r.classList.add("icon-copy"),n.appendChild(r),e.appendChild(n)})),"self"!==r&&a.querySelectorAll("a").forEach((e=>{e.setAttribute("target","_blank")})),a.innerHTML},pt="nlux-comp-message",mt={received:"nlux-comp-chatItem--received",sent:"nlux-comp-chatItem--sent"},ht="nlux-comp-chatItem--bubblesLayout",gt="nlux-comp-chatItem--listLayout",ft=(e,t)=>{let n=!1;const{onComplete:r}=t||{},s=[],o="timeout"===(t?.skipStreamingAnimation?"timeout":"animationFrame")?e=>setTimeout(e,0):e=>requestAnimationFrame(e);const i=document.createElement("div");i.classList.add("md-in-progress"),e.append(i);const a=()=>{for(;i.firstChild;){const e=i.firstChild;e instanceof HTMLElement&&N(e),i.before(e)}},c=!t?.skipStreamingAnimation&&t?.streamingAnimationSpeed&&t.streamingAnimationSpeed>=0?t.streamingAnimationSpeed:t?.skipStreamingAnimation?0:8,l={timeSinceLastProcessing:(new Date).getTime(),currentMarkdown:"",previousHtml:void 0};let u=setInterval((()=>{const e=(new Date).getTime(),c="never"!==t?.waitTimeBeforeStreamCompletion;if(0===s.length&&c){const s="number"==typeof t?.waitTimeBeforeStreamCompletion?t.waitTimeBeforeStreamCompletion:2e3;return void((n||e-l.timeSinceLastProcessing>s)&&(n=!0,u&&(clearInterval(u),u=void 0),a(),i.remove(),r?.()))}l.timeSinceLastProcessing=e;const d=s.shift();void 0!==d&&"string"==typeof d&&o((()=>{const e=l.currentMarkdown+d,n=dt(e,t).trim();if("string"!=typeof n)return l.currentMarkdown=l.currentMarkdown.slice(0,-d.length),void A("Markdown parsing failed");if(l.previousHtml&&n.length>l.previousHtml.length&&n.startsWith(l.previousHtml)){a();const e=n.slice(l.previousHtml.length).trim();i.innerHTML=t?.htmlSanitizer?t.htmlSanitizer(e):e,l.currentMarkdown=d,l.previousHtml=void 0}else i.innerHTML=t?.htmlSanitizer?t.htmlSanitizer(n):n,l.currentMarkdown=e,l.previousHtml=n}))}),c);return{next:e=>{if(n)A("Stream is already complete. No more chunks can be added");else for(const t of e)s.push(t)},complete:()=>{s.push("\n"),n=!0},cancel:()=>{u&&(clearInterval(u),u=void 0),n=!0,i.remove()},error:()=>{n=!0}}},kt=function(n,o){const{uid:i,status:a,responseRenderer:c,markdownOptions:l,initialMarkdownMessage:u,markdownContainersController:d}=n,[p,m]=r([]),f=t(null),k=t(null),x=t(null),w=t(null),[b,v]=r();e((()=>{f.current!==k.current&&(k.current=f.current,v(f.current||void 0))})),e((()=>{if(b){const e=d.getStreamingDomElement(i);b.append(e)}}),[b]),e((()=>{w.current=e=>{m((t=>[...t,e]))}}),[m]),e((()=>{const e=d.getStreamingDomElement(i);return x.current=ft(e,{syntaxHighlighter:l?.syntaxHighlighter,htmlSanitizer:l?.htmlSanitizer,markdownLinkTarget:l?.markdownLinkTarget,showCodeBlockCopyButton:l?.showCodeBlockCopyButton,skipStreamingAnimation:l?.skipStreamingAnimation,streamingAnimationSpeed:l?.streamingAnimationSpeed,waitTimeBeforeStreamCompletion:l?.waitTimeBeforeStreamCompletion,onComplete:l?.onStreamComplete}),u&&x.current.next(u),()=>{d.deleteStreamingDomElement(i)}}),[]),e((()=>()=>{k.current=null,x.current=null,w.current=null,v(void 0)}),[]),s(o,(()=>({streamChunk:e=>{w.current&&w.current?.(e),"string"==typeof e&&x.current?.next(e)},completeStream:()=>{x.current?.complete()},cancelStream:()=>{x.current?.cancel()}})),[]);const y=c||void 0;return g("div",{className:`${pt} ${H[a]} ${P.received}`,children:[y&&h(y,{uid:i,status:a,containerRef:f,content:p,contentType:"text",serverResponse:[],dataTransferMode:"stream"}),!y&&h("div",{className:"nlux-markdownStream-root",ref:f})]})},xt=r=>{const{markdownOptions:s}=r,i=t(null),a=n((()=>r.content?dt(r.content,{syntaxHighlighter:s?.syntaxHighlighter,htmlSanitizer:s?.htmlSanitizer,markdownLinkTarget:s?.markdownLinkTarget,showCodeBlockCopyButton:s?.showCodeBlockCopyButton}):""),[r.content,s?.markdownLinkTarget,s?.syntaxHighlighter,s?.htmlSanitizer,s?.showCodeBlockCopyButton]);e((()=>{i.current&&!1!==s?.showCodeBlockCopyButton&&N(i.current)}),[a,i.current,s?.showCodeBlockCopyButton]);const c=n((()=>s?.htmlSanitizer?s.htmlSanitizer(a):a),[a,s?.htmlSanitizer]),l=o((e=>{if(!r.canResubmit)return;const t=e.currentTarget.textContent;return t?I(e,r.submitShortcutKey)?(e.preventDefault(),void(r.onResubmit&&r.onResubmit(t))):void("Escape"===e.key&&(e.preventDefault(),e.currentTarget.textContent=r.content,e.currentTarget.blur())):void 0}),[r.canResubmit,r.onResubmit,r.content]),u=o((e=>{r.canResubmit&&(e.preventDefault(),e.currentTarget.textContent=r.content,e.currentTarget.blur())}),[r.canResubmit,r.content]),d=o((e=>{if(!r.canResubmit)return;e.preventDefault();const t=document.createRange();t.selectNodeContents(e.currentTarget);const n=window.getSelection();n?.removeAllRanges(),n?.addRange(t)}),[r.canResubmit]),p=r.canResubmit?"editable-markdown-container":"";return h(wt,{children:h("div",{className:"nlux-markdownStream-root"+(p?` ${p}`:""),children:h("div",{className:"nlux-markdown-container",ref:i,dangerouslySetInnerHTML:{__html:c},contentEditable:r.canResubmit,onKeyDown:l,onBlur:u,onFocus:d})})})};class wt extends i{constructor(){super(...arguments),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){A("Markdown rendering error occurred. This could be due to a malformed markdown content, or it could be because the page requires an HTML sanitizer. Please check the error message for more details and consider configuring NLUX with a compatible sanitizer."),this.props.onMarkdownRenderingError&&this.props.onMarkdownRenderingError(e)}render(){return this.state.hasError?null:this.props.children}}const bt=e=>h(wt,{children:h(xt,{...e})}),vt=e=>{const t="string"==typeof e.avatar,n=!t&&a(e.avatar);return g("div",{className:"nlux-comp-avatar",children:[n&&e.avatar,!n&&t&&h("div",{className:"nlux-comp-avatarContainer",children:e.avatar&&h("div",{className:"nlux-comp-avatarPicture",style:{backgroundImage:`url("${encodeURI(e.avatar)}")`}})})]})},yt=function(r,i){const l=t(null);s(i,(()=>({streamChunk:e=>setTimeout((()=>l?.current?.streamChunk(e))),completeStream:()=>setTimeout((()=>l?.current?.completeStream())),cancelStream:()=>l?.current?.cancelStream()})),[]);const u="server-component"===r.contentType,d="received"===r.direction,p="sent"===r.direction,m="stream"===r.dataTransferMode,k=r.isPartOfInitialSegment,x=o((()=>r.onMarkdownStreamRendered?.(r.uid)),[r.uid]);e((()=>{m||u||k||r.onMarkdownStreamRendered?.(r.uid)}),[]);const w=function(e){const{uid:t,status:n,dataTransferMode:r,contentType:s,fetchedContent:o,streamedContent:i,streamedServerResponse:c,fetchedServerResponse:l,direction:u,messageOptions:d}=e;if(void 0!==d?.responseRenderer){if("stream"===r){const e={uid:t,status:n,dataTransferMode:r,contentType:s,content:i??[],serverResponse:c??[]};return()=>{const t=d.responseRenderer;return h(t,{...e})}}const e=a(o),u={uid:t,status:"complete",dataTransferMode:r,contentType:s,content:o?e?[]:[o]:[],serverComponent:e?o:void 0,serverResponse:l?[l]:[]};return()=>{const e=d.responseRenderer;return h(e,{...u})}}if("sent"===u){if("string"==typeof o){const e=o;return()=>h(f,{children:e})}return()=>""}if("string"==typeof o){const e=o;return()=>h(bt,{messageUid:t,content:e,markdown